branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep># Direct-database
## Easy to use
A simple database for optimum data. It is intended for those who do not want to create tables and write queries in mysql.
### Create and connect
Syntax
```
$database = new Database([ database name ],[ username ],[ password ])
```
Example
```
$base = new Database("mydatabase","myusername","mypassword");
```
### Insert
If the table is not created the insert method will create it. Just enter the column names and values
Syntax
```
$table = "table name";
$values = ["row1" => "value1","row2" => "value2","row3" => "value3" ];
$base->insert($table,$values);
```
Example
```
$table = "user"; // table name
$values = ["name" => "John","surname" => "Wain","age" => "23" ];
$base->insert($table,$values);
```
### Select
Syntax
```
$table = "table name";
$condition='$row->id == "value" '; // '' for no condition
$order = 'd'; //descedenting order, '' ascedenting order
$start = offset;
$per_page = limit; // for all data $per_page = "";
$query = $base->select($table,$condition,$order,$start,$per_page);
echo "Results - select : ".$base->num_rows();
echo "<hr>";
foreach($query as $row){
echo "Id : ".$row->id." row1 : ".$row->row1." row2 : ".$row->row2." row3 : ".$row->row3;
echo "<br>";
}
```
Example
```
$table = "user"; // table name
$condition='$row->id == 0 '; // '' for no condition
$order = 'd'; //descedenting order, '' ascedenting order
$start = 0;
$per_page = 10; // for all data $per_page = "";
$query = $base->select($table,$condition,$order,$start,$per_page);
echo "Results - select : ".$base->num_rows();
echo "<hr>";
foreach($query as $row){
echo "Id : ".$row->id." name : ".$row->name." surname : ".$row->surname." age : ".$row->age;
echo "<br>";
}
```
### Update
Syntax
```
$table = "table name";
$condition='$row->row == "value"';
$values = ["row1" => "value1","row2" => "value2" ];
$base->update($table,$condition,$values);
```
Example 1
```
$table = "user";
$condition='$row->id == 0';
$values = ["name" => "Johny","surname" => "Wainy" ];
$base->update($table,$condition,$values);
```
Example 2
```
$table = "user";
$condition='$row->id>-1'; // Update all
$values = ["name" => "Johny","surname" => "Wainy" ];
$base->update($table,$condition,$values);
```
### Delete
Syntax
```
$condition='$row->row == value';
$base->delete("table",$condition);
```
Example 1
```
$condition='$row->id == 1';
$base->delete("table",$condition);
```
Example 2
```
$condition='$row->name == "John"';
$base->delete("table",$condition);
```
Example 3
```
$condition='$row->id > -1'; Delete all
$base->delete("table",$condition);
```
### Search
Syntax
```
$table = "table name";
$rows= "row1,row2,row3"; // Rows name to be searched
$search = trim($posteddata); // Search query
$order = 'd'; 'd' descedenting order, '' ascedenting order
$start = offset; // Offset
$per_page = limit; // for all data $per_page = "";
$query = $base->search($table,$rows,$search,$order,$start,$per_page);
echo "Results : ".$base->num_rows();
echo "<hr>";
foreach($query as $row){
echo "Id : ".$row->id." row1 : ".$row->row1." row2 : ".$row->row2." row3 : ".$row->row3;
echo "<br>";
}
```
Example
```
$table = "user"; // table name
$rows= "name,surname,age"; // Rows name to be searched
$search = trim($_POST['name']); // Search query
$order = 'd'; 'd' descedenting order, '' ascedenting order
$start = 0; // Offset
$per_page = 10; // for all data $per_page = "";
$query = $base->search($table,$rows,$search,$order,$start,$per_page);
echo "Results : ".$base->num_rows();
echo "<hr>";
foreach($query as $row){
echo "Id : ".$row->id." name : ".$row->name." surname : ".$row->surname." age : ".$row->age;
echo "<br>";
}
```<file_sep><?php
/* Direct database */
/* Developed by <NAME> */
class Database{
private $base;
private $table;
private $username;
private $password;
private $rows;
private $result;
private $rows_count;
private $max_rows = 200;
private $rows_config = array();
private $index_rows;
private $datum;
public function __construct($basename,$username,$password){
$this->base = $basename;
$this->username = hash("sha256", $username);
$this->password = hash("<PASSWORD>", $password);
$this->datum = date("d.m.y H:i:s");
if(!file_exists($this->base)){
mkdir($this->base, 0777, true);
$access='<Files *.*>
Order deny,allow
Deny from All
</Files>';
$this->writeFile(".htaccess", $access);
$config=array(
'basename' => hash("sha256", $basename),
'username' => $this->username,
'password' => $<PASSWORD>,
'date' => $this->datum
);
$config = json_encode($config);
$this->writeFile("config.json", $config);
}else{
$userdata = $this->readFile("config.json");
$config = json_decode($userdata,true);
if(hash("sha256", $basename) != $config['basename'] || $this->username != $config['username'] || $this->password != $config['password']){
echo "Access denied!";
exit;
}
}
if(file_exists($this->base."/tableconfig.json")){
$this->readTableconfig();
}
}
public function insert($table,$values){
$table = str_replace(" ","",$table);
$this->rows = array();
if(!array_key_exists($table,$this->rows_config)){
$this->index_rows = 0;
$this->writeTableconfig($table);
$this->table = $table."_".$this->index_rows;
}else{
$this->readTableconfig();
$this->index_rows = $this->rows_config[$table];
$this->table = $table."_". $this->index_rows ;
}
if(file_exists($this->base."/".$this->table.".json")){
$this->rows = json_decode($this->readFile($this->table.".json"));
$lastrow = end($this->rows);
$nextid = $lastrow->id + 1;
if($this->max_rows == count($this->rows)){
$this->index_rows++;
$this->writeTableconfig($table);
$nextrows11 = array();
$nextrows1 = array('id' => $nextid);
foreach($values as $key=>$value){
$nextrows1[$key] = $value;
}
$nextrows11[] = $nextrows1;
$json =json_encode($nextrows11);
if($this->writeFile($table."_".$this->index_rows.".json",$json)){
return true;
}else{
return false;
}
}else{
$nextrows = array('id' => $nextid);
foreach($values as $key=>$value){
$nextrows[$key] = $value;
}
$this->rows[] = $nextrows;
$json =json_encode($this->rows);
if($this->writeFile($this->table.".json",$json)){
return true;
}else{
return false;
}
}
}else{
$this->rows['id'] = 0;
foreach($values as $key=>$value){
$this->rows[$key] = $value;
}
$this->rows = array($this->rows);
$json =json_encode($this->rows);
if($this->writeFile($this->table.".json",$json)){
return true;
}else{
return false;
}
}
}
public function select($table,$condition,$order,$start,$per_page){
$table = str_replace(" ","",$table);
$this->readTableconfig();
if(array_key_exists($table,$this->rows_config)){
$this->index_rows = $this->rows_config[$table];
$this->result = array();
for($i=0; $i<$this->index_rows+1; $i++){
$this->rows = array();
$this->table = $table."_".$i;
$this->rows = json_decode($this->readFile($this->table.".json"));
if($condition){
foreach($this->rows as $key=>$row){
if(eval("return $condition;")){
$this->result[] = $row;
}
}
}else{
foreach($this->rows as $key=>$row){
$this->result[] = $row;
}
}
}
$this->rows_count = count($this->result);
if($order == 'd'){
$this->result = array_reverse($this->result);
}
if($per_page){
$this->result = array_slice($this->result, $start, $per_page);
}
return $this->result;
}else{
echo "Table don't exists";
}
}
public function search($basetable,$rows,$search,$order,$start,$per_page){
$basetable = str_replace(" ","",$basetable);
$this->readTableconfig();
if(array_key_exists($basetable,$this->rows_config)){
$this->index_rows = $this->rows_config[$basetable];
$this->result = array();
if($search){
$search = explode(" ",$search);
$rows = explode(",",$rows);
$searchrows = '""';
foreach($rows as $row){
$searchrows .= '." ".strtolower($row->'.$row.') ';
}
$c = 0;
$pageserch = '';
foreach($search as $search_each){
$search_each = strtolower($search_each);
if($c == 0){
$const = 'preg_match("/\b'.$search_each.'\b/", '.$searchrows.')';
$pageserch .= ' preg_match("/\b'.$search_each.'\b/", strtolower(serialize($this->rows)) )';
}else{
$const .= '&& preg_match("/\b'.$search_each.'\b/", '.$searchrows.')';
$pageserch .= ' && preg_match("/\b'.$search_each.'\b/", strtolower(serialize($this->rows)) )';
}
$c=1;
}
for($i=0; $i<$this->index_rows+1; $i++){
$this->rows = array();
$this->basetable = $basetable."_".$i;
$this->rows = json_decode($this->readFile($this->basetable.".json"));
if(eval("return $pageserch;")){
foreach($this->rows as $key=>$row){
if(eval("return $const;")){
$this->result[] = $row;
}
}
}
}
}
$this->rows_count = count($this->result);
if($order == 'd'){
$this->result = array_reverse($this->result);
}
if($per_page){
$this->result = array_slice($this->result, $start, $per_page);
}
return $this->result;
}else{
echo "Table don't exists";
}
}
public function delete($table,$condition){
$table = str_replace(" ","",$table);
$this->readTableconfig();
if(array_key_exists($table,$this->rows_config)){
$this->index_rows = $this->rows_config[$table];
$rowdeleted = array();
$rowrenamed = array();
$error = 0;
if(!$condition){
$condition='$row->id > -1';
}
for($i=0; $i<$this->index_rows+1; $i++){
$this->result = array();
$this->rows = array();
$this->table = $table."_".$i;
$this->rows = json_decode($this->readFile($this->table.".json"));
foreach($this->rows as $row){
if(eval("return $condition;")){
}else{
$this->result[] = $row;
}
}
if(empty($this->result)){
$rowdeleted[] = $table."_".$i.".json";
}else{
$rowrenamed[] = $table."_".$i.".json";
}
$json =json_encode($this->result);
if(!$this->writeFile($this->table.".json",$json)){
$error++;
}
}
if(!empty($rowdeleted)){
foreach($rowdeleted as $row){
unlink($this->base."/".$row);
}
$rownum = 0;
foreach($rowrenamed as $row){
$rowe = explode("_",$row);
rename($this->base."/".$row, $this->base."/".$rowe[0]."_".$rownum.".json");
$rownum++;
}
$this->index_rows = $rownum - 1;
if(!$this->writeTableconfig($table)){
$error++;
}
}
if($error == 0){
return true;
}else{
return false;
}
}else{
echo "Table don't exists";
}
}
public function update($table,$condition,$updates){
$table = str_replace(" ","",$table);
$this->readTableconfig();
if(array_key_exists($table,$this->rows_config)){
$this->index_rows = $this->rows_config[$table];
$error = 0;
if(!$condition){
$condition='$row->id > -1';
}
for($i=0; $i<$this->index_rows+1; $i++){
$this->result = array();
$this->rows = array();
$this->table = $table."_".$i;
$this->rows = json_decode($this->readFile($this->table.".json"));
foreach($this->rows as $row){
if(eval("return $condition;")){
foreach($updates as $key=>$value){
echo $key ." ". $value;
$row -> $key = $value;
}
$this->result[] = $row;
}else{
$this->result[] = $row;
}
}
$json =json_encode($this->result);
if(!$this->writeFile($this->table.".json",$json)){
$error++;
}
}
if($error == 0){
return true;
}else{
return false;
}
}else{
echo "Table don't exists";
}
}
private function readFile($filename){
return file_get_contents($this->base."/".$filename);
}
private function writeFile($filename,$data){
try{
file_put_contents($this->base."/".$filename, $data);
return true;
}catch(Exception $ex){
return false;
}
}
private function writeTableconfig($table){
$this->rows_config[$table] = $this->index_rows;
$tableconfig = json_encode($this->rows_config);
$this->writeFile("tableconfig.json", $tableconfig);
}
private function readTableconfig(){
if(file_exists($this->base."/tableconfig.json")){
$tableconfig = $this->readFile("tableconfig.json");
$this->rows_config = json_decode($tableconfig,true);
}else{
echo "Table don't axists !";
}
}
public function num_rows(){
return $this->rows_count;
}
public function encode($data){
return base64_encode($data);
}
public function decode($data){
return base64_decode($data);
}
}
|
5b5e4d8f492c248e0aa40554fb076723bb281936
|
[
"Markdown",
"PHP"
] | 2 |
Markdown
|
PredragJovicic/Direct-database
|
6120b2b1710703c9c8b55e6d215536cac7a95fbc
|
71daa8afe84472a2756093ccc1daa69ace617fbd
|
refs/heads/main
|
<repo_name>willy0632080/0330<file_sep>/index.php
<?php include("header.php"); ?>
<div class="container">
<?php include("menu.php"); ?>
<?php include("detabase.php");
$sql = "SELECT * FROM news";
$result = $conn->query($sql);
?>
<form action="addtitle.php" method ="POST">
新聞標題<input type=txt size=40 name=title>
<input type =submit value ="送出">
</form>
<?php
if ($result->num_rows > 0) {
echo "<table class='table table-success table-striped'>";
echo "<tr><td>消息</td><td>張貼日期</td><td>管理</td></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row["title"]. "</td>";
echo "<td>" . $row["created"]. "</td>";
echo "<td><a class='btn btn-outline-info bth-sm'href='delete.php?target=" . $row["id"] . "'>刪除</a></td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
</div>
<?php include("footer.php"); ?>
<file_sep>/0330-1a.php
<?php include ("header.php"); ?>
<?php
$h = $_POST["height"];
$w = $_POST["weight"];
$BMI = $w / $h**2;
echo "身高:" . $h ."公分<br>";
echo "體重:" . $w . "公斤<br>";
echo "BMI:" . $BMI . "<br>";
if ($BMI < 18.5){
echo "過輕!<br>";
}else if ($BMI > 24){
echo "過重!<br>";
}else{
echo "正常!<br>";
}
?>
<?php include("footer.php"); ?>
|
32447251fdf5675bad29896cb5c8ddba174b9471
|
[
"PHP"
] | 2 |
PHP
|
willy0632080/0330
|
dd07a49dbbdd42b01a79911bec2333c61718824b
|
4bfe02f2ca981126ccff894cf37c9f9610401343
|
refs/heads/master
|
<repo_name>liwenr2020/MyNews<file_sep>/app/src/main/java/com/example/mynews/Adapter/NewsAdapter.java
package com.example.mynews.Adapter;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.example.mynews.MainActivity;
import com.example.mynews.NewsInfoActivity;
import com.example.mynews.R;
import com.example.mynews.news.NewsItem;
import java.net.URL;
import java.util.List;
public class NewsAdapter extends RecyclerView.Adapter<NewsViewHolder> {
private List<NewsItem.T1348647853363DTO> mNewsList;
private LayoutInflater mLayoutInflater;
public NewsAdapter(List<NewsItem.T1348647853363DTO> data,
LayoutInflater l){
mNewsList=data;
mLayoutInflater=l;
}
@NonNull
@Override
public NewsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = mLayoutInflater.inflate(R.layout.news_item,parent,false);
return new NewsViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull NewsViewHolder holder, int position) {
String image = mNewsList.get(position).getImgsrc();
String title =mNewsList.get(position).getTitle();
Glide.with(holder.itemView.getContext()).load(image).into(holder.imageView);
holder.textView.setText(title);
holder.linearLayout.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), NewsInfoActivity.class);
String url = mNewsList.get(position).getUrl();//.replace('|', '/');
//String newUrl = "https://news.163.com/photoview/" + url + ".html";
intent.putExtra("url", url);
v.getContext().startActivity(intent);
Log.e(">>>>>","你点击了");
}
});
}
// public NewsAdapter(List<NewsItem.T1348647853363DTO> mNewsList,LayoutInflater l){
// this.mNewsList=mNewsList;
// layoutInflater=l;
// }
//
// @NonNull
// @Override
// public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//
// View view= layoutInflater.inflate(R.layout.news_item,parent,false);
// RecyclerView.ViewHolder holder=new RecyclerView.ViewHolder(view);
// return holder;
// }
//
//
// @Override
// public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
// // NewsItem.T1348647853363DTO t1348647853363DTO = mNewsList.get(position);
//
//// int i = 0;
////
//// do {
// String image = mNewsList.get(position).getImgsrc();
// String title =mNewsList.get(position).getTitle();
//
// Glide.with(holder.itemView.getContext()).load(image).into(holder.imageView);
// holder.textView.setText(title);
//
// //NewsItem.T1348647853363DTO.AdsDTO finalAdsDTO = adsDTO;
//// int finalI = i;
// holder.linearLayout.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v) {
// Intent intent = new Intent(v.getContext(), NewsInfoActivity.class);
//
// String url = mNewsList.get(position).getUrl();//.replace('|', '/');
// //String newUrl = "https://news.163.com/photoview/" + url + ".html";
//
// intent.putExtra("url", url);
// v.getContext().startActivity(intent);
//
// }
// });
//// i=i+1;
//// }while(mNewsList.get(i)!=null);
// }
@Override
public int getItemCount() {
return mNewsList.size();
}
// private static class NewsViewHolder extends RecyclerView.ViewHolder{
// ImageView imageView;
// TextView textView;
// LinearLayout linearLayout;
//
// @SuppressLint("ResourceType")
// public NewsViewHolder(View view){
// super(view);
// imageView.findViewById(R.id.img_of_item);
// textView.findViewById(R.id.details_of_item);
// linearLayout.findViewById(R.layout.news_item);
// }
// }
}
<file_sep>/app/src/main/java/com/example/mynews/web/ExplainJson.java
package com.example.mynews.web;
import android.util.Log;
import com.example.mynews.news.NewsItem;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ExplainJson {
private String json;
public NewsItem newsItem;
//private GetJson getJson;
public List<NewsItem.T1348647853363DTO> getDataList(String data) {
// getJson=new GetJson();
// json=getJson.getDetails();
json=data;
Gson gson=new Gson();
newsItem=new NewsItem();
newsItem=gson.fromJson(json,NewsItem.class);
final List<NewsItem.T1348647853363DTO> datas;
datas=newsItem.getT1348647853363();
Log.e(">>>解析的标题",datas.get(0).getLtitle().toString());
return datas;
}
}
|
c5d1b2a262ee83dfaf911c22c930bcfc2123df9c
|
[
"Java"
] | 2 |
Java
|
liwenr2020/MyNews
|
9b2377f3887cf817950e238f4e32ebfa457340d2
|
9427fc8d151f00c1b321f326bed3f0e06c0bddd1
|
refs/heads/master
|
<repo_name>HemrajRijal/WeatherApp<file_sep>/README.md
# WeatherApp
### The weather app build using vanilla JavaScript
<file_sep>/app.js
window.addEventListener('load', () => {
let long;
let lat;
let icon;
let temperatureDescription = document.querySelector(".temperature-description");
let temperatureDegree = document.querySelector(".temperature-degree");
let locationTimeZone = document.querySelector(".time-zone");
let temperatureSection = document.querySelector(".temperature");
let temperatureSpan = document.querySelector(".temperature-span");
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
// console.log(position);
long = position.coords.longitude;
lat = position.coords.latitude;
const access_key = '<KEY>';
const api = `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${long}&appid=${access_key}`;
console.log('--->' + api)
fetch(api)
.then(response => {
mode: 'no-cors'
return response.json();
})
.then(data => {
const { temp } = data.main;
const { description } = data.weather[0];
const { name } = data;
const { main } = data.weather[0];
temperatureDegree.textContent = temp;
temperatureDescription.textContent = description;
locationTimeZone.textContent = name;
//Formula for Celsius
let celsius = (temp - 273);
// Set Icon
setIcons(main, document.querySelector('.icon'));
//Change celcius to Fraheneit and vide verca
temperatureSection.addEventListener('click', () => {
if (temperatureSpan.textContent == 'K') {
temperatureSpan.textContent = 'C';
temperatureDegree.textContent = Math.floor(celsius);
} else {
temperatureSpan.textContent = 'K';
temperatureDegree.textContent = temp;
}
})
})
})
};
function setIcons(icon, iconId) {
var skycons = new Skycons({ "color": "white" });
const currentIcon = icon.toUpperCase();
skycons.play();
return skycons.set(iconId, Skycons[currentIcon]);
}
})
|
a28d1ae41dd93cecfc37880bfc34e5dba15a5f78
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
HemrajRijal/WeatherApp
|
6c076a17df450426fccd57c0f8001d057de92f94
|
73f7f38db5379df0c98fa6bc9c11ff16260c5f93
|
refs/heads/master
|
<file_sep>import torch.optim as optim
from torchvision.transforms import ToTensor, Compose, Normalize
from pipeline.config_base import ConfigBase, PredictConfigBase
from pipeline.datasets.base import DatasetWithPostprocessingFunc, DatasetComposer, OneHotTargetsDataset
from pipeline.datasets.mixup import MixUpDatasetWrapper
from pipeline.losses.vector_cross_entropy import VectorCrossEntropy
from pipeline.predictors.classification import PredictorClassification
from pipeline.schedulers.learning_rate.reduce_on_plateau import SchedulerWrapperLossOnPlateau
from pipeline.trainers.classification import TrainerClassification
from sign_pipeline.dataset import SignImagesDataset, SignTargetsDataset
from sign_pipeline.loss import SignLoss, SignMetricsCalculator, SignLossMixup
from sign_pipeline.associated import AVAILABLE_CLASSES
TRAIN_DATASET_PATH = "/Vol1/dbstore/datasets/multimodal/iceblood/data_pnm/classification_ann_train"
VAL_DATASET_PATH = "/Vol1/dbstore/datasets/multimodal/iceblood/data_pnm/classification_ann_test"
TEST_DATASET_PATH = "/root/SignDetection/classification/bin/tmp_folder/classificator_input.pickle"
TRAIN_LOAD_SIZE = 128 + 25
TRAIN_CROP_SIZE = 128
TEST_LOAD_SIZE = 128
TEST_CROP_SIZE = 128
MAX_EPOCH_LENGTH = 10000
def get_dataset(path, transforms, train, use_mixup):
load_size = TRAIN_LOAD_SIZE if train else TEST_LOAD_SIZE
crop_size = TRAIN_CROP_SIZE if train else TEST_CROP_SIZE
images_dataset = DatasetWithPostprocessingFunc(
SignImagesDataset(path=path, load_size=load_size, crop_size=crop_size),
transforms)
targets_dataset = SignTargetsDataset(path=path, load_size=load_size, crop_size=crop_size, use_mixup=use_mixup)
return DatasetComposer([images_dataset, targets_dataset])
class ConfigSignBase(ConfigBase):
def __init__(
self,
model,
model_save_path,
train_dataset_path=TRAIN_DATASET_PATH,
num_workers=8,
batch_size=128,
train_transforms=None,
val_transforms=None,
epoch_count=200,
print_frequency=10,
mixup_alpha=0,
optimizer=None,
device="cuda:0",
scheduler=None,
):
if optimizer is None:
optimizer = optim.Adam(
model.parameters(),
lr=1e-4)
if scheduler is None:
scheduler = SchedulerWrapperLossOnPlateau(optimizer, patience=2, min_lr=1e-6)
loss = SignLoss()
metrics_calculator = SignMetricsCalculator()
trainer_cls = TrainerClassification
train_dataset = get_dataset(path=train_dataset_path, transforms=train_transforms, train=True,
use_mixup=mixup_alpha > 0)
val_dataset = get_dataset(path=VAL_DATASET_PATH, transforms=val_transforms, train=False,
use_mixup=mixup_alpha > 0)
if mixup_alpha > 0:
train_dataset = MixUpDatasetWrapper(train_dataset, alpha=mixup_alpha)
loss = SignLossMixup()
super().__init__(
model=model,
model_save_path=model_save_path,
optimizer=optimizer,
scheduler=scheduler,
loss=loss,
metrics_calculator=metrics_calculator,
batch_size=batch_size,
num_workers=num_workers,
train_dataset=train_dataset,
val_dataset=val_dataset,
trainer_cls=trainer_cls,
print_frequency=print_frequency,
epoch_count=epoch_count,
max_epoch_length=MAX_EPOCH_LENGTH,
device=device)
class PredictConfigSignBase(PredictConfigBase):
def __init__(self, model, model_save_path, num_workers=4, batch_size=128, transforms=None):
predictor_cls = PredictorClassification
if transforms is None:
transforms = Compose([ToTensor(), Normalize((0.5, 0.5, 0.5), (0.2, 0.2, 0.2))])
images_dataset = DatasetWithPostprocessingFunc(
SignImagesDataset(path=TEST_DATASET_PATH,
load_size=TEST_LOAD_SIZE, crop_size=TEST_CROP_SIZE),
transforms)
dataset = DatasetComposer([images_dataset, list(range(len(images_dataset)))])
super().__init__(
model=model,
model_save_path=model_save_path,
dataset=dataset,
predictor_cls=predictor_cls,
num_workers=num_workers,
batch_size=batch_size)
<file_sep>from torchvision.models import resnet
import torch.nn as nn
class ResnetModelFeatureExtractorBase(nn.Module):
def __init__(self, model, input_channels):
super().__init__()
model.fc = nn.Sequential()
model.avgpool = nn.AdaptiveAvgPool2d(1)
if input_channels != 3:
model.conv1 = nn.Conv2d(
input_channels,
model.conv1.out_channels,
kernel_size=model.conv1.kernel_size,
stride=model.conv1.stride,
padding=model.conv1.padding,
bias=model.conv1.bias)
self._model = model
def forward(self, input):
return self._model(input)
class Resnet18FeatureExtractor(ResnetModelFeatureExtractorBase):
NUM_FEATURES = 512
def __init__(self, pretrained=True, input_channels=3):
model = resnet.resnet18(pretrained=pretrained)
super().__init__(
model=model,
input_channels=input_channels)
class Resnet34FeatureExtractor(ResnetModelFeatureExtractorBase):
NUM_FEATURES = 512
def __init__(self, pretrained=True, input_channels=3):
model = resnet.resnet34(pretrained=pretrained)
super().__init__(
model=model,
input_channels=input_channels)
class Resnet50FeatureExtractor(ResnetModelFeatureExtractorBase):
NUM_FEATURES = 2048
def __init__(self, pretrained=True, input_channels=3):
model = resnet.resnet50(pretrained=pretrained)
super().__init__(
model=model,
input_channels=input_channels)
class Resnet101FeatureExtractor(ResnetModelFeatureExtractorBase):
NUM_FEATURES = 2048
def __init__(self, pretrained=True, input_channels=3):
model = resnet.resnet101(pretrained=pretrained)
super().__init__(
model=model,
input_channels=input_channels)
class Resnet152FeatureExtractor(ResnetModelFeatureExtractorBase):
NUM_FEATURES = 2048
def __init__(self, pretrained=True, input_channels=3):
model = resnet.resnet152(pretrained=pretrained)
super().__init__(
model=model,
input_channels=input_channels)
<file_sep>import argparse
import torch
import pickle
def main():
parser = argparse.ArgumentParser()
parser.add_argument("predictions_path")
parser.add_argument("extracted_bboxes_path")
parser.add_argument("output_path")
args = parser.parse_args()
predictions = torch.load(args.predictions_path)
with open(args.extracted_bboxes_path, "rb") as fin:
extracted_bboxes = pickle.load(fin)
result = []
for prediction, info in zip(predictions, extracted_bboxes):
prediction = prediction.cpu()
prediction_multi = prediction[:-1]
prediction_multi = torch.softmax(prediction_multi, dim=-1)
prediction_binary = prediction[-1]
label_multi = prediction_multi.argmax()
prob_multi = prediction_multi.max()
if len(result) == 0 or result[-1]["filename"] != info["filename"]:
result.append({
"filename": info["filename"],
"predictions": []
})
result[-1]["predictions"].append([
info["bbox"], int(label_multi), float(prob_multi), float(torch.sigmoid(prediction_binary))
])
with open(args.output_path, "wb") as fout:
pickle.dump(result, fout)
if __name__ == "__main__":
main()
<file_sep>import argparse
import os
import shutil
import glob
import random
import json
import numpy as np
import pandas as pd
from PIL import Image
import pickle
from tqdm import tqdm
from pathlib import Path
from mmdet.ops.nms import nms_cpu, nms
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--list_all_classes_path", default='all_classes.txt')
parser.add_argument("--list_valid_classes_path", default='valid_classes_stage0.txt')
parser.add_argument("--mmdet_predict_path",
default='/group-volume/orc_srr/multimodal/iceblood/develop/mmdetection/cascade_skolkovo_fit_frozen4_lll_lr_38.pkl')
parser.add_argument("--submit_annotation_path",
default='/group-volume/orc_srr/multimodal/iceblood/datasets/main/TEST/final_skolkovo.pickle')
parser.add_argument("--confidence", type=float, default=0.55)
parser.add_argument("--class_accuracy", type=int, default=2)
parser.add_argument("--output_result_path", default='submits')
args = parser.parse_args()
pred_pickle_path = args.mmdet_predict_path
subm_annotations_path = args.submit_annotation_path
output_result_path = args.output_result_path
class_accuracy = args.class_accuracy
convert_class = lambda x: '.'.join(str(x).split('.')[:class_accuracy])
output_result_path = os.path.join(output_result_path, 'subm_' + pred_pickle_path.split('/')[-1]
+ '_' + str(args.confidence).split('.')[-1]
+ '_' + str(args.class_accuracy) + '.csv')
all_classes_list = []
with open(args.list_all_classes_path, 'r') as fileobj:
for row in fileobj:
all_classes_list.append(row.rstrip('\n'))
valid_classes_list = []
with open(args.list_valid_classes_path, 'r') as fileobj:
for row in fileobj:
valid_classes_list.append(row.rstrip('\n'))
all_classes_list = [convert_class(x) for x in all_classes_list]
valid_classes_list = [convert_class(x) for x in valid_classes_list]
print('num classes: ', len(all_classes_list))
print('num valid classes: ', len(valid_classes_list))
with open(pred_pickle_path, 'rb') as outfile:
subm_data = pickle.load(outfile)
with open(subm_annotations_path, 'rb') as outfile:
subm_annotations = pickle.load(outfile)
with open(output_result_path, 'w+') as f:
f.write('\t'.join(['frame', 'xtl', 'ytl', 'xbr', 'ybr', 'class']) + '\n')
for cur_pred, name in tqdm(zip(subm_data, subm_annotations)):
name = str('/'.join(name['filename'].split('/')[-2:]))
img_name = name.split('/')
img_name = img_name[-2] + '/' + img_name[-1]
img_name = img_name.replace('.jpg', '')
all_boxes = []
all_classes = []
for cur_sign, cur_boxes in zip(all_classes_list, cur_pred):
for cur_box in cur_boxes:
x, y, xmax, ymax, p = cur_box
h = xmax - x
w = ymax - y
cur_box = [x, y, x + h, y + w, p]
if cur_box[-1] >= args.confidence and cur_sign in valid_classes_list:
all_boxes.append(cur_box)
all_classes.append(cur_sign)
all_boxes = np.array(all_boxes)
all_classes = np.array(all_classes)
if not len(all_boxes):
continue
filtered_boxes = nms(all_boxes, 0.05)[1]
for cur_box, cur_sign in zip(all_boxes[filtered_boxes], all_classes[filtered_boxes]):
cur_box = cur_box[:4].astype(np.int32)
cur_box = list(map(str, cur_box.tolist()))
f.write('\t'.join([img_name, *cur_box, cur_sign]) + '\n')
if __name__ == "__main__":
main()<file_sep>import argparse
import os
import pickle
import copy
def main():
parser = argparse.ArgumentParser()
parser.add_argument("sequence_path")
parser.add_argument("predictions_path")
parser.add_argument("output_path")
parser.add_argument("--skip", type=int, default=1)
args = parser.parse_args()
with open(args.predictions_path, "rb") as fin:
predictions = pickle.load(fin)
filename_to_predict = {}
for predict in predictions:
filename_to_predict[predict["filename"]] = predict["predictions"]
index = 0
predict_index = 0
result = []
files = sorted(os.listdir(args.sequence_path), reverse=True)
files = list(filter(lambda x: x.endswith(".pnm"), files))
for file_name in files:
index += 1
if (index - 1) % args.skip != 0 and file_name != files[-1]:
result.append(None)
continue
prediction = filename_to_predict.get(os.path.join(args.sequence_path, file_name), [])
result.append(prediction)
predict_index += 1
with open(args.output_path, "wb") as fout:
pickle.dump(result, fout)
if __name__ == "__main__":
main()
<file_sep>import torch
import torch.nn as nn
class VectorCrossEntropy(nn.Module):
def __init__(self):
super().__init__()
self._log_softmax = nn.LogSoftmax(dim=1)
def forward(self, input, target):
input = self._log_softmax(input)
loss = -torch.sum(input * target)
loss = loss / input.shape[0]
return loss
<file_sep>import abc
from torch.nn.modules.dropout import _DropoutNd
def set_dropout_probability(module, probability):
if isinstance(module, _DropoutNd):
module.p = probability
return
for child in module.children():
set_dropout_probability(child, probability)
<file_sep>from ..base import SchedulerBase
from .utils import set_dropout_probability
class SchedulerWrapperIncreaseStep(SchedulerBase):
def __init__(self, model, epoch_count, initial_value=0, max_value=0.5):
self._model = model
self._epoch_count = epoch_count
self._initial_value = initial_value
self._max_value = max_value
def step(self, loss, metrics, epoch_id):
new_value = (self._max_value - self._initial_value) / self._epoch_count * (epoch_id + 1)
set_dropout_probability(self._model, new_value)
<file_sep>import pickle
import torch.utils.data as data
from torchvision.transforms import Compose, Resize, RandomCrop
import torch
from sign_pipeline.associated import AVAILABLE_CLASSES
class SignDataset(data.Dataset):
def __init__(self, path, load_size, crop_size, use_mixup=False):
with open(path, "rb") as fin:
self._data = pickle.load(fin)
self._transforms = Compose([
Resize(load_size),
RandomCrop(crop_size),
])
self._use_mixup = use_mixup
def get_image(self, item):
image = self._data[item]["cropped_image"]
return self._transforms(image)
def get_class(self, item):
associated_label = self._data[item]["associated_label"]
temporary = float(self._data[item]["temporary"])
if self._use_mixup:
result = torch.zeros(len(AVAILABLE_CLASSES) + 1, dtype=torch.float32)
result[associated_label] = 1
else:
result = associated_label
return [result, temporary]
def __len__(self):
return len(self._data)
def __getitem__(self, item):
return self._data[item]
class SignImagesDataset(SignDataset):
def __getitem__(self, item):
return self.get_image(item)
class SignTargetsDataset(SignDataset):
def __getitem__(self, item):
return self.get_class(item)
<file_sep>import numpy as np
import torch.nn as nn
from sklearn.metrics import accuracy_score
from pipeline.metrics.base import MetricsCalculatorBase
from pipeline.losses.vector_cross_entropy import VectorCrossEntropy
class SignLoss(nn.Module):
def __init__(self, binary_weight=1.0):
super().__init__()
self._multi = nn.CrossEntropyLoss()
self._binary = nn.BCEWithLogitsLoss()
self._binary_weight = binary_weight
def forward(self, y_pred, y_true):
multi_pred = y_pred[:, :-1]
binary_pred = y_pred[:, -1]
multi_true = y_true[0]
binary_true = y_true[1].float()
loss = self._multi(multi_pred, multi_true) + self._binary_weight * self._binary(binary_pred, binary_true)
return loss
class SignLossMixup(nn.Module):
def __init__(self, binary_weight=1.0):
super().__init__()
self._multi = VectorCrossEntropy()
self._binary = nn.BCEWithLogitsLoss()
self._binary_weight = binary_weight
def forward(self, y_pred, y_true):
multi_pred = y_pred[:, :-1]
binary_pred = y_pred[:, -1]
multi_true = y_true[0]
binary_true = y_true[1].float()
loss = self._multi(multi_pred, multi_true) + self._binary_weight * self._binary(binary_pred, binary_true)
return loss
class SignMetricsCalculator(MetricsCalculatorBase):
def __init__(self, border=0):
super().__init__()
self.zero_cache()
self._border = border
def zero_cache(self):
self._predictions = []
self._true_labels_multi = []
self._true_labels_binary = []
def add(self, y_predicted, y_true):
self._predictions.append(y_predicted.cpu().data.numpy())
y_true_multi = y_true[0] if len(y_true[0].shape) == 1 else y_true[0].argmax(-1)
self._true_labels_multi.append(y_true_multi.cpu().data.numpy())
self._true_labels_binary.append(y_true[1].cpu().data.numpy())
def calculate(self):
y_pred = np.concatenate(self._predictions)
y_true_multi = np.concatenate(self._true_labels_multi)
y_true_binary = np.concatenate(self._true_labels_binary)
y_pred_multi = np.argmax(y_pred[:, :-1], -1)
y_pred_binary = (y_pred[:, -1] >= self._border).astype("int")
return {"accuracy_multi": accuracy_score(y_true_multi, y_pred_multi),
"accuracy_binary": accuracy_score(y_true_binary, y_pred_binary)}
<file_sep>import os
import numpy as np
import pickle
from shutil import copyfile
import glob
import time
import itertools
import shutil
from joblib import Parallel, delayed
import subprocess
import argparse
IMGS_STORED = 3000
work_dir = 'work_dir/'
COPER_FOLDER = 2
PARALLEL_COPY_WORKERS = 4
parser = argparse.ArgumentParser()
parser.add_argument("test_folder")
args = parser.parse_args()
folders = glob.glob(args.test_folder + '/*/*', recursive=True)
all_batches = []
for cur_folder in folders:
internal_files = sorted(glob.glob(os.path.join(cur_folder, '*'), recursive=True))
for ind in range(0, len(internal_files), IMGS_STORED):
all_batches.append(internal_files[ind:ind + IMGS_STORED])
def _check_existance(cur_fold, status):
if os.path.exists(os.path.join(cur_fold, status)):
return True
else:
return False
def check_transfered(cur_fold):
return _check_existance(cur_fold, 'transfered')
def check_predicted(cur_fold):
return _check_existance(cur_fold, 'predicted')
def clean_dir(cur_fold):
shutil.rmtree(cur_fold)
os.makedirs(cur_fold, exist_ok=True)
def _single_copy_file(arg):
source, cur_fold = arg
folder = os.path.dirname(source)
base_folders = os.path.dirname(source).split('/')[-2:]
base_folders = '_'.join(base_folders)
name = os.path.basename(source)
#print(os.path.join(cur_fold, base_folder, name))
os.makedirs(os.path.join(cur_fold, base_folders), exist_ok=True)
copyfile(source, os.path.join(cur_fold, base_folders, name))
def copy_files(cur_fold, imgs):
arguments = [(cur_img, cur_fold) for cur_img in imgs]
results = Parallel(n_jobs=PARALLEL_COPY_WORKERS,
verbose=1,
backend="threading")(map(delayed(_single_copy_file), arguments))
time.sleep(5)
def set_transfered(cur_fold):
with open(os.path.join(cur_fold, 'transfered'), 'w') as f:
f.write('transfered')
def set_predicted(cur_fold):
with open(os.path.join(cur_fold, 'predicted'), 'w') as f:
f.write('predicted')
def _background_inderence_folder(folder):
process = subprocess.Popen(["python3", "predict_sequence.py", folder])
#process = subprocess.Popen(["sleep", "10"])
return process
def check_process(process):
try:
process.wait(timeout=0.001)
except subprocess.TimeoutExpired:
return False
return True
def get_prediction(cur_fold):
for cand_fold in os.listdir(cur_fold):
full_path = os.path.join(cur_fold, cand_fold)
if os.path.isdir(full_path):
process = _background_inderence_folder(full_path)
return process
folders = [work_dir + str(worker) for worker in range(COPER_FOLDER)]
for cur_fold in folders:
os.makedirs(cur_fold, exist_ok=True)
clean_dir(cur_fold)
pred_status = dict()
now_predicting = False
for current_imgs in all_batches:
for cur_fold in itertools.cycle(folders):
if cur_fold in pred_status and check_process(pred_status[cur_fold]): #Process return predicted status
set_predicted(cur_fold)
now_predicting = False
clean_dir(cur_fold)
del pred_status[cur_fold]
print('Prediction finished on {}'.format(cur_fold))
continue
if not check_transfered(cur_fold): #Empty or predicted
print('Starting copy from {} to {} on {}'.format(current_imgs[0], current_imgs[-1], cur_fold))
copy_files(cur_fold, current_imgs)
set_transfered(cur_fold)
print('Copy suceeded')
if not now_predicting:
process = get_prediction(cur_fold)
pred_status[cur_fold] = process
now_predicting = True
print('Prediction started on {}'.format(cur_fold))
break #should dispatch new images
time.sleep(1)
print('All predictions done')
<file_sep>import torch.utils.data as data
import random
import numpy as np
def _mixup(elem1, elem2, coeff):
if isinstance(elem1, (tuple, list)):
result = []
for inner_elem1, inner_elem2 in zip(elem1, elem2):
result.append(_mixup(inner_elem1, inner_elem2, coeff))
if isinstance(elem1, tuple):
result = tuple(result)
return result
else:
return elem1 * coeff + elem2 * (1 - coeff)
class MixUpDatasetWrapper(data.Dataset):
def __init__(self, dataset, alpha=1):
super().__init__()
self._dataset = dataset
self._alpha = alpha
def __len__(self):
return len(self._dataset)
def __getitem__(self, item):
first = self._dataset[item]
second = random.choice(self._dataset)
coeff = np.random.beta(self._alpha, self._alpha)
return _mixup(first, second, coeff)
<file_sep>import os
import pandas as pd
from tqdm import tqdm
train_annotations = '/group-volume/orc_srr/multimodal/iceblood/datasets/main/annotations/training/'
test_annotations = '/group-volume/orc_srr/multimodal/iceblood/datasets/main/annotations/test/'
final_annotations = '/group-volume/orc_srr/multimodal/iceblood/datasets/main/annotations/final/'
data_path = '/group-volume/orc_srr/multimodal/iceblood/datasets/main/TRAIN/skolkovo/'
data_path_final = '/group-volume/orc_srr/multimodal/iceblood/datasets/main/TEST/'
folders_train = os.listdir(train_annotations)
folders_test = os.listdir(test_annotations)
folders_final = os.listdir(final_annotations)
train_data = []
for cur_folder in tqdm(folders_train):
anno = list(filter(lambda x: 'tsv' in x, os.listdir(os.path.join(train_annotations, cur_folder))))
imgs = list(map(lambda x: x.replace('.tsv', '.jpg'), anno))
for cur_anno in anno:
img_data = pd.read_csv(os.path.join(train_annotations, cur_folder, cur_anno), sep='\t')
img_data['path'] = str(os.path.join(cur_folder, cur_anno.replace('.tsv', '.jpg')))
train_data.append(img_data)
test_data = []
for cur_folder in tqdm(folders_test):
anno = list(filter(lambda x: 'tsv' in x, os.listdir(os.path.join(test_annotations, cur_folder))))
imgs = list(map(lambda x: x.replace('.tsv', '.jpg'), anno))
for cur_anno in anno:
img_data = pd.read_csv(os.path.join(test_annotations, cur_folder, cur_anno), sep='\t')
img_data['path'] = str(os.path.join(cur_folder, cur_anno.replace('.tsv', '.jpg')))
test_data.append(img_data)
final_data = []
for cur_folder in tqdm(folders_final):
anno = list(filter(lambda x: 'tsv' in x, os.listdir(os.path.join(final_annotations, cur_folder))))
imgs = list(map(lambda x: x.replace('.tsv', '.jpg'), anno))
for cur_anno in anno:
img_data = pd.read_csv(os.path.join(final_annotations, cur_folder, cur_anno), sep='\t')
img_data['path'] = str(os.path.join(cur_folder, cur_anno.replace('.tsv', '.jpg')))
final_data.append(img_data)
train_df = pd.concat(train_data)
test_df = pd.concat(test_data)
train_df = train_df.reset_index()
test_df = test_df.reset_index()
df = pd.concat((test_df, train_df))
df['class'] = df['class'].astype(str)
df = df.reset_index()
df = df.drop(['level_0', 'data', 'index'], axis=1)
df.to_csv(os.path.join(data_path, 'skolkovo_ann.csv'), index=False)
final_df = pd.concat(final_data)
final_df = final_df.reset_index()
final_df['class'] = final_df['class'].astype(str)
final_df = final_df.drop(['data', 'index'], axis=1)
final_df.to_csv(os.path.join(data_path_final, 'skolkovo_final.csv'), index=False)
<file_sep>import argparse
import os
import pickle
import cv2
import joblib
from PIL import Image
import numpy as np
from sign_pipeline.associated import AVAILABLE_CLASSES
N_JOBS = 16
PADDING_PERCENT = 20
def histeq(image):
reshaped = image.reshape((image.shape[0] * image.shape[1], 3)).astype("float32")
y = (reshaped[:, 0] * 1 + reshaped[:, 1] * 1 + reshaped[:, 2] * 2) / 4
y = y.astype("uint8")
hist = np.bincount(y, minlength=256).astype("float32")
hist_sum = np.cumsum(hist)
max_value = hist_sum[-1] / 255
map_value = (hist_sum / max_value).astype("uint8")
return map_value[image]
def load_img(path):
img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
img = cv2.cvtColor(img, cv2.COLOR_BAYER_RG2RGB)
img = histeq(img)
return Image.fromarray(img)
def crop_image(image, bbox):
padding_x = int((bbox[2] - bbox[0]) / 100. * PADDING_PERCENT)
padding_y = int((bbox[3] - bbox[1]) / 100. * PADDING_PERCENT)
bbox = [bbox[0] - padding_x, bbox[1] - padding_y, bbox[2] + padding_x, bbox[3] + padding_y]
bbox[0] = max(bbox[0], 0)
bbox[1] = max(bbox[1], 0)
bbox[2] = min(bbox[2], image.size[0])
bbox[3] = min(bbox[3], image.size[1])
return image.crop(bbox)
def extract_annotations(data_path, annotation):
result = []
image = load_img(os.path.join(data_path, annotation["filename"]))
bboxes = annotation["ann"]["bboxes"]
labels = annotation["ann"]["labels"]
temporary_labels = annotation["ann"]["temporary"]
associated_data = annotation["ann"]["data"]
for bbox, label, temporary, data in zip(bboxes, labels, temporary_labels, associated_data):
if data in AVAILABLE_CLASSES:
associated_label_id = AVAILABLE_CLASSES.index(data)
else:
associated_label_id = len(AVAILABLE_CLASSES)
data = {
"bbox": bbox,
"temporary": int(temporary),
"associated_label": associated_label_id,
"cropped_image": crop_image(image, bbox)
}
result.append(data)
return result
def main():
parser = argparse.ArgumentParser()
parser.add_argument("data_path")
parser.add_argument("annotations_path")
parser.add_argument("output_path")
args = parser.parse_args()
with open(args.annotations_path, "rb") as fin:
annotations = pickle.load(fin)
p = joblib.Parallel(n_jobs=N_JOBS, backend="multiprocessing", verbose=5)
extracted_annotations = p(
joblib.delayed(extract_annotations)(args.data_path, annotation) for annotation in annotations)
result = []
for annotation in extracted_annotations:
result += annotation
with open(args.output_path, "wb") as fout:
pickle.dump(result, fout)
if __name__ == "__main__":
main()
<file_sep>from .base import TrainerBase
class TrainerSegmentation(TrainerBase):
pass
<file_sep>import argparse
import os
import subprocess
import shutil
TMP_PATH = "/root/SignDetection/classification/bin/tmp_folder"
TEST_PICKLE_PATH = "/root/SignDetection/classification/bin/tmp_folder/test.pickle"
SKIP_FRAMES_NUM = 4
CLASSIFICATOR_CONFIG = "sign_pipeline.configs.resnet34.py"
CLASSIFICATOR_PREDICTIONS_FOLDER = "/root/SignDetection/classification/bin/models/sign_resnet34/predictions"
MMDETECTION_BINARY_PATH = "/root/mmsetection_pnm/tools/test.py"
MMDETECTION_CONFIG_PATH = "/root/fp16_cascade_rcnn_50_sk_fit_predict_085.py"
MMDETECTION_CHECKPOINT_PATH = "/root/our_data/sota_fp16_cascade_rcnn_x50_32x4d_fpn_1x_fit_epoch_31.pth"
def main():
parser = argparse.ArgumentParser()
parser.add_argument("sequence_path")
args = parser.parse_args()
os.makedirs(TMP_PATH, exist_ok=True)
print("Starting prediction sequence", args.sequence_path)
print("Running prepare_test_annotations.py...")
subprocess.check_call([
"python3",
"prepare_test_annotations.py",
args.sequence_path,
TEST_PICKLE_PATH,
os.path.join(TMP_PATH, "annotations.pickle"),
"--skip",
str(SKIP_FRAMES_NUM)])
print("Running mmdet...")
subprocess.check_call([
"python3",
MMDETECTION_BINARY_PATH,
MMDETECTION_CONFIG_PATH,
MMDETECTION_CHECKPOINT_PATH,
"--out",
os.path.join(TMP_PATH, "detector_output.pickle")])
print("Running filter_predictions.py...")
subprocess.check_call([
"python3",
"filter_predictions.py",
os.path.join(TMP_PATH, "detector_output.pickle"),
os.path.join(TMP_PATH, "detector_filtered.pickle")])
print("Running prepare_test.py...")
subprocess.check_call([
"python3",
"prepare_test.py",
os.path.join(TMP_PATH, "annotations.pickle"),
os.path.join(TMP_PATH, "detector_filtered.pickle"),
os.path.join(TMP_PATH, "classificator_input.pickle")])
if os.path.exists(CLASSIFICATOR_PREDICTIONS_FOLDER):
shutil.rmtree(CLASSIFICATOR_PREDICTIONS_FOLDER)
print("Running predict.py...")
subprocess.check_call([
"python3",
"predict.py",
CLASSIFICATOR_CONFIG])
print("Running construct_predictions.py...")
subprocess.check_call([
"python3",
"construct_predictions.py",
os.path.join(CLASSIFICATOR_PREDICTIONS_FOLDER, "predictions"),
os.path.join(TMP_PATH, "classificator_input.pickle"),
os.path.join(TMP_PATH, "classificator_output.pickle")])
print("Running fill_skips.py...")
subprocess.check_call([
"python3",
"fill_skips.py",
args.sequence_path,
os.path.join(TMP_PATH, "classificator_output.pickle"),
os.path.join(TMP_PATH, "speeder_input.pickle"),
"--skip",
str(SKIP_FRAMES_NUM)])
print("Running speeder.py...")
subprocess.check_call([
"python3",
"speeder.py",
args.sequence_path,
os.path.join(TMP_PATH, "speeder_input.pickle")])
if __name__ == "__main__":
main()
<file_sep>import argparse
import os
import pickle
import copy
def main():
parser = argparse.ArgumentParser()
parser.add_argument("sequence_path")
parser.add_argument("test_pickle_path")
parser.add_argument("output_path")
parser.add_argument("--skip", type=int, default=1)
args = parser.parse_args()
with open(args.test_pickle_path, "rb") as fin:
pickle_row = pickle.load(fin)[0]
sequence_rows = []
index = 0
files = sorted(os.listdir(args.sequence_path), reverse=True)
files = list(filter(lambda x: x.endswith(".pnm"), files))
for file_name in files:
index += 1
if (index - 1) % args.skip != 0 and file_name != files[-1]:
continue
row = copy.deepcopy(pickle_row)
row["filename"] = os.path.join(args.sequence_path, file_name)
sequence_rows.append(row)
with open(args.output_path, "wb") as fout:
pickle.dump(sequence_rows, fout)
if __name__ == "__main__":
main()
<file_sep>import os
import json
import pandas as pd
from PIL import Image
from tqdm import *
import numpy as np
import pickle
from shutil import copyfile
from mmdet.apis import init_detector, inference_detector, show_result
import glob
import torch.utils.data as data
from PIL import Image
import os
import os.path
import cv2
import sys
from copy import deepcopy
import torchvision
import torch
from mmdet.ops.nms import nms_cpu, nms
from skimage.feature import match_template
from skimage.color import rgb2gray
import numpy as np
import time
def hw_to_min_max(box):
return list(map(float, [box[0], box[1], box[2]+box[0], box[3]+box[1]]))
def min_max_to_hw(cur_box):
return (cur_box[0], cur_box[1], cur_box[2] - cur_box[0], cur_box[3] - cur_box[1])
def square_from_hw(cur_box):
return cur_box[2] * cur_box[3]
def scale_translate(image, x, y):
# Define the translation matrix and perform the translation
M = np.float32([[1, 0, x], [0, 1, y]])
shifted = cv2.warpAffine(image, M, (image.shape[1], image.shape[0]))
# Return the translated image
return shifted
def scale_rotate(image, angle, center = None, scale = 1.0):
# Grab the dimensions of the image
(h, w) = image.shape[:2]
# If the center is None, initialize it as the center of
# the image
if center is None:
center = (w / 2, h / 2)
# Perform the rotation
M = cv2.getRotationMatrix2D(center, angle, scale)
rotated = cv2.warpAffine(image, M, (w, h))
# Return the rotated image
return rotated
def scale_resize(image, width = None, height = None, inter = cv2.INTER_CUBIC):
# initialize the dimensions of the image to be resized and
# grab the image size
dim = None
(h, w) = image.shape[:2]
# if both the width and height are None, then return the
# original image
if width is None and height is None:
return image
# check to see if the width is None
if width is None:
# calculate the ratio of the height and construct the
# dimensions
r = height / float(h)
dim = (int(w * r), height)
# otherwise, the height is None
else:
# calculate the ratio of the width and construct the
# dimensions
r = width / float(w)
dim = (width, int(h * r))
# resize the image
resized = cv2.resize(image, dim, interpolation = inter)
# return the resized image
return resized
def iou(boxA, boxB):
# determine the (x, y)-coordinates of the intersection rectangle
boxA = hw_to_min_max(boxA)
boxB = hw_to_min_max(boxB)
xA = max(boxA[0], boxB[0])
yA = max(boxA[1], boxB[1])
xB = min(boxA[2], boxB[2])
yB = min(boxA[3], boxB[3])
# compute the area of intersection rectangle
interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)
# compute the area of both the prediction and ground-truth
# rectangles
boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)
boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)
# compute the intersection over union by taking the intersection
# area and dividing it by the sum of prediction + ground-truth
# areas - the interesection area
iou = interArea / float(boxAArea + boxBArea - interArea)
# return the intersection over union value
return iou
def filter_all_predictions(predictions, pred_threshold, iou_nms_threshold, min_bbox_square):
result = []
for frame in predictions:
new_bboxes = []
for class_id, bboxes in enumerate(frame):
for bbox in bboxes:
bbox = list(bbox) + [class_id]
if square_from_hw(min_max_to_hw(bbox[:-2])) < min_bbox_square:
continue
new_bboxes.append(bbox)
if len(new_bboxes) == 0:
result.append([])
continue
bboxes = np.array(new_bboxes)
indices = nms(bboxes[:, :-1], iou_nms_threshold)[1]
bboxes = bboxes[indices]
bboxes = bboxes[bboxes[:, -2] >= pred_threshold]
frame_bboxes = []
for bbox in bboxes:
frame_bboxes.append(list(min_max_to_hw(bbox[:-2])) + [int(bbox[-1])])
result.append(frame_bboxes)
return result
def default_loader(path):
return Image.open(path)#.convert('RGB')
def default_flist_reader(flist):
"""
flist format: impath label\nimpath label\n ...(same to caffe's filelist)
"""
imlist = []
with open(flist, 'r') as rf:
for line in rf.readlines():
impath, imlabel = line.strip().split()
imlist.append( (impath, int(imlabel)) )
return imlist
class ImageFilelist(data.Dataset):
def __init__(self, images_data_path, flist, loader=default_loader):
self.images_data_path = images_data_path
self.imlist = flist
self.loader = loader
def __getitem__(self, index):
impath = self.imlist[index]
target = 0
#img = self.loader(os.path.join(self.images_data_path, impath))
arr_img = cv2.imread(os.path.join(self.images_data_path, impath))
arr_img = cv2.cvtColor(arr_img, cv2.COLOR_BGR2GRAY)
#arr_img = np.array(img.convert('RGB'))
#img.close()
return [arr_img, target]
def __len__(self):
return len(self.imlist)
<file_sep>import argparse
import pickle
import numpy as np
from mmdet.ops.nms import nms
PRED_THRESHOLD = 0.55
IOU_NMS_THRESHOLD = 0.05
MIN_BBOX_SQUARE = 100
def min_max_to_hw(cur_box):
return cur_box[0], cur_box[1], cur_box[2] - cur_box[0], cur_box[3] - cur_box[1]
def square_from_hw(cur_box):
return cur_box[2] * cur_box[3]
def filter_all_predictions(predictions, pred_threshold, iou_nms_threshold, min_bbox_square):
result = []
for frame in predictions:
new_bboxes = []
for class_id, bboxes in enumerate(frame):
for bbox in bboxes:
bbox = list(bbox) + [class_id]
if square_from_hw(min_max_to_hw(bbox[:-2])) < min_bbox_square:
continue
new_bboxes.append(bbox)
if len(new_bboxes) == 0:
result.append([])
continue
bboxes = np.array(new_bboxes)
indices = nms(bboxes[:, :-1], iou_nms_threshold)[1]
bboxes = bboxes[indices]
bboxes = bboxes[bboxes[:, -2] >= pred_threshold]
frame_bboxes = []
for bbox in bboxes:
frame_bboxes.append(list(min_max_to_hw(bbox[:-2])) + [int(bbox[-1])])
result.append(frame_bboxes)
return result
def main():
parser = argparse.ArgumentParser()
parser.add_argument("predictions_path")
parser.add_argument("output_path")
args = parser.parse_args()
with open(args.predictions_path, 'rb') as fin:
detector_predictions = filter_all_predictions(
pickle.load(fin),
PRED_THRESHOLD,
IOU_NMS_THRESHOLD,
MIN_BBOX_SQUARE)
with open(args.output_path, "wb") as fout:
pickle.dump(detector_predictions, fout)
if __name__ == "__main__":
main()
<file_sep>from pipeline.utils import load_predict_config, run_predict
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument("config_path")
args = parser.parse_args()
config = load_predict_config(args.config_path)
run_predict(config)
if __name__ == "__main__":
main()
<file_sep>import glob
import os
import pickle
from random import sample
import numpy as np
import p_tqdm
import pandas as pd
from PIL import Image
from tqdm import tqdm
save_path = '/group-volume/orc_srr/multimodal/iceblood/datasets/main/TRAIN/'
save_path_val = '/group-volume/orc_srr/multimodal/iceblood/datasets/main/TEST/'
datasets_list = ['/group-volume/orc_srr/multimodal/iceblood/datasets/main/TRAIN/skolkovo/',
'/group-volume/orc_srr/multimodal/iceblood/datasets/main/TRAIN/RTSD/',
'/group-volume/orc_srr/multimodal/iceblood/datasets/main/TEST/']
class_precision = 3
sign_min_size = 10 * 10
convert_class = lambda x: '.'.join(str(x).split('.')[:class_precision])
datasets_dataframes = []
for dataset_path in datasets_list:
df = pd.read_csv(glob.glob(os.path.join(dataset_path, '*.csv'))[0])
df['path'] = df['path'].apply(lambda x: os.path.join(dataset_path, x))
df['class'] = df['class'].apply(lambda x: str(x))
datasets_dataframes.append(df)
print(df.shape)
print(df['path'].nunique())
result_df = pd.concat(datasets_dataframes)
result_df = result_df.reset_index()
all_classes = [convert_class(x) for x in sorted(result_df['class'].unique())]
with open('temp_all_classes.txt', 'w') as f:
for item in all_classes:
f.write(item)
f.write('\n')
result_df = result_df.reindex(sorted(result_df.columns), axis=1)
def df_to_annontation(path, df, classes):
frame_df = df[df['path'] == path]
annotation = {}
if os.path.exists(path):
im = Image.open(path)
else:
return None
width, height = im.size
annotation['filename'] = path
annotation['width'] = width
annotation['height'] = height
annotation['ann'] = {}
bboxes = []
labels = []
temporary = []
occluded = []
ignored_bboxes = []
ignored_labels = []
ignored_temporary = []
ignored_occluded = []
for index, row in frame_df.iterrows():
cur_cls = row['class']
xbr = row['xbr']
xtl = row['xtl']
ybr = row['ybr']
ytl = row['ytl']
temp = row['temporary']
ocl = row['occluded']
cur_cls = convert_class(cur_cls)
if cur_cls in classes:
if ((ybr - ytl) * (xbr - xtl) >= sign_min_size):
labels.append(classes.index(cur_cls) + 1)
bboxes.append([xtl, ytl, xbr, ybr])
temporary.append(temp)
occluded.append(ocl)
else:
ignored_labels.append(classes.index(cur_cls) + 1)
ignored_bboxes.append([xtl, ytl, xbr, ybr])
ignored_temporary.append(temp)
ignored_occluded.append(ocl)
annotation['ann']['bboxes'] = np.array(bboxes).astype(np.float32)
annotation['ann']['labels'] = np.array(labels).astype(np.int64)
annotation['ann']['temporary'] = np.array(temporary).astype(np.float32)
annotation['ann']['occluded'] = np.array(occluded).astype(np.float32)
annotation['ann']['bboxes_ignore'] = np.array(ignored_bboxes).astype(np.float32)
annotation['ann']['labels_ignore'] = np.array(ignored_labels).astype(np.int64)
annotation['ann']['temporary_ignore'] = np.array(ignored_temporary).astype(np.float32)
annotation['ann']['occluded_ignore'] = np.array(ignored_occluded).astype(np.float32)
if len(bboxes):
return annotation
annotations = p_tqdm.p_map(lambda x: df_to_annontation(x, result_df, all_classes),
list(result_df['path'].unique()))
annotations_skolkovo = list(filter(None, annotations[:4915]))
annotations_vmk = list(filter(None, annotations[4915:64103]))
annotations_final = list(filter(None, annotations[64103:]))
with open(os.path.join(save_path, 'first_part_skolkovo.pickle'), 'wb') as handle:
pickle.dump(annotations_skolkovo, handle, protocol=pickle.HIGHEST_PROTOCOL)
with open(os.path.join(save_path, 'full_russia_vmk.pickle'), 'wb') as handle:
pickle.dump(annotations_vmk, handle, protocol=pickle.HIGHEST_PROTOCOL)
with open(os.path.join(save_path_val, 'final_skolkovo.pickle'), 'wb') as handle:
pickle.dump(annotations_final, handle, protocol=pickle.HIGHEST_PROTOCOL)
with open(os.path.join(save_path_val, 'final_val.pickle'), 'wb') as handle:
pickle.dump(sample(annotations_final, 100), handle, protocol=pickle.HIGHEST_PROTOCOL)
def bin_ann(ann):
ann['ann']['labels'] = np.array([1 if x > 0 else 0 for x in ann['ann']['labels']])
pickle_out = open(os.path.join(save_path, 'first_part_skolkovo.pickle'), "rb")
first_part_skolkovo1 = pickle.load(pickle_out)
pickle_out = open(os.path.join(save_path, 'full_russia_vmk.pickle'), "rb")
full_russia_vmk1 = pickle.load(pickle_out)
pickle_out = open(os.path.join(save_path_val, 'final_skolkovo.pickle'), "rb")
final_skolkovo1 = pickle.load(pickle_out)
pickle_out = open(os.path.join(save_path_val, 'final_val.pickle'), "rb")
final_val1 = pickle.load(pickle_out)
_ = [bin_ann(x) for x in full_russia_vmk1]
_ = [bin_ann(x) for x in first_part_skolkovo1]
_ = [bin_ann(x) for x in final_val1]
_ = [bin_ann(x) for x in final_skolkovo1]
with open(os.path.join(save_path, 'first_part_skolkovo_bin.pickle'), 'wb') as handle:
pickle.dump(first_part_skolkovo1, handle, protocol=pickle.HIGHEST_PROTOCOL)
with open(os.path.join(save_path, 'full_russia_vmk_bin.pickle'), 'wb') as handle:
pickle.dump(full_russia_vmk1, handle, protocol=pickle.HIGHEST_PROTOCOL)
with open(os.path.join(save_path_val, 'final_skolkovo_bin.pickle'), 'wb') as handle:
pickle.dump(final_skolkovo1, handle, protocol=pickle.HIGHEST_PROTOCOL)
with open(os.path.join(save_path_val, 'final_val_bin.pickle'), 'wb') as handle:
pickle.dump(final_val1, handle, protocol=pickle.HIGHEST_PROTOCOL)
imgs = glob.glob('/group-volume/orc_srr/multimodal/iceblood/datasets/main/TEST/**', recursive=True)
imgs = sorted(list(filter(lambda x: '.jpg' in x, imgs)))[::-1]
all_anno_custom_test = []
for cur_img in tqdm(imgs):
# im = Image.open(cur_img)
cur_img = '/'.join(cur_img.split('/')[-3:])
tmp_dice = {}
tmp_dice['filename'] = '/group-volume/orc_srr/multimodal/iceblood/datasets/main/' + cur_img
# im = Image.open(cur_img)
# width, height = im.size
tmp_dice['width'] = 2448 # width
tmp_dice['height'] = 2048 # height
tmp_dice['ann'] = {}
bboxes = []
labels = []
ignored_bboxes = []
ignored_labels = []
tmp_dice['ann']['bboxes'] = np.array(bboxes).astype(np.float32)
tmp_dice['ann']['labels'] = np.array(labels).astype(np.int64)
tmp_dice['ann']['bboxes_ignore'] = np.array(ignored_bboxes).astype(np.float32)
tmp_dice['ann']['labels_ignore'] = np.array(ignored_labels).astype(np.int64)
all_anno_custom_test.append(tmp_dice)
with open('/group-volume/orc_srr/multimodal/iceblood/datasets/main/TEST/skolkovo_test_file.pickle', 'wb') as outfile:
pickle.dump(all_anno_custom_test, outfile)
<file_sep>import argparse
import pickle
import joblib
from PIL import Image
import cv2
import numpy as np
N_JOBS = 16
def crop_image(image, bbox):
return image.crop(bbox)
def histeq(image):
reshaped = image.reshape((image.shape[0] * image.shape[1], 3)).astype("float32")
y = (reshaped[:, 0] * 1 + reshaped[:, 1] * 1 + reshaped[:, 2] * 2) / 4
y = y.astype("uint8")
hist = np.bincount(y, minlength=256).astype("float32")
hist_sum = np.cumsum(hist)
max_value = hist_sum[-1] / 255
map_value = (hist_sum / max_value).astype("uint8")
return map_value[image]
def load_img(path):
img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
img = cv2.cvtColor(img, cv2.COLOR_BAYER_RG2RGB)
img = histeq(img)
return Image.fromarray(img)
def extract_bboxes(annotation, bboxes):
result = []
image = load_img(annotation["filename"])
for bbox in bboxes:
data = {
"bbox": bbox,
"cropped_image": crop_image(
image, [int(bbox[0]), int(bbox[1]), int(bbox[2] + bbox[0]), int(bbox[3] + bbox[1])]),
"filename": annotation["filename"]
}
result.append(data)
return result
def main():
parser = argparse.ArgumentParser()
parser.add_argument("annotations_path")
parser.add_argument("bboxes_predict_path")
parser.add_argument("output_path")
args = parser.parse_args()
with open(args.annotations_path, "rb") as fin:
annotations = pickle.load(fin)
with open(args.bboxes_predict_path, "rb") as fin:
bboxes_predict = pickle.load(fin)
p = joblib.Parallel(n_jobs=N_JOBS, backend="multiprocessing", verbose=5)
extracted_bboxes = p(
joblib.delayed(extract_bboxes)(annotation, bboxes) for annotation, bboxes in zip(annotations, bboxes_predict))
result = []
for bboxes in extracted_bboxes:
result += bboxes
with open(args.output_path, "wb") as fout:
pickle.dump(result, fout)
if __name__ == "__main__":
main()
<file_sep>import random
import imgaug.augmenters as iaa
import numpy as np
import torch
import torch.nn as nn
from PIL import Image
from torchvision.transforms import ToTensor, Normalize, Compose, RandomAffine
from sign_pipeline.associated import AVAILABLE_CLASSES
from .base import ConfigSignBase, PredictConfigSignBase
from pretrainedmodels import se_resnext50_32x4d
MODEL_SAVE_PATH = "models/sign_resnet50_0_7"
BATCH_SIZE = 128
SEED = 85
random.seed(SEED)
np.random.seed(SEED)
torch.random.manual_seed(SEED)
class ImgAugTransforms:
def __init__(self):
self._seq = iaa.Sequential([
iaa.Sharpen(alpha=(0, 1.0), lightness=(0.75, 1.5)),
iaa.Emboss(alpha=(0, 1.0), strength=(0, 2.0)),
iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.05 * 255), per_channel=0.5),
iaa.Invert(0.05, per_channel=True),
iaa.ContrastNormalization((0.5, 2.0), per_channel=0.5),
])
def __call__(self, image):
image = np.array(image)
image = self._seq.augment_image(image)
return Image.fromarray(image)
def get_model():
model = se_resnext50_32x4d()
model.avg_pool = nn.AdaptiveAvgPool2d(1)
model.last_linear = nn.Linear(model.last_linear.in_features, len(AVAILABLE_CLASSES) + 2)
return model
class Config(ConfigSignBase):
def __init__(self):
model = get_model()
train_transforms = Compose([
RandomAffine(degrees=20, scale=(0.8, 1.1)),
ImgAugTransforms(),
ToTensor(),
Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
])
val_transforms = Compose([
ToTensor(),
Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
])
super().__init__(
model=model,
model_save_path=MODEL_SAVE_PATH,
epoch_count=100,
batch_size=BATCH_SIZE,
train_transforms=train_transforms,
val_transforms=val_transforms,
mixup_alpha=0.7)
class PredictConfig(PredictConfigSignBase):
def __init__(self):
transforms = Compose([ToTensor(), Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))])
super().__init__(
model=get_model(), model_save_path=MODEL_SAVE_PATH, batch_size=BATCH_SIZE, transforms=transforms)
<file_sep>import random
import numpy as np
import torch
import torch.nn as nn
from torchvision.models.resnet import resnet34
from torchvision.transforms import ToTensor, Normalize, Compose, RandomAffine
from .base import ConfigSignBase, PredictConfigSignBase
from sign_pipeline.associated import AVAILABLE_CLASSES
MODEL_SAVE_PATH = "models/sign_resnet34"
BATCH_SIZE = 128
SEED = 85
random.seed(SEED)
np.random.seed(SEED)
torch.random.manual_seed(SEED)
def get_model():
model = resnet34(pretrained=True)
model.fc = nn.Linear(model.fc.in_features, len(AVAILABLE_CLASSES) + 2)
return model
class Config(ConfigSignBase):
def __init__(self):
model = get_model()
train_transforms = Compose([
RandomAffine(degrees=20, scale=(0.8, 1.1)),
ToTensor(),
Normalize((0.5, 0.5, 0.5), (0.2, 0.2, 0.2))
])
val_transforms = Compose([
ToTensor(),
Normalize((0.5, 0.5, 0.5), (0.2, 0.2, 0.2))
])
super().__init__(
model=model,
model_save_path=MODEL_SAVE_PATH,
epoch_count=100,
batch_size=BATCH_SIZE,
train_transforms=train_transforms,
val_transforms=val_transforms,
mixup_alpha=0.0)
class PredictConfig(PredictConfigSignBase):
def __init__(self):
super().__init__(
model=get_model(), model_save_path=MODEL_SAVE_PATH, batch_size=BATCH_SIZE)
<file_sep>import glob
import os
import os.path
import pickle
import time
import cv2
import argparse
import numpy as np
import torch
import torch.utils.data as data
from PIL import Image
from sign_pipeline.associated import AVAILABLE_CLASSES
ALL_CLASSES_PATH = "/root/all_classes.txt"
SUBMIT_PATH = "/root/submit.tsv"
PRED_THRESHOLD = 0.65
IOU_NMS_THRESHOLD = 0.05
MIN_BBOX_SQUARE = 100
TRACKING_MIN_IOU = 0.001
TRACKING_IOU_INTERPOLATE = 1 # 0.9
TRACKING_MIN_CORRELATION = 0.3
TRACKING_MAX_DISTANCE_PIXELS = 250
BIG_CROP_PADDING = 20
TEMPORARY_THRESHOLD = 0.51 # TODO CHANGE IT
ASSOCIATED_THRESHOLD = 0.01 # TODO CHANGE IT
NUM_WORKERS = 4
POINTS = 2
def histeq(image):
reshaped = image.reshape((image.shape[0] * image.shape[1], 3)).astype("float32")
y = (reshaped[:, 0] * 1 + reshaped[:, 1] * 1 + reshaped[:, 2] * 2) / 4
y = y.astype("uint8")
hist = np.bincount(y, minlength=256).astype("float32")
hist_sum = np.cumsum(hist)
max_value = hist_sum[-1] / 255
map_value = (hist_sum / max_value).astype("uint8")
return map_value[image]
def load_img(path):
img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
img = cv2.cvtColor(img, cv2.COLOR_BAYER_RG2RGB)
img = histeq(img)
return img
def hw_to_min_max(box):
return list(map(float, [box[0], box[1], box[2] + box[0], box[3] + box[1]]))
def min_max_to_hw(cur_box):
return (cur_box[0], cur_box[1], cur_box[2] - cur_box[0], cur_box[3] - cur_box[1])
def iou(boxA, boxB):
# determine the (x, y)-coordinates of the intersection rectangle
boxA = hw_to_min_max(boxA)
boxB = hw_to_min_max(boxB)
xA = max(boxA[0], boxB[0])
yA = max(boxA[1], boxB[1])
xB = min(boxA[2], boxB[2])
yB = min(boxA[3], boxB[3])
# compute the area of intersection rectangle
interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)
# compute the area of both the prediction and ground-truth
# rectangles
boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)
boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)
# compute the intersection over union by taking the intersection
# area and dividing it by the sum of prediction + ground-truth
# areas - the interesection area
iou = interArea / float(boxAArea + boxBArea - interArea)
# return the intersection over union value
return iou
def default_loader(path):
return Image.open(path) # .convert('RGB')
def default_flist_reader(flist):
"""
flist format: impath label\nimpath label\n ...(same to caffe's filelist)
"""
imlist = []
with open(flist, 'r') as rf:
for line in rf.readlines():
impath, imlabel = line.strip().split()
imlist.append((impath, int(imlabel)))
return imlist
class ImageFilelist(data.Dataset):
def __init__(self, images_data_path, flist, loader=default_loader):
self.images_data_path = images_data_path
self.imlist = flist
self.loader = loader
def __getitem__(self, index):
impath = self.imlist[index]
target = 0
# img = self.loader(os.path.join(self.images_data_path, impath))
if True:
arr_img = cv2.imread(impath)
else:
arr_img = load_img(impath)
arr_img = cv2.cvtColor(arr_img, cv2.COLOR_BGR2GRAY)
# arr_img = np.array(img.convert('RGB'))
# img.close()
return [arr_img, target]
def __len__(self):
return len(self.imlist)
def match_bboxes_iou(start_frame_bboxes, finish_frame_bboxes):
# Returns list of pairs (start_bbox, finish_bbox, start_bbox_index, finish_bbox_index)
# where each bbox is a pair (bbox, class_id, temporary, associated_class_id)
start_to_finish_iou = []
for i, start_bbox in enumerate(start_frame_bboxes):
for j, finish_bbox in enumerate(finish_frame_bboxes):
score = iou(start_bbox[0], finish_bbox[0])
if start_bbox[1] != finish_bbox[1]:
score = 0
start_to_finish_iou.append((score, i, j))
start_to_finish_iou.sort(key=lambda x: x[0], reverse=True)
matched_pairs = []
used_start_bboxes = set()
used_finish_bboxes = set()
for score, i, j in start_to_finish_iou:
if score < TRACKING_MIN_IOU:
break
if i in used_start_bboxes or j in used_finish_bboxes:
continue
start_bbox = start_frame_bboxes[i]
finish_bbox = finish_frame_bboxes[j]
matched_pairs.append((start_bbox, finish_bbox, i, j))
used_start_bboxes.add(i)
used_finish_bboxes.add(j)
return matched_pairs
def get_distance_between_bboxes(start_bbox, finish_bbox):
distance = (start_bbox[0] - finish_bbox[0]) ** 2 + (start_bbox[1] - finish_bbox[1]) ** 2
return distance ** (1 / 2.)
def match_bboxes_template(start_frame, finish_frame):
# Returns list of pairs (start_bbox, finish_bbox, start_bbox_index, finish_bbox_index)
# where each bbox is a pair (bbox, class_id, temporary, associated_class_id)
start_frame_bboxes = start_frame[0]
finish_frame_bboxes = finish_frame[0]
start_frame_img = start_frame[1]
finish_frame_img = finish_frame[1]
start_to_finish_iou = []
for i, start_bbox in enumerate(start_frame_bboxes):
for j, finish_bbox in enumerate(finish_frame_bboxes):
if start_bbox[1] != finish_bbox[1]:
continue
distance = get_distance_between_bboxes(start_bbox[0], finish_bbox[0])
if distance > TRACKING_MAX_DISTANCE_PIXELS:
continue
start_crop = start_frame_img[
int(start_bbox[0][1]):int(start_bbox[0][1] + start_bbox[0][3]),
int(start_bbox[0][0]):int(start_bbox[0][0] + start_bbox[0][2])]
finish_crop = finish_frame_img[
int(finish_bbox[0][1]):int(finish_bbox[0][1] + finish_bbox[0][3]),
int(finish_bbox[0][0]):int(finish_bbox[0][0] + finish_bbox[0][2])]
h = min(start_crop.shape[0], finish_crop.shape[0])
w = min(start_crop.shape[1], finish_crop.shape[1])
start_crop = cv2.resize(start_crop, (w, h))
finish_crop = cv2.resize(finish_crop, (w, h))
score = cv2.matchTemplate(start_crop, finish_crop, cv2.TM_CCOEFF_NORMED)[0][0]
start_to_finish_iou.append((score, i, j))
start_to_finish_iou.sort(key=lambda x: x[0], reverse=True)
matched_pairs = []
used_start_bboxes = set()
used_finish_bboxes = set()
for score, i, j in start_to_finish_iou:
if score < TRACKING_MIN_CORRELATION:
break
if i in used_start_bboxes or j in used_finish_bboxes:
continue
start_bbox = start_frame_bboxes[i]
finish_bbox = finish_frame_bboxes[j]
matched_pairs.append((start_bbox, finish_bbox, i, j))
used_start_bboxes.add(i)
used_finish_bboxes.add(j)
return matched_pairs
def match_bboxes(start_frame, finish_frame):
# Returns list of pairs (start_bbox, finish_bbox)
# where each bbox is a pair (bbox, class_id, temporary, associated_class_id)
matched_pairs = []
matched_pairs_iou = match_bboxes_iou(start_frame[0], finish_frame[0])
start_bbox_indices_to_remove = set()
finish_bbox_indices_to_remove = set()
for start_bbox, finish_bbox, start_bbox_index, finish_bbox_index in matched_pairs_iou:
start_bbox_indices_to_remove.add(start_bbox_index)
finish_bbox_indices_to_remove.add(finish_bbox_index)
matched_pairs.append((start_bbox, finish_bbox))
new_start_frame_bboxes = []
new_finish_frame_bboxes = []
for i, bbox in enumerate(start_frame[0]):
if i not in start_bbox_indices_to_remove:
new_start_frame_bboxes.append(bbox)
for j, bbox in enumerate(finish_frame[0]):
if j not in finish_bbox_indices_to_remove:
new_finish_frame_bboxes.append(bbox)
start_frame = [new_start_frame_bboxes, start_frame[1]]
finish_frame = [new_finish_frame_bboxes, finish_frame[1]]
matched_pairs_template = match_bboxes_template(start_frame, finish_frame)
for start_bbox, finish_bbox, start_bbox_index, finish_bbox_index in matched_pairs_template:
matched_pairs.append((start_bbox, finish_bbox))
return matched_pairs
def run_tracking(sequence_tracking):
result = []
start_frame = sequence_tracking[0]
finish_frame = sequence_tracking[-1]
start_frame_img = start_frame[1]
finish_frame_img = finish_frame[1]
interpolate_frames = sequence_tracking[1:-1]
matched_bboxes = match_bboxes(start_frame, finish_frame)
for frame_num, (_, image) in enumerate(interpolate_frames):
frame_bboxes = []
for start_bbox, finish_bbox in matched_bboxes:
class_id = start_bbox[1]
temporary = start_bbox[2]
associated_class_id = start_bbox[3]
start_bbox = start_bbox[0]
finish_bbox = finish_bbox[0]
start_bbox_size = [start_bbox[2], start_bbox[3]]
finish_bbox_size = [finish_bbox[2], finish_bbox[3]]
bbox_diff = [
finish_bbox[0] - start_bbox[0],
finish_bbox[1] - start_bbox[1],
finish_bbox[2] - start_bbox[2],
finish_bbox[3] - start_bbox[3]]
new_coarse_bbox = start_bbox[:]
for i in range(4):
new_coarse_bbox[i] += bbox_diff[i] / (len(interpolate_frames) + 1) * (frame_num + 1)
if iou(start_bbox, finish_bbox) > TRACKING_IOU_INTERPOLATE:
frame_bboxes.append((new_coarse_bbox, class_id, temporary, associated_class_id))
continue
start_bbox = hw_to_min_max(start_bbox)
finish_bbox = hw_to_min_max(finish_bbox)
bbox_find_area = [
min(start_bbox[0], finish_bbox[0]) - BIG_CROP_PADDING,
min(start_bbox[1], finish_bbox[1]) - BIG_CROP_PADDING,
max(start_bbox[2], finish_bbox[2]) + BIG_CROP_PADDING,
max(start_bbox[3], finish_bbox[3]) + BIG_CROP_PADDING
]
bbox_find_area = [
max(bbox_find_area[0], 0),
max(bbox_find_area[1], 0),
min(bbox_find_area[2], image.shape[1]),
min(bbox_find_area[3], image.shape[0]),
]
crop_proposals = []
start_crop = start_frame_img[
int(start_bbox[1]):int(start_bbox[3]),
int(start_bbox[0]):int(start_bbox[2])]
# crop_proposals.append((start_crop, start_bbox_size[0], start_bbox_size[1]))
# finish_crop = finish_frame_img[
# int(finish_bbox[1]):int(finish_bbox[3]),
# int(finish_bbox[0]):int(finish_bbox[2])]
# crop_proposals.append((finish_crop, finish_bbox_size[0], finish_bbox_size[1]))
estimated_crop = cv2.resize(start_crop, (int(new_coarse_bbox[2]), int(new_coarse_bbox[3])))
crop_proposals.append((estimated_crop, estimated_crop.shape[1], estimated_crop.shape[0]))
find_area_crop = image[
int(bbox_find_area[1]):int(bbox_find_area[3]),
int(bbox_find_area[0]):int(bbox_find_area[2])]
crop_proposals_scores = []
for crop_proposal in crop_proposals:
score = cv2.matchTemplate(find_area_crop, crop_proposal[0], cv2.TM_CCOEFF_NORMED)
score_argmax = np.argmax(score)
crop_proposals_scores.append((score_argmax, score, crop_proposal[1], crop_proposal[2]))
best_proposal = max(crop_proposals_scores, key=lambda x: x[0])
match_result = np.unravel_index(best_proposal[0], best_proposal[1].shape)
new_y_min = float(match_result[0] + int(bbox_find_area[1]))
new_x_min = float(match_result[1] + int(bbox_find_area[0]))
new_y_max = new_y_min + best_proposal[3]
new_x_max = new_x_min + best_proposal[2]
new_bbox = [new_x_min, new_y_min, new_x_max, new_y_max]
new_bbox = min_max_to_hw(new_bbox)
frame_bboxes.append((new_bbox, class_id, temporary, associated_class_id))
result.append(frame_bboxes)
result.append(finish_frame[0])
return result
def write_submit(submit_path, selected_filenames, final_boxes):
with open(ALL_CLASSES_PATH) as f:
all_pos_classes = f.read().split()
convert_class = lambda x: '.'.join(str(x).split('.')[:POINTS])
all_pos_classes = [convert_class(sign) for sign in all_pos_classes]
mode = "w"
if os.path.exists(submit_path):
mode = "a"
with open(submit_path, mode) as f:
if mode == "w":
f.write('\t'.join(['frame', 'xtl', 'ytl', 'xbr', 'ybr', 'class', 'temporary', 'data']) + '\n')
for ind in range(len(selected_filenames)):
img_name = selected_filenames[ind]
img_name = img_name.replace('.pnm', '')
img_name = "/".join(img_name.split("/")[-2:])
for bbox, class_id, temporary, associated_class_id in final_boxes[ind]:
class_id = int(class_id)
class_name = all_pos_classes[class_id]
if class_id == len(all_pos_classes) - 1:
continue
bbox = hw_to_min_max(bbox)
bbox = list(map(lambda x: str(int(x)), bbox))
temporary = "true" if temporary == 1 else "false"
associated_class_name = ""
if associated_class_id < len(AVAILABLE_CLASSES):
associated_class_name = AVAILABLE_CLASSES[associated_class_id]
f.write('\t'.join([img_name, *bbox, class_name, temporary, associated_class_name]) + '\n')
def main():
parser = argparse.ArgumentParser()
parser.add_argument("sequence_path")
parser.add_argument("predictions_path")
args = parser.parse_args()
with open(args.predictions_path, 'rb') as fin:
detector_predictions = pickle.load(fin)
file_names = []
for cur_img in glob.glob(args.sequence_path + "/**", recursive=True):
if not ".pnm" in cur_img:
continue
file_names.append(cur_img)
file_names = np.array(file_names)
video_seq = np.argsort(file_names)[::-1]
selected_filenames = file_names[video_seq]
dataset = ImageFilelist(args.sequence_path, selected_filenames)
loader = torch.utils.data.DataLoader(dataset,
shuffle=False,
num_workers=NUM_WORKERS)
loader = iter(loader)
final_boxes = []
start_time = time.time()
current_sequence_tracking = []
current_sequence_index = 0
for ind in range(len(selected_filenames)):
cur_img_gray = next(loader)[0][0].data.numpy()
frame_predictions = detector_predictions[ind]
frame_final_boxes = []
if frame_predictions is not None:
frame_final_boxes = []
for prediction in frame_predictions:
bbox = prediction[0][:4]
class_id = int(prediction[0][4])
associated_class_id = prediction[1]
associated_prob = prediction[2]
temporary_prob = prediction[3]
temporary = 1 if temporary_prob > TEMPORARY_THRESHOLD else 0
associated_class_id = associated_class_id \
if associated_prob > ASSOCIATED_THRESHOLD else len(AVAILABLE_CLASSES)
frame_final_boxes.append((bbox, class_id, temporary, associated_class_id))
current_sequence_tracking.append((frame_final_boxes, cur_img_gray))
if frame_predictions is not None and len(current_sequence_tracking) > 1:
if current_sequence_index == 0:
final_boxes.append(current_sequence_tracking[0][0])
current_sequence_index += 1
for boxes in run_tracking(current_sequence_tracking):
final_boxes.append(boxes)
current_sequence_tracking = [current_sequence_tracking[-1]]
current_time = int(time.time() - start_time)
time_per_iter = (time.time() - start_time) / (ind + 1)
eta_time = int((len(selected_filenames) - ind) * time_per_iter)
print("\rIndex: {}. Time: {} s. ETA: {} s".format(ind, current_time, eta_time), end="")
if len(current_sequence_tracking) > 0:
for boxes, _ in current_sequence_tracking[1:]:
final_boxes.append(boxes)
write_submit(SUBMIT_PATH, selected_filenames, final_boxes)
if __name__ == "__main__":
main()
|
739f46a90875fe96a780e07aa3fc77d2d66033b7
|
[
"Python"
] | 25 |
Python
|
gamers5a/SignDetection
|
f46f76feb589ecc6416720d5d95b6ccbf94acb74
|
b46c7889e9464ad0ac84bc445f9530e5948899de
|
refs/heads/master
|
<file_sep>package com.challenge.java.controller;
import java.util.ArrayList;
import java.util.HashMap;
import com.challenge.java.model.Board;
import com.challenge.java.model.Piece;
import com.challenge.java.model.PieceFactory;
public class Resolve {
/**
*
* @param board - Board details
* @param boards - All solution boards
* @param lastPieces - Last position for each kind of piece in the board
* @throws IOException
*/
public void resolve(Board board, HashMap<String, Board> boards, HashMap<String, Piece> lastPieces, boolean printBoards) {
ArrayList<String> remainingPieces = board.getRemainingPieces();
// Take the first available piece
String piece = remainingPieces.remove(0);
// Last piece on the board of this kind
Piece lastPiece = lastPieces.get(piece);
int lastPieceRow = 0;
int lastPieceColumn = 0;
if (lastPiece != null){
// Prune duplicate solutions.
lastPieceRow = lastPiece.getRow();
lastPieceColumn = lastPiece.getCol()+1;
}
for(int row=lastPieceRow; row<board.getRows(); row++){
for(int col=lastPieceColumn; col<board.getColumns(); col++){
// If it isn't empty skip the iteration
if(board.getBoard()[row][col] != null)
continue;
Piece pieceToPut = PieceFactory.getPiece(piece,row, col);
String pieceSymbol = pieceToPut.toString();
// Check if it is possible to put the piece into the board safely
if(!pieceToPut.isPossible(board))
continue;
// Add piece piece to the board as partial solution
board.addPiece(pieceToPut);
lastPieces.put(pieceSymbol, pieceToPut);
String boardPattern = board.boardPattern();
if(remainingPieces.isEmpty()){
// If there is not more pieces is a final solution
// Avoid duplicate results using a unique key (the board itself)
boards.put(boardPattern, board);
if (printBoards)
board.printBoard();
}else{
// Partial solution. Resolve a smaller problem
resolve(board, boards,lastPieces,printBoards);
}
// Backtracking: Remove the piece of the board
board.removePiece(pieceToPut);
}
// Reset column
lastPieceColumn=0;
}
// Backtracking: Return the piece
remainingPieces.add(0, piece);
lastPieces.put(piece, null);
}
}
|
f180de37039b0e86f9110169b4e55322526562f0
|
[
"Java"
] | 1 |
Java
|
AnishAppanath/Chess_Java_Challenge
|
c01edefaccac9b65906566fc9e707889c314f48b
|
0bff82e6dc83504aa860861859e380135364660c
|
refs/heads/master
|
<file_sep>function displaytime() {
const date = new Date();
let hour = date.getHours();
let min = date.getMinutes();
let sec = date.getSeconds();
let date_t = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
let dayDate = date.getDay();
let day = "";
if (dayDate == 1) {
day = "Monday";
} else if (dayDate == 2) {
day = "Tuesday";
} else if (dayDate == 3) {
day = "Wednesday";
} else if (dayDate == 4) {
day = "Thursday";
} else if (dayDate == 5) {
day = "Friday";
} else if (dayDate == 6) {
day = "Saturday";
} else {
day = "Sunday";
}
let hour_elem = document.getElementById("hour");
let min_elem = document.getElementById("min");
let sec_elem = document.getElementById("sec");
let date_elem = document.getElementById("date");
let month_elem = document.getElementById("month");
let year_elem = document.getElementById("year");
let day_elem = document.getElementById("day");
hour_elem.innerHTML = hour;
min_elem.innerHTML = min;
sec_elem.innerHTML = sec;
date_elem.innerHTML = date_t;
month_elem.innerHTML = month;
year_elem.innerHTML = year;
day_elem.innerHTML = day;
}
setInterval(displaytime, 1000);
|
788f9e0d5f2df8f65eff17fcbb2c506ba8252304
|
[
"JavaScript"
] | 1 |
JavaScript
|
PreethamFernandes/JavaScript-Clock
|
454887a9f0d31753448d74248fe77857db579591
|
a2730355726c01a94c240f594ad04468796ba060
|
refs/heads/main
|
<repo_name>RemiChevrier/Piano<file_sep>/TODO.txt
Objectifs de l'application
==========================
Developper une application interactive pour :
- creer des sons
- les visualiser sous forme d'onde
- jouer les sons (notes) sur un clavier de piano sur 1 puis 2 octaves puis 3 ...
- apprendre a reconnaitre les notes au piano (afficher le nom des notes,visualiser la touche correspondante)
- creer des accords majeurs (tonalite-tierce-quinte) a partir des notes (exemple accord Do majeur : C-E-G)
- jouer les accords sur un clavier de piano sur 1 puis 2 octaves puis 3 ...
- apprendre a reconnaitre les accords au piano (afficher le nom et les notes des accords,visualiser les touches correspondantes ...)
Pour aller plus loin :
- apprendre a jouer des renversements d'accords !
Etapes à suivre
===============
1) wave_generator.py : Proposer et implementer une IHM pour creer des sons (notes pures puis harmoniques) au format wav.
2) wave_visualizer.py : Proposer et implementer une IHM pour visualiser un son pur puis un son (une note) avec ses harmoniques.
3) keyboard.py : Proposer et implementer une IHM pour jouer des notes sur un clavier a 1 octave
4) piano.py : Proposer et implementer une IHM pour jouer des notes sur un clavier de piano a 1 puis 2 puis 3... octaves
5) main.py : integration des trois versions dans une seule IHM des versions precedentes
6) Enrichir l'IHM du piano pour :
- apprendre a reconnaitre les notes sur le clavier
- visualiser et jouer des accords au piano
- visualiser et jouer les accords et leur renversement
Répertoires
===========
Audio
-----
- frequencies.py :
- frequencies.py, frequencies.db : stocker dans une table de BD la frequence des notes de gammes musicales
- audio_wav.py : creer des fichiers au format wav pour une frequence (note) donnee (cf : <NAME> ; <NAME>, ...)
- note_read.py,note_save.py : tests de lecture/écriture de fichier au format wav
- create_chords.py : creation d'un accord (3 notes) au format wav
- wav_create_note-0.py : creation d'un son (note) au format wav
- wav_read_note-0.py : lecture d'un son (note) au format wav
- create_notes_from_db.py : creation des notes a partir de la base de données (frequencies.db)
Utils : fonctions utiles
-----
Chords : pour la sauvegarde des accords
------
Sounds : pour la sauvegarde des notes
------
Annexes
=======
Liens utiles pour mettre en place cette application interactive :
- http://fsincere.free.fr/isn/python/cours_python_ch9.php
- http://freesoundeditor.com/docwave.htm
- http://blog.acipo.com/wave-generation-in-python
- https://www.tutorialspoint.com/read-and-write-wav-files-using-python-wave
- https://www.programcreek.com/python/example/82393/wave.open
- https://f5zv.pagesperso-orange.fr/RADIO/RM/RM23/RM23B/RM23B04.htm
- http://tpecan.free.fr/index.php?page=echantillonnage
Archives
========
En fin d'après-midi (17h) rendre une archive du travail du repertoire :
Nom_Prenom_Piano
├── Audio
│ ├── audio_wav.py
│ ├── create_chords.py
│ ├── create_notes_from_db.py
│ ├── frequencies.db
│ ├── frequencies.py
│ ├── note_read.py
│ ├── note_save.py
│ └── __pycache__
│ ├── audio_wav.cpython-37.pyc
│ └── wav_audio.cpython-37.pyc
├── Chords
├── Docs
│ ├── CAI_Tkinter.pdf
│ ├── tkinter_nmt.pdf
│ └── wav_pointal.pdf
├── keyboard.py
├── main.py
├── observer.py
├── piano.py
├── __pycache__
│ ├── keyboard.cpython-37.pyc
│ ├── listes.cpython-37.pyc
│ ├── observer.cpython-37.pyc
│ ├── piano.cpython-37.pyc
│ ├── signal_visualizer.cpython-37.pyc
│ ├── wave_generator.cpython-37.pyc
│ └── wave_visualizer.cpython-37.pyc
├── Sounds
│ └── sound.wav
├── TODO.txt
├── Utils
│ ├── combo.py
│ ├── __init__.py
│ ├── listes.py
│ ├── menubar.py
│ ├── path_to_files.py
│ ├── __pycache__
│ │ ├── __init__.cpython-37.pyc
│ │ └── listes.cpython-37.pyc
│ └── wave_create.py
├── wave_generator.py
└── wave_visualizer.py
tar zcvf Nom_Prenom_Piano.tgz Nom_Prenom_Piano
Envoyer l'archive (Nom_Prenom_Piano.tgz) par mail (<EMAIL>) avec l'intitulé : "CAI : Labos Piano"
<file_sep>/Utils/menubar.py
# -*- coding: utf-8 -*-
import sys
print("Your platform is : " ,sys.platform)
major=sys.version_info.major
minor=sys.version_info.minor
print("Your python version is : ",major,minor)
if major==2 and minor==7 :
import Tkinter as tk
import tkFileDialog as filedialog
import tkMessageBox as messagebox
elif major==3 and minor==6 :
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
else :
print("with this version ... I guess it will work ! ")
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
class Menubar():
def __init__(self, parent):
self.menu = tk.Menu(parent)
self.fileMenu = tk.Menu(self.menu)
#self.fileMenu.add_command(label="Item")
self.fileMenu.add_command(label="Exit", command=self.exitProgram)
#fileMenu.add_command(label="Exit", command=self.create(self.master))
self.menu.add_cascade(label="File", menu=self.fileMenu)
self.helpMenu = tk.Menu(self.menu)
self.helpMenu.add_command(label="Creator", command=self.creator)
self.helpMenu.add_command(label="Thanks", command = self.thanks)
self.menu.add_cascade(label="Help", menu=self.helpMenu)
def exitProgram(self):
MsgBox = messagebox.askquestion ('Exit App','Really Quit?',icon = 'error')
if MsgBox == 'yes':
exit()
else:
messagebox.showinfo('Welcome Back','Welcome back to the App')
def creator(self):
messagebox.showinfo('Creator','<NAME>')
def thanks(self):
messagebox.showinfo(' Thanks','Thanks tkInter for your support')
if __name__ == "__main__" :
mw = tk.Tk()
mw.wm_title("Tkinter window")
"""
btn = tk.Button(mw, text="Créer une nouvelle fenêtre", command = self.create)
btn.pack(pady = 10) """
menubar = Menubar(mw)
mw.config(menu = menubar.menu)
mw.mainloop()<file_sep>/piano.py
# -*- coding: utf-8 -*-
# https://stackoverflow.com/questions/34522095/gui-button-hold-down-tkinter
import sys
print("Your platform is : " ,sys.platform)
major=sys.version_info.major
minor=sys.version_info.minor
print("Your python version is : ",major,minor)
if major==2 and minor==7 :
import Tkinter as tk
import tkFileDialog as filedialog
elif major==3 and minor==6 :
import tkinter as tk
from tkinter import filedialog
else :
print("with your python version : ",major,minor)
print("... I guess it will work !")
import tkinter as tk
from tkinter import filedialog
from math import pi,sin
import collections
import subprocess
from keyboard import *
from wave_generator import *
class Piano :
def __init__(self,parent,octaves) :
self.parent=parent
self.octaves=[]
self.notes = []
self.keyboards=[]
self.showNote=tk.BooleanVar()
self.showNote.set(True)
frame=tk.Frame(self.parent,bg="yellow")
for octave in range(octaves) :
self.create_octave(frame,octave+3)
frame.pack(fill="x")
self.show_label = tk.Checkbutton(parent, text='Show Note', var=self.showNote)
self.show_label.bind("<Button-1>", self.checkNote)
self.show_label.pack()
def create_octave(self,parent,degree=3) :
model=Octave(degree)
control=Keyboard(parent,model)
self.keyboards.append(control)
view=Screen(parent)
model.attach(view)
control.get_keyboard().grid(column=degree,row=0)
view.get_screen().grid(column=degree,row=1)
self.octaves.append(model)
def attach_graph(self, graph):
for octave in self.octaves:
octave.attach_graph(graph)
def attach_graphnote(self, graph):
for makeNote in self.notes:
makeNote.attach_graphnote(graph)
def checkNote(self,event):
if self.showNote.get():
for keyboard in self.keyboards:
for label in keyboard.label:
label.place_forget()
else :
print("test")
for keyboard in self.keyboards:
for label, place in zip(keyboard.label, keyboard.place_Label):
print(place)
label.place(x = place[0], y = place[1])
if __name__ == "__main__" :
mw = tk.Tk()
mw.geometry("360x300")
octaves=2
mw.title("La leçon de piano à " + str(octaves) + " octaves")
piano=Piano(mw,octaves)
mw.mainloop()
<file_sep>/wave_visualizer.py
# -*- coding: utf-8 -*-
# https://stackoverflow.com/questions/34522095/gui-button-hold-down-tkinter
import sys
print("Your platform is : " ,sys.platform)
major=sys.version_info.major
minor=sys.version_info.minor
print("Your python version is : ",major,minor)
if major==2 and minor==7 :
import Tkinter as tk
import tkFileDialog as filedialog
elif major==3 and minor==6 :
import tkinter as tk
from tkinter import filedialog
else :
print("with your python version : ",major,minor)
print("... I guess it will work !")
import tkinter as tk
from tkinter import filedialog
from math import pi,sin,cos
from observer import *
class Model(Subject) :
def __init__(self):
Subject.__init__(self)
self.a,self.f,self.p=1.0,[2.0],0.0
self.signal=[]
def vibration(self,t,impair=True):
a,freqs,p=self.a,self.f,self.p
somme=0
print(freqs)
for f in freqs:
print(f)
somme=somme + a*sin(2*pi*int(f)*t-p)
return somme
def generate_signal(self,period=2,samples=100.0):
del self.signal[0:]
echantillons=range(int(samples)+1)
Tech = period/samples
for t in echantillons :
self.signal.append([t*Tech,self.vibration(t*Tech)])
self.notify()
return self.signal
def set_magnitude(self,newa):
self.a=newa
def set_frequence(self,newb):
self.f = newb
print("setfrequence")
self.generate_signal()
def set_pulsation(self,newp):
self.p = newp
class View(Observer) :
def __init__(self,parent,bg="white", width=600,height=300):
self.canvas=tk.Canvas(parent,bg=bg,width=width,height=height)
self.a,self.f,self.p=10.0,2.0,0.0
self.width,self.height=width,height
self.units=1
self.canvas.bind("<Configure>",self.resize)
def update(self, model):
print("View : update()")
self.signal = model.signal
if self.signal :
self.canvas.delete("sound")
self.plot_signal(self.signal)
def plot_signal(self,signal,color="red"):
w,h=self.width,self.height
signal_id=None
if signal and len(signal) > 1:
print(self.units)
plot = [(x*w,h/2.0*(1-y*1.0/(self.units/2.0))) for (x, y) in signal]
signal_id=self.canvas.create_line(plot, fill=color, smooth=1, width=3,tags="sound")
return signal_id
def grid(self,steps=2):
self.units=steps
tile_x=self.width/steps
for t in range(1,steps+1):
x =t*tile_x
self.canvas.create_line(x,0,x,self.height,tags="grid")
self.canvas.create_line(x,self.height/2-10,x,self.height/2+10,width=3,tags="grid")
tile_y=self.height/steps
for t in range(1,steps+1):
y =t*tile_y
self.canvas.create_line(0,y,self.width,y,tags="grid")
self.canvas.create_line(self.width/2-10,y,self.width/2+10,y,width=3,tags="grid")
def resize(self,event):
if event:
self.width,self.height=event.width,event.height
self.canvas.delete("grid")
# self.canvas.delete("sound")
# self.plot_signal(self.signal)
self.grid(self.units)
def packing(self) :
self.canvas.pack(expand=1,fill="both",padx=6)
class Controller(object) :
def __init__(self, parent, model, view):
self.model, self.view = model, view
self.create_controls(parent)
def create_controls(self, parent):
self.frame=tk.LabelFrame(parent,text='Signal')
self.amp=tk.IntVar()
self.amp.set(1)
self.scaleA=tk.Scale(self.frame,variable=self.amp, label="Amplitude", orient="horizontal",length=250, from_=0,to=5,tickinterval=1)
self.scaleA.bind("<Button-1>",self.update_magnitude)
self.freq=tk.IntVar()
self.freq.set(10)
self.scaleB=tk.Scale(self.frame,variable=self.freq, label="Fréquence", orient="horizontal",length=250, from_=0,to=10,tickinterval=1)
self.scaleB.bind("<Button-1>",self.update_frequence)
self.puls=tk.IntVar()
self.puls.set(10)
self.scaleC=tk.Scale(self.frame,variable=self.puls, label="Fréquence", orient="horizontal",length=250, from_=-10,to=10,tickinterval=1)
self.scaleC.bind("<Button-1>",self.update_pulsation)
def update_magnitude(self,event):
self.model.set_magnitude(self.amp.get())
self.model.generate_signal()
def update_frequence(self,event):
self.model.set_frequence(self.freq.get())
self.model.generate_signal()
def update_pulsation(self,event):
self.model.set_pulsation(self.puls.get())
self.model.generate_signal()
def packing(self):
self.frame.pack()
self.scaleA.pack()
self.scaleB.pack()
self.scaleC.pack()
if __name__ == "__main__" :
mw = tk.Tk()
mw.geometry("360x300")
mw.title("Visualisation de signal sonore")
frame=tk.LabelFrame(mw, text="Signal Visualizer",borderwidth=5,width=400,height=300,bg="yellow")
# frame=tk.Frame(mw,borderwidth=5,width=360,height=300,bg="green")
frame.pack()
view=View(frame)
view.grid(4)
view.packing()
model = Model()
model.attach(view)
model.generate_signal()
ctrl=Controller(mw,model,view)
view.packing()
ctrl.packing()
mw.mainloop()
<file_sep>/main.py
# -*- coding: utf-8 -*-
import sys
print("Your platform is : " ,sys.platform)
major=sys.version_info.major
minor=sys.version_info.minor
print("Your python version is : ",major,minor)
if major==2 and minor==7 :
import Tkinter as tk
import tkFileDialog as filedialog
import tkMessageBox as messagebox
elif major==3 and minor==6 :
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
else :
print("with your python version : ",major,minor)
print("... I guess it will work !")
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
from math import pi,sin
import collections
import subprocess
from observer import *
from piano import *
from wave_visualizer import *
from wave_generator import *
from keyboard import *
from Utils.menubar import *
mw = tk.Tk()
mw.geometry("1600x700")
mw.title("Leçon de Piano")
label_hello=tk.Label(mw, text="Hello Mozart !",fg="blue")
#button_quit=tk.Button(mw, text="Goodbye Mozart", fg="red", command=mw.destroy)
label_hello.pack()
#button_quit.pack(side="bottom")
model = Model()
model.generate_signal()
viewFrame=tk.Frame(mw,borderwidth=5,width=360,height=300)
view=View(viewFrame)
view.grid(5)
view.packing()
view.update(model)
model.attach(view)
octaves=4
framePiano=tk.Frame(mw,borderwidth=5,width=360,height=300)
piano=Piano(framePiano,octaves)
piano.attach_graph(model)
framePiano.place(relx=0.35, rely=0.24, height=59, width=106)
framePiano.pack()
viewFrame.pack()
"""
menubar=Menubar(mw)
frameGen=tk.LabelFrame(mw, text="Generator ",borderwidth=5,width=400,height=300,bg="pink")
notes=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"]
selection= Selection(frameGen)
menu=ListMenu(frameGen,"notes",notes,selection)
menu.packing()
selection.packing()
"""
frameGen = tk.Frame(mw)
frameGen.pack(side="left", fill='y')
makenote = MakeNote(frameGen)
makenote.attach_graphnote(model)
makenote.packing()
menubar = Menubar(mw)
mw.config(menu = menubar.menu)
mw.mainloop()
<file_sep>/wave_generator.py
# -*- coding: utf-8 -*-
import sys
import subprocess
import os.path
import sqlite3
from audio_wav import *
print("Your platform is : " ,sys.platform)
major=sys.version_info.major
minor=sys.version_info.minor
print("Your python version is : ",major,minor)
if major==2 and minor==7 :
import Tkinter as tk
import tkFileDialog as filedialog
import tkMessageBox as messagebox
elif major==3 and minor==6 :
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
else :
print("with this version ... I guess it will work ! ")
import tkinter as tk
from tkinter import filedialog
from tkinter import messagebox
from Utils.listes import *
class Menubar(tk.Frame):
def __init__(self,parent=None):
tk.Frame.__init__(self, borderwidth=2)
if parent :
menu = tk.Menu(parent)
parent.config(menu=menu)
fileMenu = tk.Menu(menu)
fileMenu.add_command(label="Save",command=self.save)
menu.add_cascade(label="File", menu=fileMenu)
def save(self):
formats=[('Texte','*.py'),('Portable Network Graphics','*.png')]
filename=filedialog.asksaveasfilename(parent=self,filetypes=formats,title="Save...")
if len(filename) > 0:
print("Sauvegarde en cours dans %s" % filename)
class MakeNote():
def __init__(self, parent):
self.graph=None
frame1 = tk.Frame(parent)
frame1.grid(row = 0, column = 0)
frame2 = tk.Frame(parent)
frame2.grid(row = 0, column = 1)
frame3 = tk.Frame(parent)
frame3.grid(row = 0, column = 2)
self.selectionNote = Selection(frame2)
self.selectionAccord = Selection(frame3)
notes=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"]
self.menuNotes = ListMenu(frame1,"note",notes)
self.octaves=["2","3","4","5"]
self.menuOctaves = ListMenu(frame1,"octave",self.octaves)
self.createButtonNotes = tk.Button(frame1,text="Create note",fg="red")
self.createButtonNotes.bind("<Button-1>",lambda event : self.createNote(event, self.selectionNote))
self.createButtonAccord = tk.Button(frame1,text="Create accord",fg="red")
self.createButtonAccord.bind("<Button-1>",lambda event : self.createAccord(event, self.selectionNote, self.selectionAccord ))
self.createPlayNotes = tk.Button(frame2,text="PlayNote",fg="red")
self.createPlayNotes.bind("<Button-1>",lambda event : self.playNote(event, self.selectionNote))
self.createPlayAccord = tk.Button(frame3,text="PlayAccord",fg="red")
self.createPlayAccord.bind("<Button-1>",lambda event : self.playAccord(event, self.selectionAccord))
self.createButtonDeleteNote = tk.Button(frame2,text="deleteNote",fg="red")
self.createButtonDeleteNote.bind("<Button-1>",lambda event : self.removeNote(event, self.selectionNote))
self.createButtonDeleteAccord = tk.Button(frame3,text="deleteAccord",fg="red")
self.createButtonDeleteAccord.bind("<Button-1>",lambda event : self.removeAccord(event, self.selectionAccord))
"""
def callback(self, event):
mw.destroy()
"""
def createNote(self, event, selection):
data = []
note = str(self.menuNotes.get_note() + self.menuOctaves.get_note())
print(note)
selection.insert(note)
notes = selection.getData()
if not os.path.isfile("Sounds/"+ note +".wav"):
connect = sqlite3.connect("Audio/frequencies.db")
cursor = connect.cursor()
for note in notes :
key = note[:-1]
octave = note[-1:]
if '#' in key:
key_search = key[0] + "Sharp"
else:
key_search = key
result=cursor.execute("SELECT " + key_search + " FROM frequencies WHERE octave=" + str(octave) + ";")
freq=result.fetchone()[0]
self.graph.set_frequence(freq)
data = sinus_wav(filename='sinus.wav',f=freq,framerate=8000,duration=2)
save_wav("Sounds/"+note+".wav",data,8000)
def playNote(self, event, selectionNote):
notes = selectionNote.getData()
connect = sqlite3.connect("Audio/frequencies.db")
cursor = connect.cursor()
for note in notes:
key = note[:-1]
octave = note[-1:]
if '#' in key:
key_search = key[0] + "Sharp"
else:
key_search = key
result=cursor.execute("SELECT " + key_search + " FROM frequencies WHERE octave=" + str(octave) + ";")
freq=result.fetchone()[0]
if self.graph:
self.graph.set_frequence([freq])
subprocess.call(["aplay","Sounds/"+note+".wav"])
def playAccord(self, event, selection):
accords = selection.getData()
for accord in accords:
subprocess.call(["aplay","Sounds/"+accord+".wav"])
if self.graph:
freqs = []
notes = []
note=""
connect = sqlite3.connect("Audio/frequencies.db")
cursor = connect.cursor()
accord = accord[:-4]
while True:
print(accord)
note += accord[0]
if accord[0] in self.octaves:
notes.append(note)
note=""
if len(accord) <=1:
break
accord=accord[1:]
print(notes)
for note in notes:
key = note[:-1]
if "#" in key:
key = key[0]+"Sharp"
octave = note[-1:]
print(key, octave)
result=cursor.execute("SELECT "+key+" FROM frequencies WHERE octave="+note[-1:]+";")
freqs.append(result.fetchone()[0])
print(freqs)
self.graph.set_frequence(freqs)
connect.commit()
def createAccord(self, event, selection, selectionAccord):
if len(selection.getData()) >= 3 :
accord = ""
data = []
notes = selection.getData()
for note in notes:
accord+=note
selectionAccord.insert(accord)
if not os.path.isfile("Sounds/"+ accord +".wav"):
connect = sqlite3.connect("Audio/frequencies.db")
cursor = connect.cursor()
for note in notes :
key = note[:-1]
octave = note[-1:]
if '#' in key:
key_search = key[0] + "Sharp"
else:
key_search = key
result=cursor.execute("SELECT " + key_search + " FROM frequencies WHERE octave=" + str(octave) + ";")
print(result)
freq=result.fetchone()[0]
nextData = sinus_wav(filename='sinus.wav',f=freq,framerate=8000,duration=2)
if len(data)==0:
data = nextData
for i in range(0, len(nextData)):
data[i] += nextData[i]
save_wav("Sounds/"+accord+".wav",data,8000)
else:
messagebox.showinfo('Warning','Il faut minimum trois notes')
def removeNote(self, event, selection):
selection.deleteNote()
def removeAccord(self, event, selection):
selection.deleteAccord()
print(selection.getData())
def attach_graphnote(self, graph):
self.graph = graph
def packing(self):
self.selectionNote.packing()
self.selectionAccord.packing()
self.menuNotes.packing()
self.menuOctaves.packing()
self.createButtonNotes.pack()
self.createPlayNotes.pack()
self.createButtonAccord.pack()
self.createPlayAccord.pack()
self.createButtonDeleteNote.pack()
self.createButtonDeleteAccord.pack()
if __name__ == "__main__" :
mw=tk.Tk()
mw.geometry("360x300")
mw.title("Generateur de fichier au format WAV")
#menubar=Menubar(mw)
#frame=tk.LabelFrame(mw, text="Generator ",borderwidth=5,width=600,height=300,bg="pink")
#notes=["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"]
#selection= Selection(frame)
#menu=ListMenu(frame,"notes",notes,selection)
#menu.packing()
#selection.packing()
#frame.pack()
note = MakeNote(mw)
note.packing()
mw.mainloop()
"""
mw=tk.Tk()
#mw.option_readfile("hello.opt")
label_hello=tk.Label(mw,text="Hello World !")
label_bonjour=tk.Label(mw,name="labelBonjour")
button_quit=tk.Button(mw,text="Goodbye World !")
label_hello.pack()
label_bonjour.pack()
button_quit.pack()
mw.mainloop() """
|
c48873734e0a11bd346267ade33cf5710c7a774e
|
[
"Python",
"Text"
] | 6 |
Text
|
RemiChevrier/Piano
|
77cabbc9cd408774857429ce7684e186982507b8
|
d9e30bf77fe48ba3b6b6b9a7c6a196072e806aea
|
refs/heads/master
|
<file_sep>import React, { Component } from 'react'
export default class GameStatus extends Component {
render() {
return (
<div className="grid-col mt-10px">
{
(this.props.gameStatus==='active')
? <h2 className="trailes">Tries Left: {this.props.counter}</h2>
: (this.props.gameStatus == "win")
? <h1 className="win">You Won the Game with {11 - this.props.counter} try(s)!</h1>
:<h1 className="lose" {...this.props.onClick()}> RIP!<br></br> Better Luck in the next life. </h1>
}
</div>
)
}
}
<file_sep>import React, { Component } from 'react'
export default class SecretWord extends Component {
constructor(props){
super(props)
}
render() {
return (
<div className="letters">
{
this.props.word.split("").map((letter, index) =>
this.props.correctLetters.includes(letter)
? <span key={index} className="lettersKnwn "> {letter} </span>
: <span key={index} className="lettersNotKnw " > ? </span>
)
}
</div>
)
}
}
<file_sep>import React, { Component } from 'react'
import ImagesCount from "./ImagesCount"
import Buttons from "./Buttons";
import PlayAgain from "./PlayAgainn"
import SecretWord from "./SecretWord";
import GameStatus from "./GameStatus";
import Hint from "./Hint";
import Header from "./Header";
import Win from "./win.mp3";
import Lost from "./lost.mp3";
import Wrong from "./WrongBtn.mp3";
import Right from "./rightBtn.mp3";
//I need to do the game status
export default class Hangman extends Component {
constructor(props) {
super(props);
this.state = {
counter:10,
word:"",
UsedLetters:[],
correctLetters:[],
isLoaded:false,
hint: [],
error:""
};
}
componentDidMount() {
fetch("https://random-word-api.herokuapp.com/word?number=1")
.then((res) => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
word: result.toString()
});
},
(error) => {
this.setState({
isLoaded: true,
error: error
});
}
);
}
render() {
const start = (sound) => {
let audio = new Audio(sound)
audio.pause();
audio.play()
audio.volume = 0.5;
}
const giveHint = (hintBtnClicked) => {
if(this.state.hint.length>1 && hintBtnClicked==true){
alert("You only have two hints");
return
}
for (let index = 0; index < this.state.word.length; index++) {
let letter = this.state.word[index];
if(!this.state.correctLetters.includes(letter) && !this.state.hint.includes(letter)){
this.setState(state => {
const hint = [...state.hint, letter];
return { hint,};
});
this.setState(state => {
const UsedLetters = [...state.UsedLetters, letter];
return { UsedLetters,};
});
this.setState(state => {
const correctLetters = [...state.correctLetters, letter];
return {correctLetters,};
});
return
}
}
}
const checkWin =()=>{
let status="win";
this.state.word.split("").forEach(letter =>{
if(!this.state.correctLetters.includes(letter)){
status="active"
}
})
return status;
}
let gameStatus = this.state.counter === 0 ? 'Lost' : checkWin();
//when the letter is wrong the counter increases
const counterIncrease = () => {
const newCounter=this.state.counter -1
this.setState({counter:newCounter})
}
//checking the letter if it is correct or worng / adding it to the used array
const CheckLetter = (letter)=>{
if (gameStatus !== 'active' || this.state.counter === 0)
return;
//it addes the letter to the USEDLETTERS array in the state
this.setState(state => {
const UsedLetters = [...state.UsedLetters, letter];
return { UsedLetters,};
});
//if the word includes the letter we add the letter to our correct letters list
if(this.state.word.includes(letter)){
this.setState(state => {
const correctLetters = [...state.correctLetters, letter];
return {correctLetters,};
});
start(Right)
}else{
start(Wrong)
counterIncrease();
}
}
//checking and returning btn status
const btnStatus=(btnLetter)=>{
return (this.state.UsedLetters.includes(btnLetter)); ;
}
return (
<div className="grid-1">
<Header />
<div className="buttons">
{utilities.generateLetters(97,122).map(letter =>
<Buttons
key={letter}
letter={letter}
onClick={CheckLetter}
status={btnStatus(letter)}
/>
)}
</div>
<div className="grid-2" >
<div className="grid-col mt-1">
{
(!this.state.isLoaded)
? <div>Looking for a Word...</div>
: <React.Fragment>
<SecretWord word={this.state.word} correctLetters={this.state.correctLetters}/>
<GameStatus gameStatus={gameStatus} counter={this.state.counter} onClick={giveHint}/>
{
(gameStatus==="win")? start(Win): (gameStatus==="Lost")? start(Lost): console.log("keep going")
}
</React.Fragment>
}
<div className="d-inline mt-2">
<PlayAgain onClick={this.props.startNewGame} />
<Hint onClick={giveHint} hint={this.state.hint} />
</div>
</div>
<div className="right" style={{textAlign:"right"}}>
<ImagesCount counter={this.state.counter}/>
</div>
</div>
</div>
)//END OF RETURN
}//END OF RENDER
}//END OF CLASS
const utilities={
generateLetters: (min, max) => Array.from({ length: max - min + 1 }, (_, i) => String.fromCharCode(min + i)),
}<file_sep>import React, { Component } from 'react'
import img1 from "./images/1.png"
import img2 from "./images/2.png"
import img3 from "./images/3.png"
import img4 from "./images/4.png"
import img5 from "./images/5.png"
import img6 from "./images/6.png"
import img7 from "./images/7.png"
import img8 from "./images/8.png"
import img9 from "./images/9.png"
import img10 from "./images/10.png"
import img11 from "./images/11.png"
export default class ImagesCount extends Component {
constructor(props){
super(props)
}
render() {
const imgs= [img1,img2,img3,img4,img5,img6,img7,img8,img9,img10,img11]
return (
<img className="center-images" src={imgs[this.props.counter]} alt="img1" width="200"/>
)
}
}
<file_sep>import React, { Component } from 'react'
export default class Header extends Component {
render() {
return (
<div className="header">
<h1> The Hangman Game !</h1>
<p> Find the letters in the <b className="trailes">Secret</b> word or the human is going to be <b className="lose">Hanged.</b> </p>
</div>
)
}
}
<file_sep>import React, { Component } from "react";
export default class Button extends Component {
constructor(props) {
super(props);
}
render() {
return (
<button
disabled={ this.props.status}
className={"buttonStyle "+ this.props.status}
onClick={() => this.props.onClick(this.props.letter)}
>
{this.props.letter}
</button>
);
}
}
<file_sep>import React, { Component } from 'react'
export default class Hint extends Component {
constructor(props){
super(props)
}
render() {
return (
<button className="btn"
onClick={() => this.props.onClick(true)}
> Hint
</button>
)
}
}
<file_sep># MAKE SURE YOU HAVE NPM AND NODE INSTALLED
# CLONE the propject and then run (npm install )
# RUN (npm start) COMMAND <file_sep>
import './App.css';
import React, { useState } from 'react';
import Hangman from "./component/Hangman";
import newGame from "./newGame.mp3";
function App() {
const [gameId, setGameId]= useState(1)
const newGmae=() => {
setGameId(gameId +1)
let audio = new Audio(newGame)
audio.play()
}
return (
<div className="App">
<Hangman key={gameId} startNewGame={newGmae} />
</div>
);
}
export default App;
<file_sep># Hangman Game
The most Dangerous game you will ever play! if you don't win a person will be hanged 👨🦱🔪 !! <br>
Visit <a href="https://nifty-booth-cc2308.netlify.app/">Hangman netlify</a> or <a href="https://areeg94fahad.github.io/hangman/">Hangman github</a> to play .
## Game OverView
The purpose of the game is to guess the word to save the person from being hanged <br><br>
<br><br>
if you guessed the words right the person will survive <br><br>
<br><br>
if you guessed the words wrong the person will die <br><br>
<br><br>
### How to play
1. press the letter that you think is the correct one and if it is, it will show.
2. if you guessed the word wrong the counter will decrease and the person will be a closer to be hanged.
3. you have 2 hints in which each one of them will show a letter for you.
4. you can restart the game by pressing play again and another word will show.
#### Technology
this game is bulit using React JS
#### Contributors
this game is developed by Lava Team <br><br>
<br>
|
1c186c218a1d70ec580d426fff6a16d28cd26088
|
[
"JavaScript",
"Markdown"
] | 10 |
JavaScript
|
AREEG94FAHAD/hangman_react_js
|
a4c594cde034b76dd45cf312de14c3502771da71
|
8b74f35db269c491d947f6820ae2ba4f02a38885
|
refs/heads/master
|
<repo_name>Hafeezistic/small-projects<file_sep>/README.md
## small-projects
> collection of my small projects during my #100DaysOfCode journey
<file_sep>/image-ambilight-effect/index.js
// cosha library
cosha({
className: 'colorful-shadow',
blur: '10px',
brightness: '125%',
saturation: '110%',
x: '4px',
y: '8px'
});
|
114a4862caf4a8017a8e7f140f52da267b7e1ceb
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
Hafeezistic/small-projects
|
43eb8cba18f95c6eb35df54c8fb209a9c362cf0c
|
d7e4a7182d468f24a5def3fd1ebd94c40bf60850
|
refs/heads/master
|
<file_sep>var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
setTimeout(function() {
navigator.splashscreen.hide();
}, 3000);
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
}
};
$(document).ready(function () {
$(".simulateur").bind("tap", function () {
switch ($(this).data("simu"))
{
case 'taux_dalcoolemie' :
$("#titre_avert").text('Taux d\'alcoolémie');
$("#msg_avert").text('Attention, les résultats des simulateurs sont donnés à titre indicatif.');
$("#continue_avert").attr('href','#page_taux_dalcoolemie');
break;
case 'distance_de_freinage' :
$("#titre_avert").text('Distance de freinage');
$("#msg_avert").text('Attention, les résultats des simulateurs sont donnés à titre indicatif.');
$("#continue_avert").attr('href','#page_distance_de_freinage');
break;
case 'comparateur_vitesse' :
$("#titre_avert").text('Comparateur de vitesse');
$("#msg_avert").text('Attention, les résultats des simulateurs sont donnés à titre indicatif.');
$("#continue_avert").attr('href','#page_comparateur_vitesse');
break;
}
$('#popupMsgAvert').popup('open');
});
$("#continue_avert").tap(function () {
$(this).css({'background-color': '#ffd700', 'color' : 'black'});
setTimeout(function () {$("#continue_avert").css('background-color', 'white');}, 300);
});
//Gestion de la fermeture de popup
$(".closepopup").tap(function () {
var objid = $(this).parents('[data-role=popup]').attr('id');
setTimeout(function () {
$("#"+objid).popup('close')
}, 300);
if(objid == "popupDialogErreurAjtAlcool")
{
setTimeout(function(){
$("#popUpNewBoisson").popup('open');
},410);
}
});
$("#liencarteid").tap(function ()
{
var em=document.getElementById("carte_de_localisation");
em.innerHTML='<iframe width="100%" height="93%" id="iframecarte" src="http://le-denmat.com/wp-content/plugins/leaflet-maps-marker/leaflet-fullscreen.php?layer=5" frameborder="0"></iframe>';
});
/*
function affiche_carte()
{
var em=document.getElementById("carte_de_localisation");
em.innerHTML='<iframe width="100%" height="93%" id="iframecarte" src="http://le-denmat.com/wp-content/plugins/leaflet-maps-marker/leaflet-fullscreen.php?layer=5" frameborder="0"></iframe>';
}
*/
//UTILISER PLUGIN CORDOVA !
/*
$(".checkCo").tap(function ()
{
var page_demande = $(this);
$.getScript("http://jacxl.free.fr/cours_xl/inetok.js", function () {
//alert('inet');
//alert(inet);
if(typeof(inet) == 'undefined')
{
document.location.href = './index.html';
$('#titre_avert').text('Erreur');
$('#msg_avert').text('La page demandée requiert une connection internet.');
$('#continue_avert').text('Ok');
$("#continue_avert").attr('href','#');
$('#continue_avert').tap(function () {
$('#popupMsgAvert').popup('close');
});
$('#popupMsgAvert').popup('open');
return;
}
switch (page_demande.data("lien"))
{
case 'carte' :
$.mobile.changePage('#carte');
$('#carte_de_localisation').html('').append('<iframe width="100%" height="93%" id="iframecarte" src="http://le-denmat.com/wp-content/plugins/leaflet-maps-marker/leaflet-fullscreen.php?layer=5" frameborder="0"></iframe>');
break;
}
})
});
*/
});
<file_sep>//Premiers secours
var cas_accident=1;
var jamais_faire=1;
var agents_service=1;
function btn_retour(){
var nb_page = history.length-1;
nb_page = -nb_page;
history.go(nb_page);
}
function affiche_reponse_securite_routiere(id_reponse){
var count;
var elements=document.getElementById(id_reponse);
switch (id_reponse)
{
case 'reponse_cas_accident' :
var btn_libelle=document.getElementById('btn_cas_accident');
if(cas_accident == 3)
{
cas_accident = 1;
}
count = cas_accident;
cas_accident++;
if(count==1)
{
elements.className="visible";
//Fermeture des autres affichages
document.getElementById('reponse_jamais_faire').className="invisible";
jamais_faire=1;
document.getElementById('btn_jamais_faire').style.backgroundColor="#CDCDCD";
document.getElementById('reponse_agent_intervention').className="invisible";
agents_service=1;
document.getElementById('agent_intervention').style.backgroundColor="#CDCDCD";
btn_libelle.style.backgroundColor="#FFD700";
}
if(count==2)
{
elements.className="invisible";
btn_libelle.style.backgroundColor="#CDCDCD";
}
break;
case 'reponse_jamais_faire' :
var btn_libelle=document.getElementById('btn_jamais_faire');
if(jamais_faire == 3)
{
jamais_faire = 1;
}
count = jamais_faire;
jamais_faire++;
if(count==1)
{
elements.className="visible";
//Fermeture des autres affichages
document.getElementById('reponse_cas_accident').className="invisible";
cas_accident=1;
document.getElementById('btn_cas_accident').style.backgroundColor="#CDCDCD";
document.getElementById('reponse_agent_intervention').className="invisible";
agents_service=1;
document.getElementById('agent_intervention').style.backgroundColor="#CDCDCD";
btn_libelle.style.backgroundColor="#FFD700";
//document.location.href="#btn_cas_accident";
}
if(count==2)
{
elements.className="invisible";
btn_libelle.style.backgroundColor="#CDCDCD";
}
break;
case 'reponse_agent_intervention' :
var btn_libelle=document.getElementById('agent_intervention');
if(agents_service == 3)
{
agents_service = 1;
}
count = agents_service;
agents_service++;
if(count==1)
{
elements.className="visible";
//Fermeture des autres affichages
document.getElementById('reponse_cas_accident').className="invisible";
cas_accident=1;
document.getElementById('btn_cas_accident').style.backgroundColor="#CDCDCD";
document.getElementById('reponse_jamais_faire').className="invisible";
jamais_faire=1;
document.getElementById('btn_jamais_faire').style.backgroundColor="#CDCDCD";
btn_libelle.style.backgroundColor="#FFD700";
//document.location.href="#btn_jamais_faire";
}
if(count==2)
{
elements.className="invisible";
btn_libelle.style.backgroundColor="#CDCDCD";
}
break;
}
}<file_sep>
/*
______ ______ .___ ___. .______ ___ .______ ___ .___________. _______ __ __ .______
/ | / __ \ | \/ | | _ \ / \ | _ \ / \ | || ____|| | | | | _ \
| ,----'| | | | | \ / | | |_) | / ^ \ | |_) | / ^ \ `---| |----`| |__ | | | | | |_) |
| | | | | | | |\/| | | ___/ / /_\ \ | / / /_\ \ | | | __| | | | | | /
| `----.| `--' | | | | | | | / _____ \ | |\ \----./ _____ \ | | | |____ | `--' | | |\ \----.
\______| \______/ |__| |__| | _| /__/ \__\ | _| `._____/__/ \__\ |__| |_______| \______/ | _| `._____|
*/
function simuDistanceGtps()
{
var distance;
var vitesseActuelle, vitesseAutorisee, differenceVitesse;
/*Récupération des données utilisateur*/
distance = document.getElementById('distanceSimuGtps').value;
vitesseActuelle = document.getElementById('vitesseActuelleSimuGtps').value;
vitesseAutorisee = document.getElementById('vitesseAutoriseeSimuGtps').value;
differenceVitesse = vitesseActuelle - vitesseAutorisee;
//Si l'utilisateur entre d'autres caractères que des chiffres
if(isNaN(distance) == true || isNaN(vitesseActuelle) == true || isNaN(vitesseAutorisee) == true)
{
//Change le message de la popup d'erreur
document.getElementById('erreurPopUpComp').innerHTML= "Utilisez seulement les chiffres digitaux pour remplir les champs demandés";
//Affiche la pop up
$('#popupDialogErreurComp').popup('open');
document.getElementById('gainTps').innerHTML="";
return;
}
//S'il entre une distance trop grande
if(distance>2000)
{
//Change le message de la popup d'erreur
document.getElementById('erreurPopUpComp').innerHTML= "Veuillez entrer une distance inférieure";
//Affiche la pop up
$('#popupDialogErreurComp').popup('open');
document.getElementById('gainTps').innerHTML="";
return;
}
//S'il n'entre pas de distance
if(distance=='' || vitesseActuelle=='' || vitesseAutorisee=='')
{
//Change le message de la popup d'erreur
document.getElementById('erreurPopUpComp').innerHTML= "Veuillez n'indiquer que des nombres";
//Affiche la pop up
$('#popupDialogErreurComp').popup('open');
document.getElementById('gainTps').innerHTML="";
return;
}
$("#consommation_p").hide();
gain_Tps(distance, vitesseActuelle, vitesseAutorisee);
contravention(differenceVitesse);
/*******************************A tester au chargement de la page !!********************/
vehicules_local();
//Calcul de la consommation
var conso = consommationCarburant(vitesseActuelle);
document.getElementById('consoCarburant').innerHTML = " " + conso + "L / 100km";
$("#consommation_p").show();
//Calcul de la consommation à la vitesse autorisée
var consoVitAutorisee = consommationCarburant(vitesseAutorisee);
//Affichage de la différence entre le cout du trajet réel, et le cout à vitesse autorisé
var prix = cout_trajet(conso, consoVitAutorisee, distance);
//Si le cout reel est inférieur au cout à vitesse autorisé
if(prix < 0){
var prix1 = - prix;
document.getElementById('gain_perte_cout_trajet').innerHTML = "<b>Économies : </b>" + prix1 + "€";
}
//Si le cout reel est supérieur au cout à vitesse autorisé
if(prix > 0){
document.getElementById('gain_perte_cout_trajet').innerHTML = "<b>Surcoût : </b>" + prix + "€";
}
//Si le cout réel est supérieur au cout à vitesse autorisée, on ne fait rien
if(prix == 0){
document.getElementById('gain_perte_cout_trajet').innerHTML = "";
}
/*Affiche les résultats*/
$("#GainTpsPopUp").popup('open');
}
function gain_Tps(distance, vitesseActuelle, vitesseAutorisee)
{
var gainTps, gainTpsH, gainTpsMin;
document.getElementById('gainTps').innerHTML="<b>Perte de temps : </b> 0 Min";
/*Calcul du gain de temps*/
gainTps = distance*(parseFloat(vitesseActuelle)-parseFloat(vitesseAutorisee))/(parseFloat(vitesseActuelle)*parseFloat(vitesseAutorisee));//parseFloat-> string to float
/*Convertion heure décimale/heure format H min*/
gainTps=gainTps+"";//converti la durée en chaine de caractère
//Heure
var i=0;//compteur
for(i=0;(gainTpsH!='.')&&(i<10);i++){//tant qu'on a pas trouve la virgule
gainTpsH=gainTps.substring(i,(i+1));//l'heure correspond a l'ensemble des chiffres placés jusqu'à la virgule
}
gainTpsH=gainTps.substring(0, i-1);//on recupere l'ensemble des chiffres places AVANT la virgule
//Minute
gainTpsMin=(gainTps-gainTpsH).toFixed(2);//recupere les minutes en decimal et arrondi à la minute
gainTpsMin=Math.round(gainTpsMin*60);//converti les minutes decimales en minutes sous format Heure/min + arrondi à la minute
/*Gestion de l'affichage*/
//Affiche du temps perdu/gagné
console.log('h'+gainTpsH+'min'+gainTpsMin);
if(gainTpsH==0 && gainTpsMin>0){
document.getElementById('gainTps').innerHTML="<b>Gain de temps : </b>"+gainTpsMin+" Min";
return;
}
if((gainTpsH==0)&&(gainTpsMin<0)){
document.getElementById('gainTps').innerHTML="<b>Perte de temps : </b>"+gainTpsMin*(-1)+" Min";//ne pas afficher d'heure negative
return;
}
if((gainTpsMin<=0)&&(gainTpsH<0)){
document.getElementById('gainTps').innerHTML="<b>Perte de temps : </b>"+gainTpsH*(-1)+" H "+gainTpsMin*(-1)+" Min";//ne pas afficher d'heure negative
return;
}
if((gainTpsMin>=0)&&(gainTpsH>0)){
document.getElementById('gainTps').innerHTML="<b>Gain de temps : </b>"+gainTpsH+" H "+gainTpsMin+" Min";
return;
}
}
function contravention(differenceVitesse)
{
if(differenceVitesse<=0){//si l'excès de vitesse est inférieur ou égal à 0
document.getElementById('amendeEuros').innerHTML="0";
document.getElementById('amendePoints').innerHTML="0 point";
return;
}
if(differenceVitesse>0 && differenceVitesse<20){//si l'excès de vitesse est inférieur à 20 km/h
document.getElementById('amendeEuros').innerHTML="45";
document.getElementById('amendePoints').innerHTML="-1 point";
return;
}
if(differenceVitesse>=20 && differenceVitesse<30){//si l'excès de vitesse est compris entre 20 et 30 km/h
document.getElementById('amendeEuros').innerHTML="90";
document.getElementById('amendePoints').innerHTML="-2 points";
return;
}
if(differenceVitesse>=30 && differenceVitesse<40){//si l'excès de vitesse est compris entre 30 et 40 km/h
document.getElementById('amendeEuros').innerHTML="90";
document.getElementById('amendePoints').innerHTML="-3 points";
return;
}
if(differenceVitesse>=40 && differenceVitesse<50){//si l'excès de vitesse est compris entre 40 et 50 km/h
document.getElementById('amendeEuros').innerHTML="90";
document.getElementById('amendePoints').innerHTML="-4 points";
return;
}
if(differenceVitesse>=50){//si l'excès de vitesse est supérieur à 50 km/h
document.getElementById('amendeEuros').innerHTML="<1500";
document.getElementById('amendePoints').innerHTML="-6 points";
return;
}
}
function consommationCarburant(vitesseActuelle)
{
var voiture, conso, conso_fixe;
var vitesse_fixe = "110";
var liste_voiture = JSON.parse(window.localStorage.getItem('Voiture'));
for(i=0; i<3; i++)
{
if(formConso.btnRadio[i].checked)
{
voiture = formConso.btnRadio[i].value;
}
}
$.each(liste_voiture, function(key, value){
if(liste_voiture[key]["voiture"] == voiture)
{
conso_fixe = liste_voiture[key][vitesse_fixe];
conso = vitesseActuelle*conso_fixe/vitesse_fixe;
conso = conso.toFixed(2);
return false; //Sort du each
}
});
return conso;
}
function cout_trajet(conso, consoVitAutorisee, distance){
var prix_carburant = 1.40; //€ par litre
var reel = (((conso/100)*distance)*prix_carburant).toFixed(2);
var autorise = (((consoVitAutorisee/100)*distance)*prix_carburant).toFixed(2);
return (reel - autorise).toFixed(2);
}
function vehicules_local()
{
liste_voiture = [];
var v1 =
{
"voiture" : "citadine",
"90" : 5.4,
"110": 6.6,
"130": 7.8
};
var v2 =
{
"voiture" : "monospace",
"90" : 6.5,
"110": 8.0,
"130": 9.4
};
var v3 =
{
"voiture" : "berline",
"90" : 5.6,
"110": 6.8,
"130": 8.1
};
//Ajout de l'ensemble des véhicules dans la liste
for(i=1; i<=3; i++)
{
var voiture = "v"+i;
liste_voiture.push(eval(voiture));
}
liste_voiture = JSON.stringify(liste_voiture);
//Stockage en local de la lsite
window.localStorage.setItem('Voiture', liste_voiture);
}<file_sep>/*
___ __ ______ ______ ______ __
/ \ | | / | / __ \ / __ \ | |
/ ^ \ | | | ,----'| | | | | | | | | |
/ /_\ \ | | | | | | | | | | | | | |
/ _____ \ | `----.| `----.| `--' | | `--' | | `----.
/__/ \__\ |_______| \______| \______/ \______/ |_______|
*/
$(document).ready(function (){
testInitialisation();
$("#choisir_verres").tap(function () {
var poids = document.getElementById('poids').value;//récupère le poids choisi par l'utilisateur
if(isNaN(poids) == true || poids == '')
{
$("#erreurPopUpAlcool").text('Veuillez indiquer votre poids');
$("#popupDialogErreurAlcool").popup('open');
return;
}
window.localStorage.setItem('Poids', poids);//stockage du genre en local pour récupérer la variable après le changement de page
/*
$(".contenuAlcool").hide({"slide": {direction:'left'}, "duration":600});
$("#choix_alcool").show({"slide": {direction:'left'},"duration":600});
*/
});
$(".genre").bind("tap click", function () {
//Initialisation d'une chaine vide pr recupérer le sexe de la personne
var coeffDiffusion;
//Homme ou Femme bouton radio
if(formHF.btnRadio[1].checked)
{
coeffDiffusion=formHF.btnRadio[1].value;
window.localStorage.setItem('Genre', coeffDiffusion);//stockage du genre en local pour récupérer la variable après le changement de page
return;
}
if(formHF.btnRadio[0].checked)
{
coeffDiffusion = formHF.btnRadio[0].value;
window.localStorage.setItem('Genre', coeffDiffusion);
}
});
/*
$("#settings").bind("tap", function () {
$.mobile.changePage("#page_config");
});
$("#resetAlcool").bind("tap", function (){
initBoissons();
});
*/
/*Ajout/suppression des verres en fonction de la fleche appuyée*/
$("#ajoutVerres").tap(function (){
var nombre = $('#nombreVerres').html();//récupère le nombre de verre dans la pop up popupNbVerres
nombre = parseInt(nombre);//tranforme en numérique
if(nombre>=0 && nombre<10){//bridage du nombre de verres à 10
nombre++;//augmente la valeur du nombre de verres dans la pop up
}
document.getElementById('nombreVerres').innerHTML=nombre;//affiche la version actuelle du nombre de verres
});
$("#enleverVerres").tap(function (){
var nombre = $('#nombreVerres').html();//récupère le nombre de verre dans la pop up popupNbVerres
nombre = parseInt(nombre);//tranforme en numérique
if(nombre>0 && nombre<=10){//le nombre ne peut pas etre négatif
nombre--;
}
document.getElementById('nombreVerres').innerHTML=nombre;//affiche la version actuelle du nombre de verres
});
$("#ajoutVerresBus").tap(function (){
var nbVerres, tabVerresBus, boisson;
var testBase = window.localStorage.getItem('NombreVerres');//variable pour l'envoie à la fonction simuAlcool
var verre= window.localStorage.getItem('verre');
verre=JSON.parse(verre);
var verreBoisson= verre.nomV;
var verreDegre = verre.degreV;
var verreContenance = verre.volV;
var existe=0;
var cle=0;
var vide = "";
window.localStorage.setItem('verre', vide);//Réinitialise le stockage des caracteristiques de la boisson à vide
nbVerres=$('#nombreVerres').html();//récupère le nombre de verres entré par l'utilisateur
/*Modifie la valeur du nombre de verres dans la liste*/
document.getElementById(verreBoisson).innerHTML=nbVerres;
if((testBase==null)||(testBase=="")){//si l'utilisateur n'a pas encore ajouté de verres
tabVerresBus=[];//initialisation d'un tableau
}
else{//si l'utilisateur a déjà entré des verres
tabVerresBus=window.localStorage.getItem('NombreVerres');//récupère le nbr de verres de chaque boisson
tabVerresBus=JSON.parse(tabVerresBus);//convertion au format JavaScript
}
boisson = {
"boisson":verreBoisson,
"degre":verreDegre,
"contenance":verreContenance,
"nbVerres": nbVerres,
};
/*Vérifie si l'utilisateur n'avait déjà pas mis un nombre de verre pour CETTE boisson*/
$.each(tabVerresBus, function(key, value){//parcourt l'ensemble des boissons déjç choisies
if((tabVerresBus[key]["boisson"])==(verreBoisson)){
existe=1;
cle=key;
}
});
if(existe==1){//si l'utilisateur avait deja choisi cette boisson et qu'il veut modifier le nbr de verres
tabVerresBus.splice(cle, 1);//on supprime la boisson dans la base temp
}
tabVerresBus.push(boisson);//on rajoute les caractéristique du verre dans le tableau
tabVerresBus=JSON.stringify(tabVerresBus);//conversion format JSON
//On stocke l'ensemble des boissons sélectionnées apr l'utilisateur
window.localStorage.setItem('NombreVerres', tabVerresBus);
//On ferme la pop up qui indique le nombre de verres
setTimeout(function(){$("#popupNbVerres").popup("close")},290);
});
function afficheRes(tauxAlcool, dureeEliminationHeure, dureeEliminationMin)
{
if(dureeEliminationHeure==0)
{//si le temps d'élimination est inférieur a une heure
document.getElementById('reponse').innerHTML="<b>Taux d'alcoolémie : </b>"+tauxAlcool.toFixed(2)+" g/l.<br> <b>Temps d'élimination : </b>"+dureeEliminationMin+" min";
}
if(dureeEliminationHeure!=0)
{
document.getElementById('reponse').innerHTML="<b>Taux d'alcoolémie : </b>"+tauxAlcool.toFixed(2)+" g/l. <br> <b>Temps d'élimination : </b>"+dureeEliminationHeure+"h"+dureeEliminationMin+"min";
}
$("#popupgraphe").popup('open');
}
//simuTauxAlcool
$("#calculerAlcool").tap(function (){
//var genre=window.localStorage.getItem('Genre');//récupère la variable stockée en local
var poids=window.localStorage.getItem('Poids');
var verresBus=JSON.parse(window.localStorage.getItem('NombreVerres'));//recupère l'ensemble des verres bus et leurs caractéristiques
var coeffDiffusion = window.localStorage.getItem('Genre');//récupère la variable stockée en local
var tauxAlcool=0;
var dureeEliminationD;//decimal
var dureeEliminationH;//sous le format heure decimale
var dureeEliminationHeure;//format heure H
var erreur=0;//variable verifie si erreur lors de la saisie
if(verresBus == null)
{
dureeEliminationHeure = 0;
dureeEliminationMin = 0;
afficheRes(tauxAlcool, dureeEliminationHeure, dureeEliminationMin);
return false;
}
$.each(verresBus, function(key, value){//parcourt l'ensemble des verres bus
//Récupère les caractéristiques
var degreBoisson = verresBus[key]["degre"];
var contenanceBoisson = verresBus[key]["contenance"];
var nbVerres = verresBus[key]["nbVerres"];
//Calcul du taux d'alcool
tauxAlcool=tauxAlcool+(contenanceBoisson*(degreBoisson)*0.8*nbVerres)/(coeffDiffusion*poids);
});
if(tauxAlcool>=1.5)
{
//Change le message de la popup d'erreur
document.getElementById('erreurPopUpAlcool').innerHTML="Vous avez dépassé les limites acceptables pour votre santé";
//Ouvre la pop up
$("#popupDialogErreurAlcool").popup('open');
return;
}
//Si le taux est correct
/*Definition du temps d'élémination du taux d'alcool dans le sang*/
dureeEliminationD=tauxAlcool/0.15;
dureeEliminationH=dureeEliminationD+"";//converti la durée en chaine de caractère
//Heure
var i=0;//compteur
for(i=0;(dureeEliminationHeure!='.')&&(i<10);i++)
{//tant qu'on a pas trouve la virgule
dureeEliminationHeure=dureeEliminationH.substring(i,(i+1));//l'heure correspond a l'ensemble des chiffres placés jusqu'à la virgule
}
dureeEliminationHeure=dureeEliminationH.substring(0, i-1);//on recupere l'ensemble des chiffres places AVANT la virgule
//Minute
dureeEliminationMinD=(dureeEliminationH-dureeEliminationHeure).toFixed(2);//recupere les minutes en decimal et arrondi à la minute
dureeEliminationMin=Math.round(dureeEliminationMinD*60);//converti les minutes decimales en minutes sous format Heure/min + arrondi à la minute
afficheRes(tauxAlcool, dureeEliminationHeure, dureeEliminationMin);
/*Représentation graphique du temps d'élimination*/
/*
function calculGraph(){
var datatps=tauxAlcool.toFixed(2)+",";
var taux=tauxAlcool.toFixed(2);
while(taux>=0.15){
taux=taux-0.15;
taux=taux.toFixed(2)
datatps=datatps+taux+",";
}
datatps=datatps+0.01;
return datatps;
}
var calcultaux=calculGraph();
alert(calcultaux);
$('#graphAlcool').highcharts({
title: {
text: 'Taux d\'alcoolémie en fonction du temps',
x: -20 //center
},
xAxis: {
categories: ['1', '2', '3', '4', '5', '6',
'7', '8', '9', '10', '11', '12']
},
yAxis: {
title: {
text: 'Taux d\'alcool en g/L'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
xAxis: {
title: {
text: 'Temps en heure'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'middle',
borderWidth: 0
},
series: [{
name: '<NAME>',
showInLegend: false,
data: [tauxAlcool.toFixed(2)-0.0, tauxAlcool.toFixed(2)-0.15, tauxAlcool.toFixed(2)-0.3]//, tauxAlcool.toFixed(2)-0.45, tauxAlcool.toFixed(2)-0.6, tauxAlcool.toFixed(2)-0.75, tauxAlcool.toFixed(2)-0.9]
//data: [+calcultaux]
}],
credits: {
enabled: false //desactive la pub de HighChart.com
},
exporting: {
enabled: false //desactive le bouton de sauvegarde de graph
},
});
*/
});//fin function simuTauxAlcool
/*Ajouter une boisson dans la base*/
$("#ajouterBoisson").tap(function (){
/*Récupération des caractéristiques de la nouvelle boisson*/
var newBoisson = document.getElementById('nvxBoisson').value;
var newDegre = document.getElementById('nvxDegre').value;
var newVolume = document.getElementById('nvxContenance').value;
var baseActuelle = JSON.parse(window.localStorage.getItem('Boisson'));
var erreur = 0;
var index = 0;
var expReg = /^[0-9]*$/;//expression reguliere, verifie si l'utilisateur n'entre que des chiffres
var expRegboisson = /^[a-zA-Z0-9ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ]*$/;
if(!expRegboisson.test(newBoisson))
{
$("#popUpNewBoisson").popup("close");//ferme la popup en cours car on ne peut pas ouvrir deux fenetres en meme temps
//Change le message de la popup d'erreur
document.getElementById('erreurPopUpAjtAlcool').innerHTML="N'utilisez que des chiffres et des lettres pour le nom des boissons";
//Ouvre la pop up d'erreur
window.setTimeout(function(){$("#popupDialogErreurAjtAlcool").popup('open')},200);
return false;
}
if((newDegre>100)|| !(expReg.test(newDegre))){
$("#popUpNewBoisson").popup("close");//ferme la popup en cours car on ne peut pas ouvrir deux fenetres en meme temps
//Change le message de la popup d'erreur
document.getElementById('erreurPopUpAjtAlcool').innerHTML="Veuillez saisir un degré compris entre 0 et 100";
//Ouvre la pop up d'erreur
window.setTimeout(function(){$("#popupDialogErreurAjtAlcool").popup('open')},200);
return;
}
if((newBoisson=="")||(newDegre=="")||(newVolume=="")){//Si l'utilisateur ne remplit pas un champ
$("#popUpNewBoisson").popup("close");//ferme la popup en cours car on ne peut pas ouvrir deux fenetres en meme temps
//Change le message de la popup d'erreur
document.getElementById('erreurPopUpAjtAlcool').innerHTML="Veuillez remplir les trois champs";
//Ouvre la pop up d'erreur
window.setTimeout(function(){$("#popupDialogErreurAjtAlcool").popup('open')},200);
return;
}
if((newVolume>2000)||(expReg.test(newVolume)==false)){
$("#popUpNewBoisson").popup("close");//ferme la popup en cours car on ne peut pas ouvrir deux fenetres en meme temps
//Change le message de la popup d'erreur
document.getElementById('erreurPopUpAjtAlcool').innerHTML="Veuillez saisir un volume inférieur";
//Ouvre la pop up d'erreur
window.setTimeout(function(){$("#popupDialogErreurAjtAlcool").popup('open')},200);
return;
}
newBoisson = newBoisson.charAt(0).toUpperCase() + newBoisson.substring(1);
/*Vérifie si une boisson du même nom n'est pas déjà présente dans la base*/
$.each(baseActuelle, function(key, value){//parcourt la base actuelle des boissons
if((baseActuelle[key]["boisson"])==(newBoisson)){
$("#popUpNewBoisson").popup("close");//ferme la popup en cours car on ne peut pas ouvrir deux fenetres en meme temps
//Change le message de la popup d'erreur
document.getElementById('erreurPopUpAjtAlcool').innerHTML="Cette boisson existe déjà";
//Ouvre la pop up d'erreur
window.setTimeout(function(){$("#popupDialogErreurAjtAlcool").popup('open')},200);
erreur=1;
}
});
//Si tous les champs sont remplis correctement
if(erreur==0){
newDegre=newDegre/100;//transforme le degré en pourcentage pr la suite des caluls
nouvelleBoisson =
{
"boisson" :newBoisson,
"degre" :newDegre,
"contenance":newVolume,
};
baseActuelle.push(nouvelleBoisson);//ajout de la nouvelle boisson dans le tableau
/*
$.each(baseActuelle, function(key, value){
for(i=0; (i<baseActuelle[key]["boisson"].length) && (i<nouvelleBoisson["boisson"].length); i++)
{
if(baseActuelle[key]["boisson"].charCodeAt(i) == nouvelleBoisson["boisson"].charCodeAt(i))
{
console.log('idem' + baseActuelle[key]["boisson"].charAt(i) + ' ' + nouvelleBoisson["boisson"].charAt(i) + ' '+i);
continue;
}
if(nouvelleBoisson["boisson"].charCodeAt(i) > baseActuelle[key]["boisson"].charCodeAt(i))
{
console.log(nouvelleBoisson["boisson"].charAt(i) + ' > ' + baseActuelle[key]["boisson"].charAt(i) + ' ' +i);
if(nouvelleBoisson["boisson"] == baseActuelle[key]["boisson"].substring(0, nouvelleBoisson["boisson"].length))
{
console.log('here ' + baseActuelle[key]["boisson"].substring(0, nouvelleBoisson["boisson"].length));
return false;
}
index++;
return true;
}
baseActuelle.splice(index, 0, nouvelleBoisson);
return false;
}
index++;
});
*/
//Trie du tableau par ordre alphabétique des boissons
baseActuelle.sort(function (a,b) {
/*
if(a.boisson > b.boisson)
{
return 1;
}
if(a.boisson < b.boisson)
{
return -1;
}*/
return (a.boisson).localeCompare(b.boisson);
});
baseActuelle=JSON.stringify(baseActuelle);//conversion au format JSON
window.localStorage.setItem('Boisson', baseActuelle);//enregistre le nouveau tableau dans le telephone
//Ferme la pop up d'ajout de boisson
$("#popUpNewBoisson").popup("close");
var vide = "";
window.localStorage.setItem('NombreVerres', vide);//Réinitialise le stockage des caracteristiques de la boisson à vide pour ne pas avoir d'ambiguité apres le rechargement de la page
//window.location.reload();// Fonctionne sous FireFox ...
$('#listeAlcools').html('');
testInitialisation();
$('#listeAlcools').listview("refresh");
}
});
/*
__ ______ ______ ___ __ _______.___________. ______ .______ ___ _______ _______
| | / __ \ / | / \ | | / | | / __ \ | _ \ / \ / _____|| ____|
| | | | | | | ,----' / ^ \ | | | (----`---| |----`| | | | | |_) | / ^ \ | | __ | |__
| | | | | | | | / /_\ \ | | \ \ | | | | | | | / / /_\ \ | | |_ | | __|
| `----.| `--' | | `----./ _____ \ | `----. .----) | | | | `--' | | |\ \----./ _____ \ | |__| | | |____
|_______| \______/ \______/__/ \__\ |_______| |_______/ |__| \______/ | _| `._____/__/ \__\ \______| |_______|
*/
/*Vérifie si l'utilisateur a déjà stocké les boissons de base*/
function testInitialisation()
{
//Suppression des données (verres, poids, genre) saisies précédement
window.localStorage.setItem('Genre', 0.6);//femme selectionnée par défaut
window.localStorage.removeItem('Poids');
window.localStorage.removeItem('NombreVerres');
var test = window.localStorage.getItem('Boisson');
var baseActuelle;
if(test == null)//si la base est vide
{
initBoissons();//on initialise la base
return;
}
//si des boissons sont déjà présentes dans le téléphone
baseActuelle = JSON.parse(window.localStorage.getItem('Boisson'));//on récupère la base présente dans le mobile..
afficheListe(baseActuelle, baseActuelle);//...et on l'affiche
}
function initBoissons(){
/*Initialisation d'un tableau JavaScript*/
var baseActuelle=[];
/*Définition des boissons de base*/
boisson1 =
{
"boisson": "Biere",
"degre":0.05,
"contenance":250,
};
boisson2=
{
"boisson":"Champagne",
"degre":0.12,
"contenance":100,
};
boisson3=
{
"boisson":"Cidre",
"degre":0.05,
"contenance":250,
};
boisson4=
{
"boisson":"Digestif",
"degre":0.45,
"contenance":25,
};
boisson5=
{
"boisson":"Pastis",
"degre":0.45,
"contenance":25,
};
boisson6=
{
"boisson":"Porto",
"degre":0.2,
"contenance":60,
};
boisson7=
{
"boisson":"Vin",
"degre":0.12,
"contenance":100,
};
boisson8=
{
"boisson":"Vodka",
"degre":0.375,
"contenance":40,
};
boisson9=
{
"boisson":"Whisky",
"degre":0.45,
"contenance":30,
};
/*Rajout de l'ensemble des boissons dans la base*/
for(i=1; i<=9;i++)
{
var boisson="boisson"+i;
baseActuelle.push(eval(boisson));//eval pour considerer boisson comme une variable et non un string
}
/*Affichage de l'ensemble des boissons dans la liste que peut choisir l'utilisateur*/
//$("#listeAlcools").html("");
afficheListe(baseActuelle, baseActuelle);
/*Conversion au format JSON pour le stockage*/
baseActuelle=JSON.stringify(baseActuelle);
/*Stockage des boissons*/
window.localStorage.setItem('Boisson', baseActuelle);
/*Stockage une variable comme quoi la base est maintenant enregistrée en local dans le mobile*/
/*
initialise=1;
window.localStorage.setItem('TestInitialisation', initialise);
*/
}
/*Affichage des noms de boissons dans la page pour choisir son alcool*/
function afficheListe(liste, listeBoissons)//le premier parametre correspond au nom de la liste, le deuxieme au stockage format "parser"
{
//var PosixTimeStamp;
$.each(listeBoissons, function(key, value){//parcourt l'ensemble de la liste passée en paramètre
var listeActuelle = $("#listeAlcools").html();//récupère le contenu actuel de la liste d'alcools
//document.getElementById('listeAlcools').innerHTML=listeActuelle + "<li class=\"ui-btn ui-icon-carat-r\" onClick=\"ouvrePopUpVerre('"+liste[key]["boisson"]+"','"+liste[key]["degre"]+"','"+liste[key]["contenance"]+"');\">"+liste[key]["boisson"]+"<span class=\"ui-li-count\" id=\""+liste[key]["boisson"]+"\" >"+0+"</span></li>";
$("#listeAlcools").append("<li class=\"ui-btn ui-icon-carat-r\" >"+liste[key]["boisson"]+"<span class=\"ui-li-count\" id=\""+liste[key]["boisson"]+"\" >"+0+"</span></li>");
$("#listeAlcools li #"+liste[key]["boisson"]).parents("li").bind("swipeleft", function () {
//$(this).css('background-color', '#ffec00');
$("#erreurPopUpSuppAlcool").text("Voulez vous supprimer cette boisson : "+liste[key]["boisson"] +" ?");
$("#suppression_id").unbind();
$("#suppression_id").bind("tap", function (){
supprimeBoisson(liste[key]["boisson"]);
$("#popupDialogErreurSuppAlcool").popup("close");
//$(this).css('background-color', '#f6f6f6');
});
$("#popupDialogErreurSuppAlcool").popup("open");
});
$("#listeAlcools li #"+liste[key]["boisson"]).parents("li").tap(function () {
ouvrePopUpVerre(liste[key]["boisson"],liste[key]["degre"],liste[key]["contenance"]);
});
/*Pour une suppression par longclick*/
/*
$("#listeAlcools li #"+liste[key]["boisson"]).parents("li").touchstart(function () {
PosixTimeStamp = new Date().getTime();
});
$("#listeAlcools li #"+liste[key]["boisson"]).parents("li").touchend(function () {
if(new Date().getTime()-PosixTimeStamp < 300)
{
ouvrePopUpVerre(liste[key]["boisson"],liste[key]["degre"],liste[key]["contenance"]);
return;
}
$("#erreurPopUpSuppAlcool").text("Voulez vous supprimer cette boisson : "+liste[key]["boisson"] +" ?");
$("#popupDialogErreurSuppAlcool").popup("open");
$("#suppression_id").unbind();
$("#suppression_id").bind("tap", function (){
supprimeBoisson(liste[key]["boisson"]);
});
});
*/
});
}
function supprimeBoisson(boisson)
{
var listeBoissons = JSON.parse(window.localStorage.getItem('Boisson'));
var index = 0;
$.each(listeBoissons, function(key){
if(listeBoissons[key]["boisson"] == boisson)
{
listeBoissons.splice(index, 1);
window.localStorage.setItem('Boisson', JSON.stringify(listeBoissons));
$('#listeAlcools').html('');
testInitialisation();
$('#listeAlcools').listview("refresh");
return false;
}
index++;
});
}
/*Boite de dialogue pour le choix du nombre de verrres*/
function ouvrePopUpVerre(verreBoisson, verreDegre, verreContenance)
{
var verre;
var vide = "";
window.localStorage.setItem('verre', vide);//Réinitialise le stockage des caracteristiques de la boisson à vide, au cas où l'utilisateur cliquerait dans le vide au lieu d'ajouter
/*Modifie les caractéristiques de la boisson a afficher*/
document.getElementById('boissonAjtVerres').innerHTML=verreBoisson;
document.getElementById('degreAjtVerre').innerHTML="<b>Degré : </b>"+verreDegre*100 +" %";
document.getElementById('volumeAjtVerre').innerHTML="<b>Volume : </b>"+verreContenance+" mL";
$("#nombreVerres").text($("#"+verreBoisson).text());
verre={
"nomV":verreBoisson,
"degreV":verreDegre,
"volV":verreContenance,
};
verre=JSON.stringify(verre);//format JSON
window.localStorage.setItem('verre', verre);//stock pr passer a la fonction ajout verre
//Ouvre la pop Up
$("#popupNbVerres").popup("open");
}
});//fin document ready
//Ajax Carte de localisation
/*****************************************************************/
function affiche_carte()
{
var em=document.getElementById("carte_de_localisation");
em.innerHTML='<iframe width="100%" height="93%" id="iframecarte" src="http://msr-cotesdarmor.com/wp-content/plugins/leaflet-maps-marker/leaflet-fullscreen.php?layer=5" frameborder="0"></iframe>';
}
<file_sep>//Premiers secours
var donner_alerte=1;
var etouffement=1;
var inconscience=1;
var saignement=1;
var arret_cardiaque=1;
function affiche_reponse_premier_secours(id_reponse){
var count;
var elements=document.getElementById(id_reponse);
switch (id_reponse)
{
case 'reponse_donner_alerte' :
var btn_libelle=document.getElementById('boutonDonnerAlerte');
if(donner_alerte == 3)
{
donner_alerte = 1;
}
count = donner_alerte;
donner_alerte++;
if(count==1)
{
elements.className="visible";
//Fermeture des autres affichages
document.getElementById('reponse_etouffement').className="invisible";
document.getElementById('reponse_inconscience').className="invisible";
document.getElementById('reponse_saignement').className="invisible";
document.getElementById('reponse_arret_cardiaque').className="invisible";
etouffement=1;
inconscience=1;
saignement=1;
arret_cardiaque=1;
document.getElementById('boutonEtouffement').style.backgroundColor="#CDCDCD";
document.getElementById('boutonInconscience').style.backgroundColor="#CDCDCD";
document.getElementById('boutonSaignement').style.backgroundColor="#CDCDCD";
document.getElementById('boutonCardiaque').style.backgroundColor="#CDCDCD";
btn_libelle.style.backgroundColor="#FFD700";
}
if(count==2)
{
elements.className="invisible";
btn_libelle.style.backgroundColor="#CDCDCD";
}
break;
case 'reponse_etouffement' :
var btn_libelle=document.getElementById('boutonEtouffement');
if(etouffement == 3)
{
etouffement = 1;
}
count = etouffement;
etouffement++;
if(count==1)
{
elements.className="visible";
//Fermeture des autres affichages
document.getElementById('reponse_donner_alerte').className="invisible";
document.getElementById('reponse_inconscience').className="invisible";
document.getElementById('reponse_saignement').className="invisible";
document.getElementById('reponse_arret_cardiaque').className="invisible";
donner_alerte=1;
inconscience=1;
saignement=1;
arret_cardiaque=1;
document.getElementById('boutonDonnerAlerte').style.backgroundColor="#CDCDCD";
document.getElementById('boutonInconscience').style.backgroundColor="#CDCDCD";
document.getElementById('boutonSaignement').style.backgroundColor="#CDCDCD";
document.getElementById('boutonCardiaque').style.backgroundColor="#CDCDCD";
btn_libelle.style.backgroundColor="#FFD700";
//document.location.href="#boutonDonnerAlerte";
}
if(count==2)
{
elements.className="invisible";
btn_libelle.style.backgroundColor="#CDCDCD";
}
break;
case 'reponse_inconscience' :
var btn_libelle=document.getElementById('boutonInconscience');
if(inconscience == 3)
{
inconscience = 1;
}
count = inconscience;
inconscience++;
if(count==1)
{
elements.className="visible";
//Fermeture des autres affichages
document.getElementById('reponse_donner_alerte').className="invisible";
document.getElementById('reponse_etouffement').className="invisible";
document.getElementById('reponse_saignement').className="invisible";
document.getElementById('reponse_arret_cardiaque').className="invisible";
donner_alerte=1;
etouffement=1;
saignement=1;
arret_cardiaque=1;
document.getElementById('boutonDonnerAlerte').style.backgroundColor="#CDCDCD";
document.getElementById('boutonEtouffement').style.backgroundColor="#CDCDCD";
document.getElementById('boutonSaignement').style.backgroundColor="#CDCDCD";
document.getElementById('boutonCardiaque').style.backgroundColor="#CDCDCD";
btn_libelle.style.backgroundColor="#FFD700";
//document.location.href="#boutonEtouffement";
}
if(count==2)
{
elements.className="invisible";
btn_libelle.style.backgroundColor="#CDCDCD";
}
break;
case 'reponse_saignement' :
var btn_libelle=document.getElementById('boutonSaignement');
if(saignement == 3)
{
saignement = 1;
}
count = saignement;
saignement++;
if(count==1)
{
elements.className="visible";
//Fermeture des autres affichages
document.getElementById('reponse_donner_alerte').className="invisible";
document.getElementById('reponse_etouffement').className="invisible";
document.getElementById('reponse_inconscience').className="invisible";
document.getElementById('reponse_arret_cardiaque').className="invisible";
donner_alerte=1;
etouffement=1;
inconscience=1;
arret_cardiaque=1;
document.getElementById('boutonDonnerAlerte').style.backgroundColor="#CDCDCD";
document.getElementById('boutonEtouffement').style.backgroundColor="#CDCDCD";
document.getElementById('boutonInconscience').style.backgroundColor="#CDCDCD";
document.getElementById('boutonCardiaque').style.backgroundColor="#CDCDCD";
btn_libelle.style.backgroundColor="#FFD700";
//document.location.href="#boutonInconscience";
}
if(count==2)
{
elements.className="invisible";
btn_libelle.style.backgroundColor="#CDCDCD";
}
break;
case 'reponse_arret_cardiaque' :
var btn_libelle=document.getElementById('boutonCardiaque');
if(arret_cardiaque == 3)
{
arret_cardiaque = 1;
}
count = arret_cardiaque;
arret_cardiaque++;
if(count==1)
{
elements.className="visible";
//Fermeture des autres affichages
document.getElementById('reponse_donner_alerte').className="invisible";
document.getElementById('reponse_etouffement').className="invisible";
document.getElementById('reponse_inconscience').className="invisible";
document.getElementById('reponse_saignement').className="invisible";
donner_alerte=1;
etouffement=1;
inconscience=1;
saignement=1;
document.getElementById('boutonDonnerAlerte').style.backgroundColor="#CDCDCD";
document.getElementById('boutonEtouffement').style.backgroundColor="#CDCDCD";
document.getElementById('boutonInconscience').style.backgroundColor="#CDCDCD";
document.getElementById('boutonSaignement').style.backgroundColor="#CDCDCD";
btn_libelle.style.backgroundColor="#FFD700";
btn_libelle.style.backgroundColor="#FFD700";
//document.location.href="#boutonSaignement";
}
if(count==2)
{
elements.className="invisible";
btn_libelle.style.backgroundColor="#CDCDCD";
}
break;
}
}<file_sep>/*
_______ .______ _______ __ .__ __. ___ _______ _______
| ____|| _ \ | ____|| | | \ | | / \ / _____|| ____|
| |__ | |_) | | |__ | | | \| | / ^ \ | | __ | |__
| __| | / | __| | | | . ` | / /_\ \ | | |_ | | __|
| | | |\ \----.| |____ | | | |\ | / _____ \ | |__| | | |____
|__| | _| `._____||_______||__| |__| \__| /__/ \__\ \______| |_______|
*/
function simuDistanceArret()
{
var vitessem;
var dtr;//distance de reaction
var df;//distance de freinage
var da;//distance d'arret
vitessem = (document.getElementById('vitesseSimuArret').value)*1000;//recupere la vitesse en m/H
if(isNaN(vitessem) || vitessem =='')
{
document.getElementById('erreurPopUpFrein').innerHTML="Veuillez entrer une vitesse";
$("#popupDialogErreurFrein").popup('open');
return;
}
dtr = distanceReaction(vitessem);
df = distanceFreinage(vitessem);
da = distanceArret(dtr, df);
$("#DistancesPopUp").popup('open');
}
function distanceReaction(vitessem)
{
/*Temps de réaction en fontion de l'état de l'utilisateur*/
var etat = document.getElementById('etatSimuDA').value;
switch(etat)
{
case 'N'://"normal"
etat = 1;//seconde de reaction
break;
case 'F'://fatigué
etat = 2;
break;
case 'A'://alccolisé
etat = 3;
break;
}
var dtr = (vitessem*etat/3600).toFixed(2);//calcul la distance de reaction
document.getElementById('distReaction').innerHTML="<b>Réaction : </b>"+dtr+" m";
return dtr;
}
function distanceFreinage(vitessem)
{
var chausse;
if(formWeather.btnRadio[1].checked)
{
chausse=formWeather.btnRadio[1].value;
}
if(formWeather.btnRadio[0].checked)
{
chausse=formWeather.btnRadio[0].value;
}
switch(chausse)
{
case 'S'://seche
df = ((Math.pow((vitessem/3600),2)/14)).toFixed(2);//math.pow : élevé à la puissance
break;
case 'M' ://mouillée
df = ((Math.pow((vitessem/3600),2)/7)).toFixed(2);
}
document.getElementById('distFreinage').innerHTML="<b>Freinage : </b>"+df+" m";
return df;
}
function distanceArret(dtr, df)
{
da = (parseFloat(dtr) + parseFloat(df)).toFixed(2);//empeche la concatenation des nombres
document.getElementById('distArret').innerHTML="<b>Arrêt : </b>"+da+" m";
}
|
32147fe0e5b4f14f45b6651b53ce2d44a19cd03b
|
[
"JavaScript"
] | 6 |
JavaScript
|
phildurand/APPSR
|
483cac2083b5febef353325c3816c6003dfbdbf1
|
6681f4b96e90c7dc2d940fd5e98d506a4263c0f0
|
refs/heads/main
|
<file_sep>function removeDuplicateValues(arr) {
return (
arr.reduce((unique, item) => {
return unique.includes(item) ? unique : [...unique, item]
}, [])
)
}
const arrOne = ["one", "two", "one", "three", "three", "two"]
const arrTwo = [2, 4, 7, 5, 4, 5, 6, 3, 2, 9, 10]
console.log(removeDuplicateValues(arrOne))
console.log(removeDuplicateValues(arrTwo))
|
76cd66359df02c93fcdf41956217c82f84750ae4
|
[
"JavaScript"
] | 1 |
JavaScript
|
nodyalclaydon/reduce-function-remove-array-duplicates
|
475263dccf32aac7c5152ab85a56762cd2e1f1cf
|
612d8495724b79b094f9a08c52ce08cf72d0f62a
|
refs/heads/master
|
<repo_name>pp8323127/HttpListener_POST<file_sep>/HttpListener_POST/MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Threading;
using System.IO;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.ComponentModel;
namespace HttpListener_POST
{
/// <summary>
/// MainWindow.xaml 的互動邏輯
/// </summary>
public partial class MainWindow : Window
{
static HttpListener listener;
private Thread listenThread1;
/** method stolen from an SO thread. sorry can't remember the author **/
static void AddAddress(string address, string domain, string user)
{
string args = string.Format(@"http add urlacl url={0}", address) + " user=\"" + domain + "\\" + user + "\"";
ProcessStartInfo psi = new ProcessStartInfo("netsh", args);
psi.Verb = "runas";
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = true;
Process.Start(psi).WaitForExit();
}
public MainWindow()
{
InitializeComponent();
showTextBox();
//AddAddress("http://172.16.17.32:1508/", Environment.UserDomainName, Environment.UserName);
AddAddress("http://*:1508/", Environment.UserDomainName, Environment.UserName);
listener = new HttpListener();
try
{
///listener.Prefixes.Add("http://localhost:8000/");
//listener.Prefixes.Add("http://127.0.0.1:8000/");
//listener.Prefixes.Add("http://172.16.17.32:8000/");
//listener.Prefixes.Add("http://172.16.17.32:1508/");
listener.Prefixes.Add("http://*:1508/");
listener.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
listener.Start();
this.listenThread1 = new Thread(new ParameterizedThreadStart(startlistener));
listenThread1.Start();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
//finally
//{
// listener.Stop();
//}
}
private void MainWindow_Closing()
{
listener.Stop();
}
private void startlistener(object s)
{
while (true)
{
////blocks until a client has connected to the server
ProcessRequest();
}
}
private void ProcessRequest()
{
var result = listener.BeginGetContext(ListenerCallback, listener);
result.AsyncWaitHandle.WaitOne();
}
private void ListenerCallback(IAsyncResult result)
{
var context = listener.EndGetContext(result);
Thread.Sleep(1000);
var post_raw_data = new StreamReader(context.Request.InputStream, context.Request.ContentEncoding).ReadToEnd();
//functions used to decode json encoded data.
//JavaScriptSerializer js = new JavaScriptSerializer();
//var data1 = Uri.UnescapeDataString(post_raw_data);
//string da = Regex.Unescape(post_raw_data);
// var unserialized = js.Deserialize(post_raw_data, typeof(String));
var post_data = System.Web.HttpUtility.UrlDecode(post_raw_data);
//MessageBox.Show(post_data);
if (post_data != "")
{
string str = post_data;
str.Substring(post_data.Length - 10, 10);
//MessageBox.Show(str);
//MessageBox.Show(post_data);
DateTime mNow = DateTime.Now;
//MessageBox.Show(mNow.ToString("yyyy-MM-dd HH:mm:ss"));
//string strInvoice = mNow.ToString("yyyy-MM-dd HH:mm:ss") + ", " + post_data.Substring(post_data.Length - 10, 10) + ", " + Environment.NewLine;
string strInvoice = mNow.ToString("yyyy-MM-dd HH:mm:ss") + ", " + post_data + ", " + Environment.NewLine;
//MessageBox.Show(strInvoice);
////bool b = File.Exists("tmp.txt"); // 判定檔案是否存在
////File.Create("tmp.txt"); // 建立檔案
//string text = File.ReadAllText("tmp.txt"); // 讀取檔案內所有文字
//File.WriteAllText("tmp.txt", text + "/n" + post_data); // 將 text 寫入檔案
string path = @"tmp.txt";
File.AppendAllText(path, strInvoice);
//// Open the file to read from.
//using (StreamReader sr = File.OpenText("tmp.txt"))
//{
// string s = "";
// while ((s = sr.ReadLine()) != null)
// {
// Console.WriteLine(s);
// }
//}
}
context.Response.StatusCode = 200;
context.Response.StatusDescription = "OK";
//use this line to get your custom header data in the request.
//var headerText = context.Request.Headers["mycustomHeader"];
//use this line to send your response in a custom header
//context.Response.Headers["mycustomResponseHeader"] = "mycustomResponse";
context.Response.Close();
}
private void showTextBox()
{
textBox.Text = File.ReadAllText("tmp.txt");
textBox.ScrollToEnd();
}
private void MainWindow_Closing(object sender, CancelEventArgs e)
{
//listener.Close();
listener.Stop();
}
private void button_Click(object sender, RoutedEventArgs e)
{
showTextBox();
}
}
}
|
22dc7dfc7ec1b617fb22d02475c547ff00a2eae5
|
[
"C#"
] | 1 |
C#
|
pp8323127/HttpListener_POST
|
d585c7cb3870a63323f031ca6c8e7d8472f68565
|
6e62d56f4d6af9a7f3f3a707a2892709847c5250
|
refs/heads/master
|
<repo_name>tangyuezong/test<file_sep>/bb/application/admin/controller/Index.php
<?php
namespace app\admin\controller;
use think\Db;
use think\Controller;
use think\Request;
class Index extends Common
{
/**
* 显示资源列表
*
* @return \think\Response
*/
public function index()
{
return view();
}
public function loginout()
{
session(null,'login');
$this->success('退出成功','admin/login/index');
return view();
}
//加载欢迎界面
public function welcome(){
$server=[
'HTTP_HOST'=>$_SERVER['HTTP_HOST'],
'SERVER_SOFTWARE'=>$_SERVER['SERVER_SOFTWARE'],
'osname'=>php_uname(),
'HTTP_ACCEPT_LANGUAGE'=>$_SERVER['HTTP_ACCEPT_LANGUAGE'],
'SERVER_PORT'=>$_SERVER['SERVER_PORT'],
'SERVER_NAME'=>$_SERVER['SERVER_NAME'],
];
$version=Db::query("select version()");
$server['mysqlversion']=$version[0]['version()'];
$server['databasename'] =config('database')['database'];
$server['phpversion']=phpversion();
$server['maxupload']=ini_get('max_file_uploads');
$this->assign('server',$server);
return view();
}
public function modify()
{
if (Request()->isPost()) {
$data=input('post.');
if ($data['repassword']!=$data['password']) {
$this->error('俩次密码输入不一致');
}
$userid=session('loginid','','login');
$res=db('manager')->where('Id',$userid)->field('Id,password')->find();
if ($res['password']!=$data['oldpassword']) {
$this->error('旧密码输入错误');
}
$result=db('manager')->where('Id',$res['Id'])->update(['password'=>$data['password']]);
if (!$result) {
$this->error('俩次密码相同');
}
$this->success('修改密码成功');
}
return view();
}
}
<file_sep>/bb/application/index/controller/Index.php
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
class Index extends Common
{
/**
* 显示资源列表
*
* @return \think\Response
*/
public function index()
{
$a=session('loginid','','userlogin');
$data=db('yeji')->where('uid',$a)->order('settime Desc')->select();
$this->assign('data',$data);
return view();
}
public function add()
{
return view();
}
/**
* 保存新建的资源
*
* @param \think\Request $request
* @return \think\Response
*/
public function save(Request $request)
{
if (request()->isPost()) {
$data=input('post.');
$data['uid']=session('loginid','','userlogin');
$data['updatetime']=time();
if (!db('yeji')->insert($data)) {
$this->error('添加失败');
}
$this->success('添加成功','index/index/index');
}
}
/**
* 显示编辑资源表单页.
*
* @param int $id
* @return \think\Response
*/
public function edit($id)
{
$data=db('yeji')->where('id',$id)->find();
$this->assign('data',$data);
return view();
}
/**
* 保存更新的资源
*
* @param \think\Request $request
* @param int $id
* @return \think\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* 删除指定资源
*
* @param int $id
* @return \think\Response
*/
public function delete($id)
{
if (!db('yeji')->delete($id)) {
$this->error('删除失败');
}else{
$this->success("删除成功",'index/index/index');
}
}
public function logout()
{
session(null,'userlogin');
$this->success("退出成功",'index/Login/index');
}
}
<file_sep>/bb/application/admin/controller/Yeji.php
<?php
namespace app\admin\controller;
use think\Controller;
use think\Request;
class Yeji extends Controller
{
/**
* 显示资源列表
*
* @return \think\Response
*/
public function index()
{
$data=db('yeji')->where('state',0)->order('updatetime Desc')->select();
$this->assign('data',$data);
return view();
}
/**
* 显示待审核资源表单页.
*
* @return \think\Response
*/
public function shenhe(Request $request)
{
$id=input('Id');
$sta=input('sta');
$settime=time();
$res=db('yeji')->where('Id',$id)->update(['state'=>$sta, 'settime'=> $settime]);
return;
}
/**
* 显示创建资源表单页.
*
* @return \think\Response
*/
public function lst()
{
$data=db('yeji')->order('updatetime Desc')->select();
$this->assign('data',$data);
return view();
}
public function gzff()
{
$data=db('yeji')->alias('a')
->join('user b','a.uid=b.Id')
->group('a.uid')
->where('a.state','in',[1,2])
->field('a.*,a.id as yejiid,a.state as yejistate,b.name,b.state as userstate,b.Id as userid,b.age,sum(a.yeji)*b.ticheng/100 as heji')
->order('a.updatetime Desc')
->select();
$this->assign('data',$data);
return view();
}
/**
* 保存新建的资源
*
* @param \think\Request $request
* @return \think\Response
*/
public function save(Request $request)
{
//
}
/**
* 显示指定的资源
*
* @param int $id
* @return \think\Response
*/
public function read($id)
{
//
}
/**
* 显示编辑资源表单页.
*
* @param int $id
* @return \think\Response
*/
public function edit($id)
{
//
}
/**
* 保存更新的资源
*
* @param \think\Request $request
* @param int $id
* @return \think\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* 删除指定资源
*
* @param int $id
* @return \think\Response
*/
public function delete($id)
{
//
}
}
<file_sep>/bb/application/index/controller/Common.php
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
class Common extends Controller
{
protected function initialize()
{
$a=session('loginname','','userlogin');
if (!$a) {
$this->redirect('index/Login/index');
}
}
}
<file_sep>/1.php
<?php
echo "hello wsorld";
?><file_sep>/bb/application/admin/controller/Login.php
<?php
namespace app\admin\controller;
use think\Controller;
use think\Request;
class Login extends Controller
{
public function index()
{
$a=session('?loginname','','login');
if ($a!=1) {
return view();
}
$this->redirect('admin/index/index');
}
public function login()
{
$data=input('post.');
$res=db('Manager')->where('name',$data['name'])->field('Id,name,password')->find();
if ($data['name']!=$res['name']) {
$this->error('用户名不存在');
}
if ($data['password']!=$res['password']) {
$this->error('密码错误');
}
session('loginname',$res['name'],'login');
session('loginid',$res['Id'],'login');
db('Manager')->where('id',$res['Id'])->update(['logintime'=>time()]);
$this->success('登录成功','admin/index/index',null,1);
}
}
<file_sep>/bb/application/index/controller/Login.php
<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
class Login extends Controller
{
/**
* 显示资源列表
*
* @return \think\Response
*/
public function index()
{
$a=session('?loginname','','userlogin');
if ($a!=1) {
return view();
}
$this->redirect('index/login/index');
}
public function login()
{
$data=input('post.');
$res=db('user')->where('name',$data['name'])->field('Id,name,password')->find();
if ($data['name']!=$res['name']) {
$this->error('用户名不存在');
}
if ($data['password']!=$res['password']) {
$this->error('密码错误');
}
session('loginname',$res['name'],'userlogin');
session('loginid',$res['Id'],'userlogin');
$this->success('登录成功','index/index/index',null,1);
}
}
<file_sep>/bb/application/admin/controller/Common.php
<?php
namespace app\admin\controller;
use think\Controller;
use think\Request;
class Common extends Controller
{
protected function initialize()
{
$a=session('?loginname','','login');
if ($a!=1) {
$this->redirect('admin/login/index');
}
}
}
<file_sep>/bb/application/admin/controller/User.php
<?php
namespace app\admin\controller;
use think\Controller;
use think\Request;
class User extends Common
{
/**
* 显示资源列表
*
* @return \think\Response
*/
public function index()
{
$data=db('user')->select();
$this->assign('data',$data);
return view();
}
/**
* 显示创建资源表单页.
*
* @return \think\Response
*/
public function add()
{
return view();
}
/**
* 保存新建的资源
*
* @param \think\Request $request
* @return \think\Response
*/
public function save(Request $request)
{
if (request()->isPost()) {
$data=input('post.');
$data['createtime']=time();
$data['password']='<PASSWORD>';
if (!db('user')->insert($data)) {
$this->success('添加失败');
}
$this->success('添加成功','admin/user/index');
}
}
/**
* 显示指定的资源
*
* @param int $id
* @return \think\Response
*/
public function read($id)
{
//
}
/**
* 显示编辑资源表单页.
*
* @param int $id
* @return \think\Response
*/
public function edit($id)
{
$data=db('user')->where('Id',$id)->find();
$this->assign('data',$data);
return view();
}
/**
* 保存更新的资源
*
* @param \think\Request $request
* @param int $id
* @return \think\Response
*/
public function update(Request $request)
{
if (Request()->isPost()) {
$data=$request->post();
if (!db('user')->update($data)) {
$this->error('修改失败');
}
$this->success('修改成功','user/index');
}
}
/**
* 删除指定资源
*
* @param int $id
* @return \think\Response
*/
public function delete($id)
{
if (Request()->isGet()) {
$res=db('user')->delete($id);
if (!$res) {
$this->error('删除失败');
}
$this->success('删除成功','user/index');
}
}
}
|
9f8864b941b31d2717af7b3367aa434618f58952
|
[
"PHP"
] | 9 |
PHP
|
tangyuezong/test
|
286ff6ce7b7515d11f39af1421cce4190323a06f
|
67c71ad92c98a09e86df6d421be063bba1fea7d9
|
refs/heads/master
|
<file_sep><?php
namespace App\Http\Controllers;
require "twitteroauth/autoload.php";
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Abraham\TwitterOAuth\TwitterOAuth;
class TwitterController extends Controller
{
var $CONSUMER_KEY = "tj5gC8eInAhyFqDZzLxj9yfJb";
var $CONSUMER_SECRET = "5LT4EEgkRErSDIDVsMEc0najghfF2hrIdtRO7Vo8kmYV3S657P";
var $access_token = "<KEY>";
var $access_token_secret = "<KEY>";
var $connection;
var $length_of_tweets = 20;
var $result = array();
public function __construct(){
$this->connection = new TwitterOAuth($this->CONSUMER_KEY, $this->CONSUMER_SECRET, $this->access_token, $this->access_token_secret);
}
public function twitterRest(){
return view('pages.twitter_REST');
}
public function twitterRESTApi(Request $request){
$response = array();
//$content = $this->connection->get("account/verify_credentials");
//return response()->json(['display', 'Information updated']);
//return response()->json(['display', $request->input('hash_text')]);
if ($request->has('hash_text'))
{
$hash_text = $request->input('hash_text');
//return response()->json(['display', $hash_text]);
//$hash_result = build_multiple_hashtag_search($hash_text);
$statuses = $this->connection->get("search/tweets", array("q" => $hash_text, "until" => "2015-12-07"));
return response()->json(['display', $statuses]);
$response["success"] = $hash_text;
$this->build_up_result_array($statuses);
return response()->json( $this->send_array());
// echo $this->send_array();
}
else{
$response["error"] = "can not find hash_text in your get request!";
return response()->json(json_encode($response));
}
}
public function build_multiple_hashtag_search($hash_text)
{
$return_value = "";
preg_match_all("/(#\w+)/", $hash_text, $matches);
for ($i = 0; $i < sizeof($matches[0]); $i++) {
if ($i != sizeof($matches[0]) - 1) {
$return_value = $return_value . "%23" . $matches[0][$i] . "+OR+";
} else {
$return_value = $return_value . "%23" . $matches[0][$i];
}
}
return $return_value;
}
public function build_up_result_array($statuses)
{
for ($i = 0; $i < $this->length_of_tweets; $i++) {
$this->result[$i] = $statuses->statuses[$i];
}
}
//print_r($result[4]->text);
public function send_array()
{
$response["display"] = array();
for ($i = 0; $i < $this->length_of_tweets; $i++) {
$display = array();
$display["user_img"] = $this->result[$i]->user->profile_image_url;
$display["username"] = $this->result[$i]->user->name;
$display["text"] = $this->result[$i]->text;
// $display["user_img"] = $result[$i]['user']['profile_image_url'];
// $display["username"] = $result[$i]['user']['name'];
// $display["text"] = $result[$i]['text'];
array_push($response["display"], $display);
}
return json_encode($response);
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sg.edu.nus.iss.phoenix.schedule.entity;
import java.util.Date;
import java.util.List;
import sg.edu.nus.iss.phoenix.schedule.delegate.ReviewSelectScheduleDelegate;
/**
*
* @author ADMIN
*/
public class WeeklySchedule {
private Date startDate;
private String assignedBy;
private List<ProgramSlot> programSlotList;
public WeeklySchedule() {
}
public void retriveProgramSlotList(){
ReviewSelectScheduleDelegate del = new ReviewSelectScheduleDelegate();
programSlotList = del.reviewSelectProgramSlot();
}
public WeeklySchedule(String assignedBy) {
this.assignedBy = assignedBy;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public String getAssignedBy() {
return assignedBy;
}
public void setAssignedBy(String assignedBy) {
this.assignedBy = assignedBy;
}
public List<ProgramSlot> getProgramSlotList() {
return programSlotList;
}
}
<file_sep>/**
* Created by jixiang on 25/8/15.
*/
$(document).ready(function(){
var submitIcon = $('.searchbox-submit');
var inputBox = $('.searchbox-input');
var searchBox = $('.searchbox');
var searchIcon = $('.searchbox-icon');
var isOpen = false;
submitIcon.css('display','none');
searchIcon.click(function(){
if(isOpen == false){
searchBox.addClass('searchbox-open');
searchIcon.css('display','none');
submitIcon.css('display','block');
inputBox.focus();
isOpen = true;
} else {
searchBox.removeClass('searchbox-open');
searchIcon.css('display','block');
submitIcon.css('display','none');
inputBox.focusout();
isOpen = false;
}
});
searchIcon.mouseup(function(){
return false;
});
searchBox.mouseup(function(){
return false;
});
$(document).mouseup(function(){
if(isOpen == true){
//searchIcon.css('display','block');
searchIcon.click();
}
//var isExpaned = $('#bs-example-navbar-collapse-1').className;
//if (isExpaned === 'navbar-collapse collapse in'){
// isExpaned.className='navbar-collapse collapse';
//}
$(".navbar-collapse").collapse('hide');
});
//var title = $(this).attr('title').toLowerCase();
//alert(title);
//var lastTab = $.cookie('lastTab');
var lastTab = getCookie('lastTab');
//alert(lastTab);
if (lastTab) {
$('.main-main-presentation-div ul li:has(a[href="' + lastTab + '"])').addClass("active");
}
});
function buttonUp(){
var inputVal = $('.searchbox-input').val();
inputVal = $.trim(inputVal).length;
if( inputVal !== 0){
$('.searchbox-icon').css('display','none');
} else {
$('.searchbox-input').val('');
//$('.searchbox-icon').css('display','block');
}
}
$('.main-main-presentation-div ul li').click(function (e) {
$(this).siblings().removeClass("active");
$(this).addClass("active");
var href = $(this).children('a').attr('href');
//alert(href);
//localStorage.setItem('lastTab', href);
document.cookie = "lastTab="+href;
//$.cookie('lastTab', href, {expires: 7});
//alert(document.cookie);
if(e.target.nodeName == 'A') return;
});
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
}
return "";
}
////
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sg.edu.nus.iss.phoenix.radioprogram.controller;
import at.nocturne.api.Action;
import at.nocturne.api.Perform;
import java.io.IOException;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sg.edu.nus.iss.phoenix.radioprogram.delegate.ProgramDelegate;
import sg.edu.nus.iss.phoenix.radioprogram.delegate.ReviewSelectProgramDelegate;
import sg.edu.nus.iss.phoenix.radioprogram.entity.RadioProgram;
/**
*
* @author boonkui
*/
@Action("enterrp")
public class EnterProgramDetailsCmd implements Perform {
@Override
public String perform(String path, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
ProgramDelegate del = new ProgramDelegate();
RadioProgram rp = new RadioProgram();
rp.setName(req.getParameter("name"));
rp.setDescription(req.getParameter("description"));
String dur = req.getParameter("typicalDuration");
System.out.println(rp.toString());
Time t;
if (isTimeValid(dur)) {
t = strToTime(dur);
}else{
return "/pages/error.jsp";
}
rp.setTypicalDuration(t);
String ins = (String) req.getParameter("ins");
Logger.getLogger(getClass().getName()).log(Level.INFO,
"Insert Flag: " + ins);
if (ins.equalsIgnoreCase("true")) {
del.processCreate(rp);
} else {
del.processModify(rp);
}
ReviewSelectProgramDelegate rsdel = new ReviewSelectProgramDelegate();
List<RadioProgram> data = rsdel.reviewSelectRadioProgram();
req.setAttribute("rps", data);
return "/pages/crudrp.jsp";
}
public boolean isTimeValid(String dur) {
Time result;
try {
result = Time.valueOf(dur);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public Time strToTime(String dur){
Time result = null;
Date result2 = null;
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
long ms;
try {
ms = sdf.parse(dur).getTime();
result = new Time(ms);
result2 = sdf.parse(dur);
} catch (ParseException ex) {
Logger.getLogger(EnterProgramDetailsCmd.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
}
<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sg.edu.nus.iss.phoenix.producer.delegate;
import java.util.List;
import sg.edu.nus.iss.phoenix.producer.entity.Producer;
import sg.edu.nus.iss.phoenix.producer.service.ProducerService;
import sg.edu.nus.iss.phoenix.utils.RecordDisplay;
/**
*
* @author <NAME>
*/
public class ProducerDelegate {
private ProducerService producerService;
public ProducerDelegate() {
producerService = new ProducerService();
}
public Producer findProducer(String id){
return producerService.findProducer(id);
}
public List<Producer> findAllProducers(Producer example) {
return producerService.findAllProducers(example);
}
public List<Producer> findAllProducers(Producer example, RecordDisplay criteria) {
return producerService.findAllProducers(example, criteria);
}
public List<Producer> findAllProducers(){
return producerService.findAllProducers();
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: jixiang
* Date: 23/10/15
* Time: 12:21 PM
*/
// The OAuth credentials you received when registering your app at Twitter
define("TWITTER_CONSUMER_KEY", "tj5gC8eInAhyFqDZzLxj9yfJb");
define("TWITTER_CONSUMER_SECRET", "5LT4EEgkRErSDIDVsMEc0najghfF2hrIdtRO7Vo8kmYV3S657P");
// The OAuth data for the twitter account
define("OAUTH_TOKEN", "<KEY>");
define("OAUTH_SECRET", "<KEY>");
?><file_sep>package sg.edu.nus.iss.phoenix.schedule.entity;
import java.io.Serializable;
import java.util.Date;
import sg.edu.nus.iss.phoenix.radioprogram.entity.RadioProgram;
import sg.edu.nus.iss.phoenix.utils.DateFormat;
import java.text.ParseException;
import sg.edu.nus.iss.phoenix.presenter.entity.Presenter;
import sg.edu.nus.iss.phoenix.producer.entity.Producer;
public class ProgramSlot implements Cloneable, Serializable {
/**
* eclipse identifier
*/
private static final long serialVersionUID = -5500218812568593553L;
/**
* Persistent Instance variables. This data is directly
* mapped to the columns of database table.
*/
private int id;
private Date duration;
private Date dateOfProgram;
private Date startTime;
private RadioProgram radioProgram;
private Presenter presenter;
private Producer producer;
/**
* Constructors.
* The first one takes no arguments and provides the most simple
* way to create object instance. The another one takes one
* argument, which is the primary key of the corresponding table.
*/
public ProgramSlot () {
}
public ProgramSlot (int id) {
this.id=id;
}
/**
* Get- and Set-methods for persistent variables. The default
* behaviour does not make any checks against malformed data,
* so these might require some manual additions.
*/
public int getId(){
return this.id;
}
public void setId(int id){
this.id=id;
}
public Date getDuration() {
return this.duration;
}
public void setDuration(Date duration){
this.duration = duration;
}
public void setDuration(String durationIn) {
try{
Date dur = DateFormat.SCHEDULE_TIME.parse(durationIn);
setDuration(dur);
}catch(ParseException e){
e.printStackTrace();;
}
}
public Date getDateOfProgram() {
return this.dateOfProgram;
}
public void setDateOfProgram(String dateOfProgramStr) {
try{
Date dur = DateFormat.SCHEDULE_DATE.parse(dateOfProgramStr);
setDateOfProgram(dur);
}catch(ParseException e){
e.printStackTrace();
}
}
public void setDateOfProgram(Date dateOfProgram) {
this.dateOfProgram = dateOfProgram;
}
public Date getStartTime() {
return this.startTime;
}
public void setStartTime(Date startTime){
this.startTime = startTime;
}
public void setStartTime(String startTime) {
try{
Date dur = DateFormat.SCHEDULE_TIME.parse(startTime);
setStartTime(dur);
}
catch(ParseException e){
e.printStackTrace();;
}
}
public RadioProgram getRadioProgram() {
return this.radioProgram;
}
public void setRadioProgram(RadioProgram radioProgram) {
this.radioProgram = radioProgram;
}
public Presenter getPresenter() {
return this.presenter;
}
public void setPresenter(Presenter presenter) {
this.presenter = presenter;
}
public Producer getProducer() {
return this.producer;
}
public void setProducer(Producer producer) {
this.producer = producer;
}
/**
* setAll allows to set all persistent variables in one method call.
* This is useful, when all data is available and it is needed to
* set the initial state of this object. Note that this method will
* directly modify instance variables, without going trough the
* individual set-methods.
*/
public void setAll(int id,String durationIn,Date dateOfProgramIn,String startTimeIn,
String radioProgramIn,String presenterIn,String producerIn) {
setId(id);
setDuration(durationIn);
this.dateOfProgram = dateOfProgramIn;
setStartTime( startTimeIn);
RadioProgram rp= new RadioProgram(radioProgramIn);
this.radioProgram= rp;
Presenter p1 = new Presenter(presenterIn);
this.presenter=p1;
Producer p2 = new Producer(producerIn);
this.producer=p2;
}
/**
* hasEqualMapping-method will compare two ProgramSlot instances
* and return true if they contain same values in all persistent instance
* variables. If hasEqualMapping returns true, it does not mean the objects
* are the same instance. However it does mean that in that moment, they
* are mapped to the same row in database.
*/
public boolean hasEqualMapping(RadioProgram valueObject) {
// to do
return true;
}
/**
* toString will return String object representing the state of this
* valueObject. This is useful during application development, and
* possibly when application is writing object states in text log.
*/
public String toString() {
StringBuffer out = new StringBuffer();
out.append("\nProgramSlot class, mapping to table program-slot\n");
out.append("Persistent attributes: \n");
out.append("id = " + this.id + "\n");
out.append("duration = " + this.duration + "\n");
out.append("dateOfProgram = " + this.dateOfProgram + "\n");
out.append("startTime = " + this.startTime + "\n");
out.append("radioProgram = " + this.radioProgram.getName()+ "\n");
out.append("presenter = " + this.presenter.getId()+ "\n");
out.append("producer = " + this.producer.getId()+ "\n");
return out.toString();
}
/**
* Clone will return identical deep copy of this valueObject.
* Note, that this method is different than the clone() which
* is defined in java.lang.Object. Here, the returned cloned object
* will also have all its attributes cloned.
*/
public Object clone() {
ProgramSlot cloned = new ProgramSlot();
//to do
return cloned;
}
@Override
public boolean equals(Object obj)
{
if(!(obj instanceof ProgramSlot)) return false;
ProgramSlot p = (ProgramSlot) obj;
//if same id
if(p.getId() == this.id) return true;
//if same value?
return p.getDateOfProgram().equals(this.dateOfProgram) && p.getStartTime().equals(this.startTime);
}
}
<file_sep>package sg.edu.nus.iss.phoenix.schedule.delegate;
import java.util.Date;
import sg.edu.nus.iss.phoenix.schedule.entity.ProgramSlot;
import sg.edu.nus.iss.phoenix.schedule.service.ScheduleService;
public class ScheduleDelegate {
/*
public ArrayList<RadioProgram> searchPrograms(RPSearchObject rpso) {
RadioProgram rp = new RadioProgram(rpso.getName());
rp.setDescription(rpso.getDescription());
ProgramService service = new ProgramService();
return service.searchPrograms(rp);
}
public ArrayList<RadioProgram> findRPByCriteria(RPSearchObject rpso) {
RadioProgram rp = new RadioProgram(rpso.getName());
rp.setDescription(rpso.getDescription());
ProgramService service = new ProgramService();
return service.searchPrograms(rp);
}
public RadioProgram findRP(String rpName) {
RadioProgram rp = new RadioProgram(rpName);
ProgramService service = new ProgramService();
return (service.searchPrograms(rp)).get(0);
}
public ArrayList<RadioProgram> findAllRP() {
ProgramService service = new ProgramService();
return service.findAllRP();
}
*/
public void processCreate(ProgramSlot ps) {
ScheduleService service = new ScheduleService();
service.processCreate(ps);
}
public void processModify(ProgramSlot ps) {
ScheduleService service = new ScheduleService();
service.processModify(ps);
}
public void processDelete(String name) {
ScheduleService service = new ScheduleService();
service.processDelete(name);
}
public Date getDateValueOfString(String time){
ScheduleService service = new ScheduleService();
return service.getDateValueOfString(time);
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes in an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('home', function () {
// return view('welcome');
return view('template.index');
});
Route::get('about', function () {
// return view('welcome');
return view('template.about');
});
Route::get('look', function () {
// return view('welcome');
return view('template.lookBook');
});
Route::get('features', function () {
// return view('welcome');
return view('template.features');
});
Route::get('pricing', function () {
// return view('welcome');
return view('template.pricing');
});
Route::get('love', function () {
// return view('welcome');
return view('template.loveStories');
});
Route::get('signup', function () {
// return view('welcome');
return view('pages.register');
});
Route::get('home2', function () {
// return view('welcome');
return view('home');
});
Route::get('mainpage','HomeController@index');
Route::get('login','LoginController@login');
Route::get('twitterREST','TwitterController@twitterRest');
//get('twitterRESTApi','TwitterController@twitterRESTApi');
//Route::get('twitterRESTApi','TwitterController@twitterRESTApi');
Route::group(['middleware' => 'auth'], function()
{
Route::get('twitterRESTApi','TwitterController@twitterRESTApi');
//Route::post('edit-data', 'DataController@editData');
});<file_sep>/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package sg.edu.nus.iss.phoenix.presenter.service;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import sg.edu.nus.iss.phoenix.authenticate.dao.UserDao;
import sg.edu.nus.iss.phoenix.authenticate.entity.Role;
import sg.edu.nus.iss.phoenix.authenticate.entity.User;
import sg.edu.nus.iss.phoenix.core.dao.DAOFactory;
import sg.edu.nus.iss.phoenix.core.dao.DAOFactoryImpl;
import sg.edu.nus.iss.phoenix.core.exceptions.NotFoundException;
import sg.edu.nus.iss.phoenix.presenter.entity.Presenter;
import sg.edu.nus.iss.phoenix.utils.RecordDisplay;
/**
*
* @author jiqin
* @author <NAME> ---add comments to prepare javadoc
*/
public class PresenterService {
DAOFactory factory;
UserDao udao;
public DAOFactory getFactory() {
return factory;
}
public void setFactory(DAOFactory factory) {
this.factory = factory;
}
public UserDao getUdao() {
return udao;
}
public void setUdao(UserDao udao) {
this.udao = udao;
}
public static ArrayList<Role> PRESENTER_ROLE;
{
Role role = new Role("presenter");
PRESENTER_ROLE = new ArrayList<>();
PRESENTER_ROLE.add(role);
}
/**
* Constructor of Presenter Service
*
*/
public PresenterService(){
factory = new DAOFactoryImpl();
udao = factory.getUserDAO();
}
/**
* Constructor of Presenter Service with DAOFactory
*
*/
public PresenterService(DAOFactory factory)
{
this.factory = factory;
udao = factory.getUserDAO();
}
/**
* Returns List of Presenter object
* <p>
* This method return Presenter list according to its given criteria
*
* @param example Presenter object
* @param criteria search criteria
* @return List of Presenter object
*
*/
public List<Presenter> findAllPresenters(Presenter example, RecordDisplay criteria){
List<Presenter> presenters = new ArrayList<>();
User user = new User();
user.setId(example.getId());
user.setName(example.getName());
user.setRoles(PRESENTER_ROLE);
try{
List<User> users = udao.searchMatching(user);
if(users!=null){
for(User fuser : users){
presenters.add(new Presenter(fuser.getId(),fuser.getName()));
}
}
}catch(Exception e){
e.printStackTrace();
}
return presenters;
}
/**
* Returns List of all Presenter objects
* <p>
* This method return all Presenter list of Presenter according to its given criteria
*
* @param example Presenter object
* @return List of Presenter
*
*/
public List<Presenter> findAllPresenters(Presenter example) {
return findAllPresenters(example, RecordDisplay.getDefaultCriteria());
}
/**
* Returns Presenter object according to argument id
* <p>
* This method return Presenter object according to its argument id
*
* @param id id of Presenter
* @return Presenter object
*
*/
public Presenter findPresenter(String id){
User user;
try {
try {
user = udao.getObject(id);
if(user !=null){
Presenter presenter = new Presenter();
presenter.setId(user.getId());
presenter.setName(user.getName());
return presenter;
}
} catch (NotFoundException ex) {
Logger.getLogger(PresenterService.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (SQLException ex) {
Logger.getLogger(PresenterService.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
/**
* Returns List of Presenter object
* <p>
* This method return all Presenter object
*
* @return List of Presenters
*
*/
public List<Presenter> findAllPresenters()
{
List<Presenter> presenters = new ArrayList<>();
User user = new User();
user.setId("");
user.setName("");
user.setRoles(PRESENTER_ROLE);
try{
List<User> users = udao.searchMatching(user);
if(users!=null){
for(User fuser : users){
presenters.add(new Presenter(fuser.getId(),fuser.getName()));
}
}
}catch(Exception e){
e.printStackTrace();
}
return presenters;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sg.edu.nus.iss.phoenix.schedule.controller;
import at.nocturne.api.Action;
import at.nocturne.api.Perform;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import sg.edu.nus.iss.phoenix.schedule.delegate.ReviewSelectScheduleDelegate;
import sg.edu.nus.iss.phoenix.schedule.entity.AnnualSchedule;
import sg.edu.nus.iss.phoenix.schedule.entity.ProgramSlot;
import sg.edu.nus.iss.phoenix.schedule.entity.WeeklySchedule;
/**
*
* @author jixiang
*/
@Action("managers")
public class ManageScheduleCmd implements Perform {
@Override
public String perform(String path, HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
ReviewSelectScheduleDelegate del = new ReviewSelectScheduleDelegate();
List<AnnualSchedule> annualScheduleList = del.reviewSelectAnnualSchedule();
List<ProgramSlot> data = getAllProgramSlots(annualScheduleList);
req.setAttribute("rps", data);
return "/pages/crudps.jsp";
}
public List<ProgramSlot> getAllProgramSlots(List<AnnualSchedule> annualList){
List<ProgramSlot> result = new ArrayList<ProgramSlot>();
Iterator<AnnualSchedule> iter = annualList.iterator();
while(iter.hasNext()){
AnnualSchedule annualSchedule = iter.next();
List<WeeklySchedule> weeklyList = annualSchedule.getWeeklySchedule();
Iterator<WeeklySchedule> iter2 = weeklyList.iterator();
while(iter2.hasNext()){
WeeklySchedule weeklySchedule = iter2.next();
List<ProgramSlot> programList = weeklySchedule.getProgramSlotList();
if (programList.size() > 0 ){
result.addAll(programList);
}
}
}
return result;
}
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: jixiang
* Date: 22/10/15
* Time: 9:41 PM
*/
require "../twitteroauth/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;
//namespace Abraham\TwitterOAuth;
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "<KEY>",
'oauth_access_token_secret' => "<KEY>",
'consumer_key' => "<KEY>",
'consumer_secret' => "5LT4EEgkRErSDIDVsMEc0najghfF2hrIdtRO7Vo8kmYV3S657P",
);
$CONSUMER_KEY = "<KEY>";
$CONSUMER_SECRET = "5LT4EEgkRErSDIDVsMEc0najghfF2hrIdtRO7Vo8kmYV3S657P";
$access_token = "<KEY>";
$access_token_secret = "<KEY>";
$connection = new TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET, $access_token, $access_token_secret);
?><file_sep><?php
/**
* Created by PhpStorm.
* User: jixiang
* Date: 8/12/15
* Time: 1:56 PM
*/
namespace App\Http\Controllers;
class HomeController extends Controller{
public function index(){
return view('index');
// return "helloworld";
}
}<file_sep>package sg.edu.nus.iss.phoenix.producer.entity;
import java.io.Serializable;
import java.util.Date;
import sg.edu.nus.iss.phoenix.radioprogram.entity.RadioProgram;
import sg.edu.nus.iss.phoenix.utils.DateFormat;
import java.text.ParseException;
public class Producer implements Cloneable, Serializable {
/**
* eclipse identifier
*/
private static final long serialVersionUID = -5500218812568593553L;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author ADMIN
*/
private String id;
private String name;
public Producer(){
this.id = "";
this.name = "";
}
public Producer(String id){
this.id=id;
this.name = "";
}
public Producer(String id, String name){
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
<file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sg.edu.nus.iss.phoenix.core.dao;
/**
*
* @author jixiang
*/
public class EntityConstants {
//User
public static final String USER_TABLE = "user";
public static final String USER_ID = "id";
public static final String USER_NAME = "name";
public static final String USER_PASSWORD = "<PASSWORD>";
public static final String USER_ROLE = "role";
//Radio Program
public static final String RADIO_PROGRAM_TABLE = "radio-program";
public static final String RADIO_PROGRAM_NAME = "name";
public static final String RADIO_PROGRAM_DESCRIPTION = "desc";
public static final String RADIO_PROGRAM_TYPICAL_DURATION = "typicalDuration";
//Schedule
public static final String SCHEDULE_ANNUAL_TABLE="annual-schedule";
public static final String SCHEDULE_ANNUAL_YEAR = "year";
public static final String SCHEDULE_ANNUAL_ASSIGNED_BY="assignedBy";
public static final String SCHEDULE_WEEKLY_TABLE="weekly-schedule";
public static final String SCHEDULE_WEEKLY_START_DATE="startDate";
public static final String SCHEDULE_WEEKLY_ASSIGNED_BY="assignedBy";
public static final String SCHEDULE_PROGRAM_SLOT_TABLE="program-slot";
public static final String SCHEDULE_PROGRAM_SLOT_DURATION="duration";
public static final String SCHEDULE_PROGRAM_SLOT_DATE_OF_PROGRAM="dateOfProgram";
public static final String SCHEDULE_PROGRAM_SLOT_START_TIME="startTime";
public static final String SCHEDULE_PROGRAM_SLOT_PROGRAM_NAME="program-name";
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: jixiang
* Date: 21/10/15
* Time: 1:11 PM
*/
require "twitter_connection_REST.php";
$response = array();
$content = $connection->get("account/verify_credentials");
$hash_text;
$statuses;
$length_of_tweets = 20;
$result = array();
//build_multiple_hashtag_search("this has a #hashtag a #badhash-tag and a #goodhash_tag");
if (isset ($_GET['hash_text']))
{
$hash_text = $_GET['hash_text'];
$hash_result = build_multiple_hashtag_search($hash_text);
$statuses = $connection->get("search/tweets", array("q" => $hash_result, "until" => "2015-12-07"));
$response["success"] = $hash_text;
build_up_result_array($statuses);
echo send_array();
}
else{
$response["error"] = "can not find hash_text in your get request!";
echo json_encode($response);
}
function build_multiple_hashtag_search($hash_text)
{
$return_value = "";
preg_match_all("/(#\w+)/", $hash_text, $matches);
for ($i = 0; $i < sizeof($matches[0]); $i++) {
if ($i != sizeof($matches[0]) - 1) {
$return_value = $return_value . "%23" . $matches[0][$i] . "+OR+";
} else {
$return_value = $return_value . "%23" . $matches[0][$i];
}
}
return $return_value;
}
//print_r ($statuses->statuses[0]);
//
//print_r("<br>");
function build_up_result_array($statuses)
{
GLOBAL $length_of_tweets;
GLOBAL $result;
for ($i = 0; $i < $length_of_tweets; $i++) {
$result[$i] = $statuses->statuses[$i];
}
}
//print_r($result[4]->text);
function send_array()
{
$response["display"] = array();
GLOBAL $length_of_tweets;
GLOBAL $result;
for ($i = 0; $i < $length_of_tweets; $i++) {
$display = array();
$display["user_img"] = $result[$i]->user->profile_image_url;
$display["username"] = $result[$i]->user->name;
$display["text"] = $result[$i]->text;
// $display["user_img"] = $result[$i]['user']['profile_image_url'];
// $display["username"] = $result[$i]['user']['name'];
// $display["text"] = $result[$i]['text'];
array_push($response["display"], $display);
}
return json_encode($response);
}
<file_sep><?php
/**
* Created by PhpStorm.
* User: jixiang
* Date: 22/10/15
* Time: 9:38 PM
*/
require_once('../phirehose-master/lib/Phirehose.php');
require_once('../phirehose-master/lib/OauthPhirehose.php');
require 'twitter_connection_STREAMING.php';
/**
* Example of using Phirehose to display the 'sample' twitter stream.
*/
class SampleConsumer extends OauthPhirehose
{
/**
* Enqueue each status
*
* @param string $status
*
*
*/
public $response = array();
public function enqueueStatus($status)
{
/*
* In this simple example, we will just display to STDOUT rather than enqueue.
* NOTE: You should NOT be processing tweets at this point in a real application, instead they should be being
* enqueued and processed asyncronously from the collection process.
*/
$data = json_decode($status, true);
if (is_array($data) && isset($data['user']['screen_name'])) {
$this->response['display'] = $data['user']['screen_name'] . ': ' . urldecode($data['text']) . "\n";
//print($data['user']['screen_name'] . ': ' . urldecode($data['text']) . "\n");
echo json_encode( $this->response);
//print($data['user']['screen_name'] . ': ' . urldecode($data['text']) . "\n");
}
}
}
set_time_limit(1);
// Start streaming
$sc = new SampleConsumer(OAUTH_TOKEN, OAUTH_SECRET, Phirehose::METHOD_FILTER);
$sc->setTrack(array('morning', 'goodnight', 'hello', 'the'));
//$sc->consume();
$sc->consume();
?><file_sep>/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sg.edu.nus.iss.phoenix.utils;
import java.util.List;
/**
*
* @author <NAME>
*/
public class RecordDisplay {
private int pageNo = 1;
private int numberPerPage = 10;
private List<String> orders = null;
private static final RecordDisplay defaultCriteria = new RecordDisplay();
public RecordDisplay(){
}
public static RecordDisplay getDefaultCriteria()
{
return defaultCriteria;
}
}
<file_sep>/**
* Created by jixiang on 9/12/15.
*/
var json_data = Object();
$("#protoType_btn").click(function(){
var hash_text = $("#hash_text").val();
$.get(
"/twitterRESTApi",
{ hash_text: hash_text },
function(data) {
alert(data);
$('#stage').html(data);
json_data = JSON.parse(data);
//alert(data);
fill_table(json_data);
}
);
});
//console.log(json_data);
//alert(json_data);
function remove_all_table(){
$('#table').bootstrapTable('removeAll');
}
function fill_table(json_data){
if (json_data.length !== 0){
console.log(json_data['display']);
$('#table').bootstrapTable('load',build_data(json_data));
// $('#table').bootstrapTable({
// columns: [{
// field: 'user_img',
// title: 'user_img'
// }, {
// field: 'username',
// title: 'username'
// }, {
// field: 'text',
// title: 'text'
// }],
// data: json_data['display']
// });
}
}
function build_data(json_data){
data = json_data["display"];
//alert(data.length);
rows = [];
for (var i = 0; i < data.length; i++) {
rows.push({
user_img: data[i]["user_img"],
username: data[i]["username"],
text: data[i]["text"]
});
}
return rows;
}<file_sep>/**
* Created by jixiang on 23/1/16.
*/
$(document).ready(function() {
// This command is used to initialize some elements and make them work properly
$.material.init();
});
<file_sep>package sg.edu.nus.iss.phoenix.schedule.entity;
import java.io.Serializable;
import java.sql.Time;
import java.util.Date;
import java.util.List;
import sg.edu.nus.iss.phoenix.schedule.delegate.ReviewSelectScheduleDelegate;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
/**
*
* @author ADMIN
*/
public class AnnualSchedule implements Cloneable, Serializable {
private static final long serialVersionUID = -5500218812568593553L;
private String assignedBy;
private int year;
private List <WeeklySchedule> weeklyScheduleList;
public AnnualSchedule() {
}
public List<WeeklySchedule> getWeeklySchedule() {
return weeklyScheduleList;
}
public void retriveAllWeeklySchedule() {
ReviewSelectScheduleDelegate del = new ReviewSelectScheduleDelegate();
weeklyScheduleList = del.reviewSelectWeeklySchedule();
}
public String getAssignedBy() {
return assignedBy;
}
public void setAssignedBy(String assignedBy) {
this.assignedBy = assignedBy;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
<file_sep>package sg.edu.nus.iss.phoenix.schedule.service;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import sg.edu.nus.iss.phoenix.core.dao.DAOFactoryImpl;
import sg.edu.nus.iss.phoenix.core.exceptions.NotFoundException;
import sg.edu.nus.iss.phoenix.schedule.dao.ScheduleDAO;
import sg.edu.nus.iss.phoenix.schedule.entity.ProgramSlot;
public class ScheduleService {
DAOFactoryImpl factory;
ScheduleDAO psDAO;
public ScheduleService() {
super();
// TODO Auto-generated constructor stub
factory = new DAOFactoryImpl();
psDAO = factory.getScheduleDAO();
}
/*
public ArrayList<RadioProgram> searchPrograms(RadioProgram rpso) {
ArrayList<RadioProgram> list = new ArrayList<RadioProgram>();
try {
list = (ArrayList<RadioProgram>) rpdao.searchMatching(rpso);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return list;
}
public ArrayList<RadioProgram> findRPByCriteria(RadioProgram rp) {
ArrayList<RadioProgram> currentList = new ArrayList<RadioProgram>();
try {
currentList = (ArrayList<RadioProgram>) rpdao.searchMatching(rp);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return currentList;
}
public RadioProgram findRP(String rpName) {
RadioProgram currentrp = new RadioProgram();
currentrp.setName(rpName);
try {
currentrp = ((ArrayList<RadioProgram>) rpdao
.searchMatching(currentrp)).get(0);
return currentrp;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return currentrp;
}
public ArrayList<RadioProgram> findAllRP() {
ArrayList<RadioProgram> currentList = new ArrayList<RadioProgram>();
try {
currentList = (ArrayList<RadioProgram>) rpdao.loadAll();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return currentList;
}
*/
public void processCreate(ProgramSlot ps) {
try {
psDAO.create(ps);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void processModify(ProgramSlot ps) {
try {
psDAO.save(ps);
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void processDelete(String name) {
try {
ProgramSlot rp = new ProgramSlot(); // Take care of this
psDAO.delete(rp);
} catch (NotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Date getDateValueOfString(String time){
Date date = null;
String dateString = "01-01-50:"+time+":00";
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd-MM-yy:HH:mm:SS");
try{
date = DATE_FORMAT.parse(dateString);
}catch(Exception e){
e.printStackTrace();
}
return date;
}
}
|
ee773460f70edc9865b6c6b296323f964548c67d
|
[
"JavaScript",
"Java",
"PHP"
] | 22 |
PHP
|
ljx213101212/PRMS1
|
90636ae4b31179bb459ba3cb2f5f1091154ddeda
|
9885a0c9f0f6e8fa4cba2b6e786b73dba2572248
|
refs/heads/master
|
<repo_name>nikita-kazakov/Pragmatic-Ruby-Game<file_sep>/README.md
# Pragmatic-Ruby-Game
This is the Ruby Game from Pragmatic Studio Ruby Course.
Completed By: <NAME>
This is the Ruby Game from Pragmatic Studio Ruby Course (https://online.pragmaticstudio.com/courses/ruby)
Further description here...<file_sep>/studio_game/lib/game_turn.rb
module StudioGame
module GameTurn
def self.die_roll
rand(1..6)
end
def self.take_turn(player)
number_rolled = die_roll
case number_rolled
when 5..6
player.w00t
when 3..4
puts "#{player.name} got skipped"
when 1..2
player.blam
end
treasure = TreasureTrove.random
player.found_treasure(treasure)
#puts "#{player.name} found a #{treasure.name} worth #{treasure.points} points."
end
end
end
<file_sep>/movieApp/lib/flicks/snackbar.rb
module Flicks
Snack = Struct.new(:name, :carbs)
module Snackbar
SNACKS = [
Snack.new(:popcorn, 20),
Snack.new(:candy, 15),
Snack.new(:nachos, 40),
Snack.new(:pretzels, 10),
Snack.new(:soda, 5)
]
def self.random
SNACKS.sample
end
end
end
#Sample Code
if __FILE__ == $0
puts Flicks::Snackbar.random
snack = Flicks::Snackbar.random
puts "Enjoy your #{snack.name} (#{snack.carbs} carbs)"
end
<file_sep>/chris pines refresher/practice.rb
=begin
numBottles = 99
while numBottles > 2
puts "#{numBottles} bottles of beer on the wall. #{numBottles} bottles of beer."
puts "Take one down, pass it around. \n#{numBottles - 1} bottles of beer on the wall."
numBottles -= 1
end
puts "#{numBottles} bottle of beer on the wall. #{numBottles} bottle of beer."
puts "Take one down, pass it around. \n#{numBottles} bottle of beer on the wall."
numBottles -= 1
puts "No more bottles of beer on the wall, no more bottles of beer."
puts "Go to the store and buy some more, 99 bottles of beer on the wall."
puts"\n\n\n"
numbers = [1,2,3,4]
puts numbers
numbers = (1..10)
print numbers.to_a
puts "\n\n"
puts numbers.select{|n| n > 5}
numbers.select do |number|
number < 5
end
evens = numbers.select{|num| num.even?}
print evens
puts "\n"
odds = numbers.reject{|num| num.even?}
print odds
#evens, odds = numbers.partition {|num| num.evens?}
#You can also partition and split into 2 variables AFTERWARDS:
part_array = numbers.partition{|num| num.even?}
print part_array
evens = part_array[0]
odds = part_array[1]
puts "\n"
print evens
print odds
puts "\n\n"
#Let's use the reduce method to sum up the array
array = (1..5).to_a
print array
puts array.reduce{|sum, n| sum + n}
puts array.reduce{|product, n| product * n}
names = ["Goonies", "Ghostbusters", "Goldfinger", "Godfather"]
#Alphabetical order sorting
print names.sort
print"\n\n"
#Sort by:
print names.sort_by{|name| name.length}
#Practice iterators
array = [24,13,8,65]
newArray = array.select {|num|num>20 }
print newArray
newArray = array.reject {|num|num>20 }
print newArray
puts "\n\n"
newArray = array.sort
puts newArray
puts "\n\n"
newArray = array.sort.reverse
print newArray
puts "\n\n"
newArray = array.reduce{|sum,n| sum + n}
print newArray
evens, odds = array.partition {|num|num.even? }
puts "\n\n"
print evens, odds
puts "\n\n"
array = ["bobby", "alpha", "shazzball", "dickerson"]
print array
newArray = array.sort
print newArray
newArray = array.sort_by{|item|item.length}.reverse
print newArray
puts "\n\n\n\n"
#Structs
Snack = Struct.new(:name, :carbs)
popcorn = Snack.new("popcorn", 20)
candy = Snack.new("candy", 15)
puts "\n\n\n\n"
#Hashes
#old way of writing before Ruby 1.9
#snack_carbs = {
# :candy => 15,
# :pretzel => 10
#}
#New way of writing hashes (greater than Ruby 1.9)
snack_carbs = {
candy: 30,
pretzel: 100
}
puts snack_carbs[:candy]
snack_carbs[:candy] = 15
puts snack_carbs[:candy]
print snack_carbs.keys
print snack_carbs.values
puts""
snack_carbs.each do |key, value|
puts "#{key} has #{value} carbs"
end
puts"\n\n"
snack_carbs = {}
snack_carbs[:candy] = 15
snack_carbs[:candy] += 15
puts snack_carbs[:candy]
#snack_carbs[:surge] += 10
snack_carbs = Hash.new(0)
snack_carbs[:bread] += 15
p snack_carbs
#Hashes
moes_treasures = {
:hammer => 100,
:crowbar => 500
}
puts moes_treasures
moes_treasures.each { |key, value| puts "Moe has a #{key} that's worth #{value}" }
hash_arr = moes_treasures.keys
print hash_arr
hash_arr = moes_treasures.values
print hash_arr
puts "\n\n"
#So if we wanted to sum up the values of all the keys, we'd run this.
#In the parenthesis, is the initial value....(zero)
#Then you have the sum...for the entire block, and each part that's going to get added up.
sum1 = moes_treasures.values.reduce(0){ |sum, n| sum + n }
# can also write it with a symbol
sum2= moes_treasures.values.reduce(0, :-)
puts sum2
#You can also use INJECT...which is exactly same as reduce.
sum3 = moes_treasures.values.reduce{|sum, n| sum + n}
puts sum3
puts "\n\n\n\n\n"
=end
#Scrabble Game
#
=begin
letters = {
"c" => 3,
"e" => 1,
"l" => 1,
"n" => 1,
"t" => 1,
"x" => 8,
"y" => 4
}
score = Hash.new(0)
word = "cell".each_char
word.each do |char|
letters.each { |key, value|
if char == key
score[key] += value
end
}
end
score.each do |key, value|
puts "#{key} : #{value}"
end
#Custom Iterators
def once
puts "Before Yield"
yield
puts "After Yield"
end
once {puts "Running Block"}
def three_times
yield(1)
yield(2)
end
three_times {|number| puts "This is number #{number}"}
def compute
puts yield
end
numbers = (1..10).to_a
####Let's make the array give even numbers only:
numbers = (1..10).to_a
numbers.select {|num|num.even? }
#But now, let's implement this "SELECT" method ourselves!
def my_select(array)
results = []
array.each do |element|
results << element if yield(element)
end
results
end
puts my_select(numbers) {|n|n.even?}
def conversation
puts "Hello"
yield
puts "Goodbye"
end
conversation {puts "Good to meet you!"}
def five_times
yield 1
yield 2
end
five_times do |n|
puts "#{n} situps"
puts "#{n} pushups"
puts "#{n} chinups"
end
#INPUT OUTPUT
# Opening Files
File.open("/home/osboxes/RubymineProjects/Pragmatic-Ruby-Game/chris pines refresher/movies.csv") do |file|
file.each_line do |line|
puts line
end
end
#use readlines method instead...it runs a block and puts each line into an array that you can then print.
File.readlines("/home/osboxes/RubymineProjects/Pragmatic-Ruby-Game/chris pines refresher/movies.csv").each do |line|
print line
end
puts "\n\n\n"
#use readlines method instead...it runs a block and puts each line into an array that you can then print.
# Make sure to require the movie object at the top of this file..
File.readlines("/home/osboxes/RubymineProjects/Pragmatic-Ruby-Game/chris pines refresher/movies.csv").each do |line|
title, rank = line.split(",")
movie = Movie.new(title, rank.to_i)
puts movie
end
=end
#Practice
numbers = [1,2,3,4]
print numbers
numbers.select {|even| puts even.even? }
numbers = [1,2,3,4]
#puts numbers
numbers = (1..20).to_a
puts numbers.select{|number| number.odd? }
#numbers = (1..10)
#print numbers.to_a
#puts "\n\n"
#puts numbers.select{|n| n > 5}
#numbers.select do |number|
# number < 5
#end
evens = numbers.select{|num| num.even?}
print evens
#puts "\n"
puts numbers.reverse
puts numbers.reject{|num| num.even?}
#odds = numbers.reject{|num| num.even?}
#print odds
#evens, odds = numbers.partition {|num| num.evens?}
#You can also partition and split into 2 variables AFTERWARDS:
#part_array = numbers.partition{|num| num.even?}
#print part_array
#evens = part_array[0]
#odds = part_array[1]
#puts "\n"
#print evens
#print odds
#puts "\n\n"
#Let's use the reduce method to sum up the array
#array = (1..5).to_a
#print array
#puts array.reduce{|sum, n| sum + n}
#puts array.reduce{|product, n| product * n}
#Writing a Factorial the Ruby WAY.
numbers = (1..5).to_a
puts numbers.reduce{|sum, num| sum * num}
puts numbers.select! {|num| num < 4 }
puts numbers
puts numbers.any?
numbers.each {|num| puts num + 5 }
numbers.map!{|num| num + 10}
print numbers
puts "\n\n\n\n\n"
names = ["Goonies", "Ghostbusters", "Goldfinger", "Godfather"]
#Alphabetical order sorting
print names.sort
print"\n\n"
#Sort by:
print names.sort_by{|name| name.length}
puts "\n\n\n"
def sort_desc(array)
array.sort_by!{|arr| arr.length}
array.reverse!
end
print sort_desc(names)
puts "\n\n\n\n\n\n\n\n\n\n"
#Structs and Hashes
Snack = Struct.new(:name, :carbs)
popcorn = Snack.new("popcorn", 20)
candy = Snack.new("candy", 15)
Scores = Struct.new(:name, :score)
jack = Scores.new("jack", 20)
susan = Scores.new("Susan", 50)
players = []
players << jack
players << susan
players.each do |player|
puts "****Player****"
puts player.name
puts player.score
end
puts "\n\n\n\n"
#Hashes
#old way of writing before Ruby 1.9
#snack_carbs = {
# :candy => 15,
# :pretzel => 10
#}
scores = {
:jack => 20,
:susan => 25
}
print scores
#New way of writing hashes (greater than Ruby 1.9)
#snack_carbs = {
# candy: 30,
# pretzel: 100
#}
puts "\n\n\n"
puts scores[:jack]
puts scores[:susan]
scores.each do |k,v|
puts "#{k} has #{v} points"
end
#puts snack_carbs[:candy]
#snack_carbs[:candy] = 15
#puts snack_carbs[:candy]
puts scores.keys
puts scores.values
puts scores.values.reduce{|sum, n| sum + n}
print scores.keys.to_a.to_s
puts scores.keys
puts scores.values
puts scores.values.reduce{|sum, n| sum + n}
scores[:jack] += 15
scores[:jack] = scores[:jack] + 15
puts scores
#MAP returns a NEW array with the results. That's why I'm referencing it to a new variable (mult_scores)
mult_scores = scores.map do |k,v|
v + 100
end
puts mult_scores
puts "\n\n\n"
print scores.values.reduce{|sum, n| sum + n}
=begin
print snack_carbs.keys
print snack_carbs.values
puts""
snack_carbs.each do |key, value|
puts "#{key} has #{value} carbs"
end
puts"\n\n"
snack_carbs = {}
snack_carbs[:candy] = 15
snack_carbs[:candy] += 15
puts snack_carbs[:candy]
#snack_carbs[:surge] += 10
snack_carbs = Hash.new(0)
snack_carbs[:bread] += 15
p snack_carbs
#Hashes
moes_treasures = {
:hammer => 100,
:crowbar => 500
}
puts moes_treasures
moes_treasures.each { |key, value| puts "Moe has a #{key} that's worth #{value}" }
hash_arr = moes_treasures.keys
print hash_arr
hash_arr = moes_treasures.values
print hash_arr
puts "\n\n"
#So if we wanted to sum up the values of all the keys, we'd run this.
#In the parenthesis, is the initial value....(zero)
#Then you have the sum...for the entire block, and each part that's going to get added up.
sum1 = moes_treasures.values.reduce(0){ |sum, n| sum + n }
# can also write it with a symbol
sum2= moes_treasures.values.reduce(0, :-)
puts sum2
#You can also use INJECT...which is exactly same as reduce.
sum3 = moes_treasures.values.reduce{|sum, n| sum + n}
puts sum3
puts "\n\n\n\n\n"
=end
puts "\n\n\n\n\n"
class Car
attr_reader :name
attr_writer :name
def initialize(name = "default name")
@name = name
@points = 0
end
def self.description
puts "I'm a car class."
end
#def name
# @name
#end
#def name=(name)
# @name = name
#end
def level_up
@points += 1
end
end
class Honda < Car
end
honda = Car.new
puts honda
puts honda.name
honda.name="I'm Honda"
puts honda.name
honda.level_up
honda.level_up
puts honda.inspect
Car.description
puts "\n\n\n"
puts Car.ancestors
puts Honda.description
module Items
class Books
def self.description
puts "I'm the books factory"
end
end
end
class Hardbound < Items::Books
end
class Books #FROM ANOTHER CLASS. Will Overwrite.
def self.description
puts "I'm overwriting your description"
end
end
puts Hardbound.description
puts Hardbound.description
randhash = {
abc: 'hello',
'another_key' => 123,
4567 => 'third'
}
print randhash.keys.collect(&:to_s).sort_by { |key| key.length }
print randhash.keys.map{|key| key.to_s}.sort_by{|key| key.length}
def times_two(arg1);
puts arg1 * 2;
end
def sum(arg1, arg2);
puts arg1 + arg2;
end
sum 1, 2
book = :book
string = "Sleeps"
puts book.object_id
puts string.object_id<file_sep>/movieApp/lib/flicks/movie3d.rb
require_relative 'movie'
module Flicks
class Movie3D < Movie
def initialize(title, rank, wow_factor)
super title, rank
@wow_factor = wow_factor
end
def show_effect
puts "Wow! " * @wow_factor
end
def thumbs_up
@wow_factor.times{super}
end
end
end
if __FILE__ == $0
movie3d = Flicks::Movie3D.new("End of World 3D", 5, 55)
puts movie3d
p movie3d.class.ancestors
movie3d.show_effect
p movie3d.rank
p movie3d.thumbs_up
movie3d.show_effect
p movie3d.rank
end
<file_sep>/movieApp/trash/movie_spec.rb
require_relative 'lib/movie'
#To Run, type in terminal: rspec movie_rspec.rb --color
#To Run with Documentation: Rspec movie_rspec.rb --color --format documentation
#Testing Movie class
describe Movie do
end
#Inside of it, you will type in: it-do for each test
describe Movie do
#This before do is like initialize in a class! You create instance variables
#and you use them in the it do blocks(like methods of a class)
before do
movie = Movie.new("goonies", 10)
@movie = movie
@initial_rank = movie.rank
end
it 'has a capitalized title' do
@movie.title.should == "Goonies"
end
it 'has an Initial Rank' do
@movie.rank.should == 10
end
it 'has a string representation' do
@movie.to_s.should == "Goonies has a rank of 10 (Hit)"
end
it 'increases rank by 1 when thumbs up' do
@movie.thumbs_up.should == @initial_rank + 1
end
it 'decreases rank by 1 when given a thumbs down' do
@movie.thumbs_down.should == @initial_rank - 1
end
context "created with a default rank" do
before do
@movie = Movie.new('goonies')
end
it 'has a rank of 0' do
@movie.rank.should == 0
end
end
context 'with a rank of at least 10' do
before do
@movie = Movie.new('goonies', 10)
end
it 'is a hit' do
#Question marks return a boolean true or false
@movie.hit?.should == true
#Another way to write this:
#@movie.should be_hit
end
it "has a hit status" do
@movie.status.should == "Hit"
end
end
context 'with a rank of less than 10' do
before do
@movie = Movie.new('goonies', 9)
end
it 'is not a hit' do
@movie.hit?.should == false
#another way to write this in Rspec is:
#@movie.hit?.should be_false
end
it 'has a flop status' do
@movie.status.should == "Flop"
end
end
end<file_sep>/studio_game/bin/studio_game.rb
require_relative '../lib/player'
require_relative '../lib/game'
require_relative '../lib/clumsy_player'
require_relative '../lib/berserk_player'
player1 = StudioGame::Player.new("Moe", 100)
player2 = StudioGame::Player.new("Larry", 60)
player3 = StudioGame::Player.new("Curly", 125)
player4 = StudioGame::Player.new("Shemp", 90)
player5 = StudioGame::ClumsyPlayer.new("ClumsyDude", 90)
player6 = StudioGame::BerserkPlayer.new("Berserk", 100)
knuckleheads = StudioGame::Game.new("Knuckleheads")
knuckleheads.load_players(ARGV.shift || "/home/osboxes/RubymineProjects/Pragmatic-Ruby-Game/studio_game/bin/players.csv")
knuckleheads.add_player(player1)
knuckleheads.add_player(player2)
knuckleheads.add_player(player3)
knuckleheads.add_player(player4)
knuckleheads.add_player(player5)
knuckleheads.add_player(player6)
loop do
puts "How many rounds? ('quit' to exit)"
answer = gets.chomp.downcase
case answer
when /^\d+$/
knuckleheads.play(answer.to_i)
when 'quit', 'exit'
break
else
puts "Please enter a number or 'quit'"
end
end
#knuckleheads.add_player(player1)
#knuckleheads.add_player(player2)
#knuckleheads.add_player(player3)
#knuckleheads.play
#gameChipmunks = Game.new("chipmunks")
#gameChipmunks.addPlayerTest
#gameChipmunks.play<file_sep>/chris pines refresher/01 - Strings.rb
#This is a Ruby refresher from <NAME> - Learn to Program Book
# https://pine.fm/LearnToProgram
#
#puts and gets
#puts stands for PUT STRING. gets is GET STRING.
puts "Hello my friend. What's your name?"
name = gets.chomp
puts "Your name is " + name + ". It's a pleasure"
#chomp is used to get rid of a break line that gets automatically generates.
# Let's look at some string methods.
word = "AbraCadaBra"
puts word.upcase<file_sep>/studio_game/README.md
##Studio Game - Nikita Version<file_sep>/studio_game/trash/irb testing.rb
#Chapter 4 - Variables and Objects
fav_movie = "Total Recall"
my_fav_movie = fav_movie
your_fav_movie = my_fav_movie
puts my_fav_movie.object_id
puts your_fav_movie.object_id
my_fav_movie[0] = "L"
puts my_fav_movie
puts your_fav_movie
puts ""
rank = 16
puts 16.*(2)
movie_name = "goonies"
puts movie_name.start_with?("g")
puts movie_name.include?("x")
puts movie_name.reverse!<file_sep>/movieApp/lib/flicks/playlist.rb
require_relative 'playlist'
require_relative 'movie'
require_relative 'waldorf_and_statler'
require_relative 'snackbar'
module Flicks
class Playlist
attr_reader :name
def initialize(name)
@name = name
@movies = []
end
def load(from_file)
File.readlines(from_file).each do |line|
add_movie(Movie.from_csv(line))
end
end
def save(to_file = "movie_rankings.csv")
File.open(to_file, "w") do |file|
@movies.sort.each do |movie|
file.puts movie.to_csv
end
end
end
def add_movie(a_movie)
@movies << a_movie
end
def play(viewings)
snacks = Snackbar::SNACKS
puts "There are #{snacks.size} snacks available:"
snacks.each do |snack|
puts "#{snack.name} has #{snack.carbs} carbs."
end
puts "\n#{@name}'s playlist:"
puts @movies.sort
1.upto(viewings) do |count|
puts "\n******Viewing # #{count}******"
@movies.each do |movie|
WaldorfAndStatler.review(movie)
snack = Snackbar.random
movie.ate_snack(snack)
puts movie
end
end
end
def total_carbs_consumed
@movies.reduce(0) do |sum, movie|
sum + movie.carbs_consumed
end
end
def print_stats
puts "#{total_carbs_consumed} total carbs consumed"
@movies.sort.each do |movie|
puts "#{movie.title}'s snack totals:"
movie.each_snack do |snack|
puts "#{snack.carbs} total #{snack.name} carbs."
end
puts "#{movie.carbs_consumed} grand total carbs."
end
puts "\n****#{@name}'s Stats:****"
hits, flops = @movies.partition {|movie| movie.hit?}
puts "\nHits"
puts hits.sort
puts "\nFlops"
puts flops.sort
end
end
end
#sample code
if __FILE__ == $0
movie1 = Movie.new("Die Hard", 10)
movie2 = Movie.new("Beetlejuice", 10)
movie3 = Movie.new("Animaniacs", 10)
playlist = FlicksModule::Playlist.new("bobsPlaylist")
playlist.add_movie(movie1)
playlist.add_movie(movie2)
playlist.add_movie(movie3)
playlist.play(3)
playlist.print_stats
end
<file_sep>/studio_game/trash/studio_game_chapter4.rb
#Chapter 3 Numbers and Strings
name1 = "larry"
name2 = "curly"
name3 = "moe"
health1 = 60
health2 = 125
health3 = 100
puts 'larry\'s health is ' + health1.to_s
puts "#{name1}'s health is #{health1}"
puts "#{name1}'s health is #{health1 * 3}"
puts "#{name1}'s health is #{health1 / 9.0}"
puts "Players: \n\tlarry\n\tcurly\n\tmoe"
puts "Players: \n\t#{name1}\n\t#{name2}\n\t#{name3}"
puts "\n\n\n"
puts "#{name1.capitalize} has a health of #{health1}"
puts "#{name2.upcase} has a health of #{health2}"
puts "#{name3} has a health of #{health3}".center(50, "*")
time_start = Time.new
puts time_start.strftime("The game started on %A %d/%m/%Y at %H:%M%p")
puts self
self.class
puts "\n\n\n******************************"
#Chapter 4 - Methods
def time_now
time_now = Time.new
time_now.strftime("%B")
end
def say_hello(name, health = 100)
"I'm #{name.capitalize} with a health of #{health} as of #{time_now}"
end
puts say_hello("larry", 60)
puts say_hello("curly", 125)
puts say_hello("moe")
puts say_hello("shemp", 90)
<file_sep>/studio_game/spec/player_spec.rb
require_relative '../lib/player'
module StudioGame
describe Player do
before do
@player = Player.new("diehard", 10)
@health = @player.health
end
it 'has a capitalized name' do
@player.name.should == "Diehard"
end
it "has an initial health of" do
@player.health.should == 10
end
it "computes a score as the sum of it's health and length of name" do
@player.score == 107
end
it "increases health by 15 when wooted" do
@player.w00t
@player.health.should == 25
end
it "decreases health by 10 when blammed" do
@player.blam
@player.health.should == 0
end
end
end
<file_sep>/studio_game/lib/game_spec.rb
require_relative 'game'
describe Game do
before do
@player = Player.new("jack")
@game = Game.new("Street Fighter")
end
context 'play method'do
it 'calls one parameter' do
end
end
end<file_sep>/chris pines refresher/04 - Classes and Methods.rb
class Account
attr_accessor :name, :balance
def initialize(name, balance)
@name = name
@balance = balance
end
def deposit(amount)
@balance = @balance + amount
end
def TakeFrom(person, amount)
person.balance = person.balance - amount
self.balance = self.balance + amount
puts "#{self.name} took #{amount} from #{person.name}. #{person.name} now has a balance of #{person.balance}. #{self.name} has a balance of #{self.balance}"
end
end
bob = Account.new("Bob", 100)
jill = Account.new("Jill", 100)
puts jill.TakeFrom(bob,50)
puts jill.TakeFrom(bob,50)
<file_sep>/movieApp/lib/flicks/movie.rb
require_relative 'rankable'
module Flicks
class Movie
include Rankable
attr_reader :title, :rank
attr_accessor :rank
def initialize(title, rank=0)
@title = title.capitalize
@rank = rank
@snack_carbs = Hash.new(0)
end
def self.from_csv(line)
title, rank = line.split(",")
Movie.new(title, rank.to_i)
end
def to_csv
"#{title},#{rank}"
end
def each_snack
@snack_carbs.each do |name, carbs|
snack = Snack.new(name, carbs)
yield snack
end
end
def carbs_consumed
@snack_carbs.values.reduce(0, :+)
end
def ate_snack(snack)
@snack_carbs[snack.name] += snack.carbs
puts "#{@title} led to #{snack.carbs} #{snack.name} carbs being consumed."
puts "#{@title}'s snacks: #{@snack_carbs}'"
end
def listing
"#{@title} has a rank of #{@rank}"
end
def to_s
"#{title} has a rank of #{rank} (#{status})"
end
end
end
#Sample code
if __FILE__ == $0
movie = Movie.new("goonies", 5)
puts movie.title
3.times{puts "hi"}
10.upto(20) do |number|
puts "#{number} - bye"
end
end<file_sep>/chris pines refresher/06 - myCar.rb
#This exercise is an adaption from launchschool.com
# https://launchschool.com/books/oo_ruby/read/classes_and_objects_part1
class MyCar
def initialize(year, color, model)
@year = year
@color = color
@model = model
@speed = 0
@ignition = 0
end
#write getters
def yearGet
@year
end
def colorGet
@color
end
def modelGet
@model
end
def speedGet
@speed
end
def ignitionGet
@ignition
end
#write setters
def colorSet=(value)
@color = value
end
def modelSet=(value)
@model = value
end
def speedSet=(value)
@speed = value
end
def ignitionSet=(value)
@ignition = value
end
#Realize that I could have skipped writing the getters and the setters and simply put down:
#attr_accessor :model, :color, :year
#This one little line would generate a getter and setter for model, color, and year.
#I'm not using it to continue furthering my basic education of ruby.
#Car Methods below
def speedIncrease(value)
self.speedSet = self.speedGet + value
end
def speedDecrease(value)
self.speedSet = self.speedGet - value
end
def ignitionOff
if self.ignitionGet == 1
puts "Your car has now been turned off. ignitionGet = #{self.ignitionGet}"
self.ignitionSet = 0
else
puts "Your car is already OFF! ignitionGet = #{self.ignitionGet}"
end
end
def ignitionOn
if self.ignitionGet == 0
self.ignitionSet = 1
puts "vroom vroom. Your car just turned on. ignitionGet = #{self.ignitionGet}"
else
puts "Your car is already ON! ignitionGet = #{self.ignitionGet}"
end
end
def sprayPaint(value)
self.colorSet = value
end
#ADDING A CLASS METHOD to calculate gas mileage
#It's special because it works on the class object itself without you having to instantiate an object first.
def self.gas_mileage(gallons, miles)
puts "You get #{miles / gallons} miles per gallon"
end
end
ford = MyCar.new(2007, "black", "mustang")
puts ford.speedGet
puts ford.speedIncrease(20)
puts ford.speedIncrease(20)
puts ford.speedDecrease(10)
puts ford.ignitionOff
puts ford.ignitionOn
puts ford.ignitionOn
puts ford.ignitionOn
puts ford.ignitionOff
puts ford.ignitionOff
puts "\n\n\n"
puts ford.colorSet = "red"
puts ford.colorGet
puts "\n\n\n"
puts ford.colorGet
puts ford.sprayPaint("blue")
puts ford.colorGet
puts "\n\n"
inspectstring = ford.inspect.to_s
inspectarray = inspectstring.split("@").to_a
print inspectarray.drop(1)
puts"\n\n"
MyCar.gas_mileage(10,30)
puts "\n\n\n*****************\n"
class Person
attr_reader :name
attr_writer :name
def initialize(name)
@name = name
end
end
bob = Person.new("Steve")
bob.name = "Bob"
puts bob.name<file_sep>/chris pines refresher/02 - Strings.rb
#This is a Ruby refresher from <NAME> - Learn to Program Book
#https://pine.fm/LearnToProgram
word = "AbraCadabra"
#In RubyMine, Hover over any method and press Ctrl + Q. It will give you quick documentation.
puts word.upcase
puts word.downcase
puts word.swapcase
puts word.capitalize
#Justification
puts "Table of Contents \n".center(70)
puts "Chapter 1: Getting Started ljustify".ljust(60," ") + "page 1"
puts "Chapter 2: More space ljustify".ljust(60," ") + "page 1"
puts "Chapter 3: More space I said okay ljustify?".ljust(60," ") + "page 1"
#there's also rjustify.
puts ""
puts "Table of Contents #2".center(70)
puts "The Adventurs of Baggles".rjust(40, "-")
#numbers
puts ""
puts (5-2)
puts (2-6).abs
puts 5**2
puts 7/3
puts (7.0 / 3).round(2)
puts 7.modulo(3)
puts 7%3
puts rand(500)
puts rand(20..50)
puts ""
puts Math::E
puts Math::PI
puts Math.sin(90)
puts "\n\nLet's do word stuff"
puts "aander" < "bug"
puts "aander" == "bug"
puts""
#However capital letters always come BEFORE lowercase!!!
puts "aander" < "Bug"
#So to truly compare this, let's downcase all letters.
puts "aander".downcase < "bug".downcase
<file_sep>/movieApp/spec/flicks/snack_bar_spec.rb
require 'flicks/snackbar'
module Flicks
describe Snack do
before do
@snack = Snack.new(:pretzel, 10)
end
it "has a name attribute" do
@snack.name.should == :pretzel
end
it "has a carbs attribute" do
@snack.carbs.should == 10
end
end
end
<file_sep>/chris pines refresher/05 - Person Bank.rb
class Account
#initialize method to create the @amount instance variable
# We define amount initial value to $100
def initialize(name ,amount)
@name = name
@amount = amount
puts "I'm #{nameGet} with an initial amount of $#{amountGet}."
end
#this is a getter method
def amountGet
@amount
end
#this is a setter method
def amountSet=(value)
@amount = value
end
#name getter method
def nameGet
@name
end
#This method adds money
def moneyGiveTo(amountGiven,recipientName)
puts "***Start moneyGiveTo method***"
puts "#{self.nameGet} has $#{self.amountGet}."
puts "#{self.nameGet} gives #{amountGiven} to #{recipientName.nameGet}"
self.amountSet = self.amountGet - amountGiven
recipientName.amountSet = recipientName.amountGet + amountGiven
end
end
bob = Account.new("bob", 100)
sally = Account.new("sally", 100)
puts ""
puts ""
bob.moneyGiveTo(50, sally)
puts""
puts "#{bob.nameGet} now has #{bob.amountGet}"
puts "#{sally.nameGet} now has #{sally.amountGet}"
puts""
bob.moneyGiveTo(30, sally)
puts""
puts "#{bob.nameGet} now has #{bob.amountGet}"
puts "#{sally.nameGet} now has #{sally.amountGet}"
puts""
bob.moneyGiveTo(40, sally)
puts""
puts "#{bob.nameGet} now has #{bob.amountGet}"
puts "#{sally.nameGet} now has #{sally.amountGet}"
puts""
sally.moneyGiveTo(100, bob)
puts""
puts "#{bob.nameGet} now has #{bob.amountGet}"
puts "#{sally.nameGet} now has #{sally.amountGet}"
puts"\n*********\n\n\n"
#This is written so that I can use this in my tutorials
class Person
def initialize(name, amount)
@name = name
@amount = amount
end
def nameGet
@name
end
end
sally = Person.new("sally", 100)
puts sally.nameGet<file_sep>/chris pines refresher/03 - Loops Blocks.rb
#This is a Ruby refresher from <NAME> - Learn to Program Book
#https://pine.fm/LearnToProgram
#Let's look at loops
#if statement
if "apple" < "bananna"
puts "Yep"
else
puts "nope"
end
#Looping
input = ""
#while input != "bye"
# puts input
# input = gets.chomp
#end
puts 'come again soon'
#Arrays
puts ""
myLanguages = ['russian', 'english', 'spanish', 'french']
myLanguages.each do |lang|
puts "I speak " + lang
end
3.times do
puts "Hi 3 times!"
end
puts ""
myList = ["first", "second", "third"]
print "size of list: #{myList}"
print myList.concat(["four"])
puts ""
puts myList.first(2)
puts myList.last(2).reverse
puts ""
puts myList
puts""
puts myList.push("five", "six", "seven", "eight")
puts""
puts myList.pop(2)
def mult(num1, num2)
puts num1 * num2
end
mult(5,4)<file_sep>/movieApp/trash/files.rb
file = File.open("/home/osboxes/RubymineProjects/Pragmatic-Ruby-Game/movieApp/movies.csv")
puts file.size #File size in bytes
array = []
#read file
file.each_line do |line|
array << line
end
file.close # but you have to remember to call CLOSE on file...To difficult to remember.
#Instead let's use a block.
#At first we just open the file...do anything inside of it.
File.open("/home/osboxes/RubymineProjects/Pragmatic-Ruby-Game/movieApp/movies.csv") do |file|
end
#Now we scan each line of the file and print it.
File.open("/home/osboxes/RubymineProjects/Pragmatic-Ruby-Game/movieApp/movies.csv") do |file|
file.each_line do |line|
puts line
end
end
#Dude, make it easier and call the readlines method instead. It will read each line and store it in an ARRAY.
#Viola! No need to close the file either here.
array = File.readlines("/home/osboxes/RubymineProjects/Pragmatic-Ruby-Game/movieApp/movies.csv")
p array
require_relative '../lib/movie'
File.readlines("/home/osboxes/RubymineProjects/Pragmatic-Ruby-Game/movieApp/movies.csv").each do |line |
title, rank = line.split(",")
movie = Movie.new(title,rank.to_i)
puts movie
end
puts "\n\n\n"
#Let's take a look at how to SAVE things to a csv file.
movie1 = Movie.new("goonies", 10)
movie2 = Movie.new("ghostbusters", 9)
movie3 = Movie.new("goldfinger", 7)
movie4 = Movie.new("gremlins", 15)
movies = [movie1, movie2, movie3, movie4]
movie_write_path = "/home/osboxes/RubymineProjects/Pragmatic-Ruby-Game/movieApp/movie_rankings.csv"
File.open(movie_write_path, "w") do |file|
end
#Let's now run an enumerable on that movie array and
#puts whatever we need to delimited by commas
File.open(movie_write_path, "w") do |file|
movies.sort.each do |movie|
file.puts "#{movie.title}, #{movie.rank}"
end
end<file_sep>/studio_game/studio_game.gemspec
Gem::Specification.new do |s|
s.name = "studio_game_nikita"
s.version = "1.0"
s.author = "<NAME>"
s.email = "***<EMAIL>"
s.homepage = ""
s.summary = "A text based random hitter game with multiple players."
s.description = File.read(File.join(File.dirname(__FILE__), 'README'))
s.licenses = ['MIT']
s.files = Dir["{bin,lib,spec}/**/*"] + %w(LICENSE README)
s.test_files = Dir["spec/**/*"]
s.executables = [ 'studio_game.rb' ]
s.required_ruby_version = '>=1.9'
s.add_development_dependency 'rspec', '~> 2.8', '>= 2.8.0'
end<file_sep>/crowd_fund_app/crowdfund.rb
=begin Pragmatic Studio Crowd Fund App
project1_fund = 1000
project2_fund = 2000
project3_fund = 5000
project1_name = "ABC"
project2_name = "LMN"
project3_name = "XYZ"
puts "Project #{project1_name} has $#{project1_fund} in funding."
puts "Project #{project2_name} has $#{project2_fund} in funding."
puts "Project #{project3_name} has $#{project3_fund} in funding."
puts""
puts "Projects:\n\t#{project1_name}\n\t#{project2_name}\n\t#{project3_name}"
#Chapter 6
def project_list(name, fund)
"#{name.ljust(30,".")}Cost: #{fund}"
end
puts"List of Projects"
puts project_list("ABC", 1000)
puts project_list("LMN", 2000)
puts project_list("XYZ", 5000)
=end
#Chapter 7
class Project
attr_accessor :name, :amountInit, :amountTarget
def initialize(name, amountInit, amountTarget)
@name = name
@amountInit = amountInit
@amountTarget = amountTarget
end
def fund_increase
@amountInit += 25
puts"#{@name} has INCREASED funds!"
end
def fund_decrease
@amountInit -= 15
puts"#{@name} has DECREASED funds!"
end
def fund_increase_by(amt)
@amountInit = @amountInit + amt
end
end
class Portfolio
def initialize(name)
@name = name
@projectArray = []
end
def add_project(name)
@projectArray.push(name)
end
def stats
puts "This is portfolio called #{@name}. I have the following projects:"
@projectArray.each do |item|
puts "#{item.name} has #{item.amountInit} with a goal of : #{item.amountTarget}"
end
end
end
puts ""
proj1 = Project.new("Project1",500,1000)
proj2 = Project.new("Project2",700,1000)
proj3 = Project.new("Project3",300,1000)
proj4 = Project.new("Project4",100,1000)
portfolio1 = Portfolio.new("portfolio 1")
portfolio1.add_project(proj1)
portfolio1.add_project(proj2)
puts portfolio1.stats
=begin
puts xyz
puts xyz.fund_decrease
puts xyz
puts xyz.fund_increase_by(500)
puts xyz
projectsArray = [proj1, proj2, proj3, proj4]
puts "There are #{projectsArray.size} projects:"
projectsArray.each do |project|
puts "- #{project}"
end
=end<file_sep>/chris pines refresher/07 - Inheritance.rb
#Learning about inheritance
class Animal
def initialize
end
def speak
puts "Hello!"
end
end
#GoodDog inherits Animal Class
class GoodDog < Animal
end
#Cat inherits Animal Class
class Cat < Animal
end
sparky = GoodDog.new.speak
kitty = Cat.new.speak
puts "\n\n"
#So now, let's show how you can overwrite methods in the subclasses. Kind of like cascading css.
#Speak has been overwritten and doesn't get directions from Animal class anymore.
class GoodDog < Animal
def speak
puts "I am GoodDOG NOW!"
end
end
sparky = GoodDog.new.speak
#We also have a built-in function called "super". It allows you to call methods UP the inheritance hierarchy.
#Where we put super, it will look for the "speak" method that's in the SUPERCLASS (Animal).
class Animal
def speak
"Hello!"
end
end
class GoodDog < Animal
def speak
super + " from GoodDog class"
end
end
sparky = GoodDog.new
puts sparky.speak # => "Hello! from GoodDog class
<file_sep>/chris pines refresher/00 - misc.rb
require '/home/osboxes/RubymineProjects/Pragmatic-Ruby-Game/movieApp/movie.rb'
=begin
numBottles = 99
while numBottles > 2
puts "#{numBottles} bottles of beer on the wall. #{numBottles} bottles of beer."
puts "Take one down, pass it around. \n#{numBottles - 1} bottles of beer on the wall."
numBottles -= 1
end
puts "#{numBottles} bottle of beer on the wall. #{numBottles} bottle of beer."
puts "Take one down, pass it around. \n#{numBottles} bottle of beer on the wall."
numBottles -= 1
puts "No more bottles of beer on the wall, no more bottles of beer."
puts "Go to the store and buy some more, 99 bottles of beer on the wall."
puts"\n\n\n"
numbers = [1,2,3,4]
puts numbers
numbers = (1..10)
print numbers.to_a
puts "\n\n"
puts numbers.select{|n| n > 5}
numbers.select do |number|
number < 5
end
evens = numbers.select{|num| num.even?}
print evens
puts "\n"
odds = numbers.reject{|num| num.even?}
print odds
#evens, odds = numbers.partition {|num| num.evens?}
#You can also partition and split into 2 variables AFTERWARDS:
part_array = numbers.partition{|num| num.even?}
print part_array
evens = part_array[0]
odds = part_array[1]
puts "\n"
print evens
print odds
puts "\n\n"
#Let's use the reduce method to sum up the array
array = (1..5).to_a
print array
puts array.reduce{|sum, n| sum + n}
puts array.reduce{|product, n| product * n}
names = ["Goonies", "Ghostbusters", "Goldfinger", "Godfather"]
#Alphabetical order sorting
print names.sort
print"\n\n"
#Sort by:
print names.sort_by{|name| name.length}
#Practice iterators
array = [24,13,8,65]
newArray = array.select {|num|num>20 }
print newArray
newArray = array.reject {|num|num>20 }
print newArray
puts "\n\n"
newArray = array.sort
puts newArray
puts "\n\n"
newArray = array.sort.reverse
print newArray
puts "\n\n"
newArray = array.reduce{|sum,n| sum + n}
print newArray
evens, odds = array.partition {|num|num.even? }
puts "\n\n"
print evens, odds
puts "\n\n"
array = ["bobby", "alpha", "shazzball", "dickerson"]
print array
newArray = array.sort
print newArray
newArray = array.sort_by{|item|item.length}.reverse
print newArray
puts "\n\n\n\n"
#Structs
Snack = Struct.new(:name, :carbs)
popcorn = Snack.new("popcorn", 20)
candy = Snack.new("candy", 15)
puts "\n\n\n\n"
#Hashes
#old way of writing before Ruby 1.9
#snack_carbs = {
# :candy => 15,
# :pretzel => 10
#}
#New way of writing hashes (greater than Ruby 1.9)
snack_carbs = {
candy: 30,
pretzel: 100
}
puts snack_carbs[:candy]
snack_carbs[:candy] = 15
puts snack_carbs[:candy]
print snack_carbs.keys
print snack_carbs.values
puts""
snack_carbs.each do |key, value|
puts "#{key} has #{value} carbs"
end
puts"\n\n"
snack_carbs = {}
snack_carbs[:candy] = 15
snack_carbs[:candy] += 15
puts snack_carbs[:candy]
#snack_carbs[:surge] += 10
snack_carbs = Hash.new(0)
snack_carbs[:bread] += 15
p snack_carbs
#Hashes
moes_treasures = {
:hammer => 100,
:crowbar => 500
}
puts moes_treasures
moes_treasures.each { |key, value| puts "Moe has a #{key} that's worth #{value}" }
hash_arr = moes_treasures.keys
print hash_arr
hash_arr = moes_treasures.values
print hash_arr
puts "\n\n"
#So if we wanted to sum up the values of all the keys, we'd run this.
#In the parenthesis, is the initial value....(zero)
#Then you have the sum...for the entire block, and each part that's going to get added up.
sum1 = moes_treasures.values.reduce(0){ |sum, n| sum + n }
# can also write it with a symbol
sum2= moes_treasures.values.reduce(0, :-)
puts sum2
#You can also use INJECT...which is exactly same as reduce.
sum3 = moes_treasures.values.reduce{|sum, n| sum + n}
puts sum3
puts "\n\n\n\n\n"
=end
#Scrabble Game
#
letters = {
"c" => 3,
"e" => 1,
"l" => 1,
"n" => 1,
"t" => 1,
"x" => 8,
"y" => 4
}
score = Hash.new(0)
word = "cell".each_char
word.each do |char|
letters.each { |key, value|
if char == key
score[key] += value
end
}
end
score.each do |key, value|
puts "#{key} : #{value}"
end
#Custom Iterators
def once
puts "Before Yield"
yield
puts "After Yield"
end
once {puts "Running Block"}
def three_times
yield(1)
yield(2)
end
three_times {|number| puts "This is number #{number}"}
def compute
puts yield
end
numbers = (1..10).to_a
####Let's make the array give even numbers only:
numbers = (1..10).to_a
numbers.select {|num|num.even? }
#But now, let's implement this "SELECT" method ourselves!
def my_select(array)
results = []
array.each do |element|
results << element if yield(element)
end
results
end
puts my_select(numbers) {|n|n.even?}
def conversation
puts "Hello"
yield
puts "Goodbye"
end
conversation {puts "Good to meet you!"}
def five_times
yield 1
yield 2
end
five_times do |n|
puts "#{n} situps"
puts "#{n} pushups"
puts "#{n} chinups"
end
#INPUT OUTPUT
# Opening Files
File.open("/home/osboxes/RubymineProjects/Pragmatic-Ruby-Game/chris pines refresher/movies.csv") do |file|
file.each_line do |line|
puts line
end
end
#use readlines method instead...it runs a block and puts each line into an array that you can then print.
File.readlines("/home/osboxes/RubymineProjects/Pragmatic-Ruby-Game/chris pines refresher/movies.csv").each do |line|
print line
end
puts "\n\n\n"
#use readlines method instead...it runs a block and puts each line into an array that you can then print.
# Make sure to require the movie object at the top of this file..
File.readlines("/home/osboxes/RubymineProjects/Pragmatic-Ruby-Game/chris pines refresher/movies.csv").each do |line|
title, rank = line.split(",")
movie = Movie.new(title, rank.to_i)
puts movie
end
<file_sep>/movieApp/trash/conditionals.rb
require_relative '../lib/movie'
movie = Movie.new('godfather', 10)
#You can use an IF, or you can use it on a single line.
if movie.rank >= 10
puts "Hit!"
end
puts "Hit!" if movie.rank >= 10
if movie.rank < 10
puts "flop"
end
puts "flop" if movie.rank < 10
puts "\n\n"
if movie.rank >= 10
puts "hit"
else
puts "flop"
end
|
5086c47a83fbe7ecf65035fee310163604bb87c9
|
[
"Markdown",
"Ruby"
] | 27 |
Markdown
|
nikita-kazakov/Pragmatic-Ruby-Game
|
44b3a81748778499161329cb3fe1587b9eb34fb5
|
a39f68d7d193fb79c19a3e25719ffd1a4046cc31
|
refs/heads/master
|
<repo_name>Mikulward/Inventorything<file_sep>/MWDM3000.rb
puts "Welcome to the Michael Ward Drink Master 2000!!!".center(75)
puts
puts "Please enter the current amount of drinks in each row."
puts
#TEAS #TEAS #TEAS #TEAS #TEAS #TEAS #TEAS #TEAS #TEAS #TEAS #TEAS #TEAS #TEAS #TEAS
print "Pink Tea Row A: "
PTA = gets
print "Pink Tea Row B: "
PTB = gets
PTN = (16 - (PTA.to_i + PTB.to_i))
print "Orange Tea Row A: "
OTA = gets
print "Orange Tea Row B: "
OTB = gets
OTN = (16 - (OTA.to_i + OTB.to_i))
print "Green Tea Row A: "
GTA = gets
print "Green Tea Row B: "
GTB = gets
GTN = (16 - (GTA.to_i + GTB.to_i))
print "Blue Tea Row A: "
BTA = gets
print "Blue Tea Row B: "
BTB = gets
BTN = (16 - (BTA.to_i + BTB.to_i))
puts ''
#RADE #RADE #RADE #RADE #RADE #RADE #RADE #RADE #RADE #RADE #RADE #RADE #RADE #RADE
print "Rade Row A: "
GRA = gets
print "Rade Row B: "
GRB = gets
GRN = (14 - (GRA.to_i + GRB.to_i))
puts ''
#COCONUT #COCONUT #COCONUT #COCONUT #COCONUT #COCONUT #COCONUT #COCONUT
print "Coconut Row A: "
CocoA = gets
print "Coconut Row B: "
CocoB = gets
print "Coconut Row C: "
CocoC = gets
CocoN = (24 - (CocoA.to_i + CocoB.to_i + CocoC.to_i))
#JUICE #JUICE #JUICE #JUICE #JUICE #JUICE #JUICE #JUICE #JUICE #JUICE #JUICE #JUICE
print "Orange Juice Row A: "
OJA = gets
print "Orange Juice Row B: "
OJB = gets
print "Orange Juice Row C: "
OJC = gets
OJN = (24 - (OJA.to_i + OJB.to_i + OJC.to_i))
print "Apple Juice Row A: "
AJA = gets
print "Apple Juice Row B: "
AJB = gets
print "Apple Juice Row C: "
AJC = gets
AJN = (24 - (AJA.to_i + AJB.to_i + AJC.to_i))
print "Cranberry Juice Row A: "
CJA = gets
print "Cranberry Juice Row B: "
CJB = gets
puts ''
CJN = (16 - (CJA.to_i + CJB.to_i))
#REDBULLS #REDBULLS #REDBULLS #REDBULLS #REDBULLS #REDBULLS #REDBULLS #REDBULLS #REDBULLS
print "Sugar-Free Redbull Row A: "
SFRBA = gets
print "Sugar-Free Redbull Row B: "
SFRBB = gets
print "Sugar-Free Redbull Row B: "
SFRBC = gets
SFRBN = (27 - (SFRBA.to_i + SFRBB.to_i + SFRBC.to_i))
print "Redbull Row A: "
RBA = gets
print "Redbull Row B: "
RBB = gets
RBN = (18 - (RBA.to_i + RBB.to_i))
puts ''
#COKE #COKE #COKE #COKE #COKE #COKE #COKE #COKE #COKE #COKE #COKE #COKE #COKE #COKE
print "Diet Coke Row A: "
DCA = gets
print "Diet Coke Row B: "
DCB = gets
print "Diet Coke Row C: "
DCC = gets
DCN = (21 - (DCA.to_i + DCB.to_i + DCC.to_i))
print "Coke Row A: "
CA = gets
print "Coke Row B: "
CB = gets
CN = (14 - (CA.to_i + CB.to_i))
puts ''
#SODAS #SODAS #SODAS #SODAS #SODAS #SODAS #SODAS #SODAS #SODAS #SODAS #SODAS #SODAS
print "Fresca: "
F = gets
FN = (7 - F.to_i)
print "Diet Ginger Ale: "
DGA = gets
DGAN = (7 - DGA.to_i)
print "Ginger Ale: "
GA = gets
GAN = (7 - GA.to_i)
print "Diet Dr. Pepper: "
DDP = gets
DDPN = (7 - DDP.to_i)
print "Sprite: "
S = gets
SN = (7 - S.to_i)
print "Orangina: "
O = gets
ON = (7 - O.to_i)
print "Root Beer: "
RoB = gets
RoBN = (7 - RoB.to_i)
print "Dr. Brown: "
DB = gets
DBN = (7 - DB.to_i)
print "Cherry Coke: "
CC = gets
CCN = (7 - CC.to_i)
puts ''
#SELTZER #SELTZER #SELTZER #SELTZER #SELTZER #SELTZER #SELTZER #SELTZER #SELTZER #SELTZER
print "Seltzer Row A: "
SeA = gets
print "Seltzer Row B: "
SeB = gets
print "Seltzer Row C: "
SeC = gets
print "Seltzer Row D: "
SeD = gets
print "Seltzer Row E: "
SeE = gets
print "Seltzer Row F: "
SeF = gets
print "Seltzer Row G: "
SeG = gets
print "Seltzer Row H: "
SeH = gets
print "Seltzer Row I: "
SeI = gets
SeN = (63 - ((SeA.to_i) + (SeB.to_i) + (SeC.to_i) + (SeD.to_i) + (SeE.to_i) + (SeF.to_i) +
(SeG.to_i) + (SeH.to_i) + (SeI.to_i)))
puts ''
#OTHERS #OTHERS #OTHERS #OTHERS #OTHERS #OTHERS #OTHERS #OTHERS #OTHERS #OTHERS #OTHERS
print "Lemon Seltzer Row A: "
LSA = gets
print "Lemon Seltzer Row B: "
LSB = gets
LSN = (14 - (LSA.to_i + LSB.to_i))
puts ''
print "Orange Adirondack Row A: "
OAA = gets
print "Orange Adirondack Row B: "
OAB = gets
OAN = (14 - (OAA.to_i + OAB.to_i))
print "Raspberry Adirondack Row A: "
RAA = gets
print "Raspberry Adirondack Row B: "
RAB = gets
RAN = (14 - (RAA.to_i + RAB.to_i))
print "Wild Berry Adirondack Row A: "
WAA = gets
print "Wild Berry Adirondack Row B: "
WAB = gets
WAN = (14 - (WAA.to_i + WAB.to_i))
puts ''
print "Light Izze: "
LI = gets
LIN = (9 - LI.to_i)
print "Dark Izze: "
DI = gets
DIN = (9 - DI.to_i)
puts ''
puts "Drinks Needed Drinks Needed Drinks Needed Drinks Needed Drinks Needed Drinks Needed ".center(75)
puts ''
#TEAS2 #TEAS2 #TEAS2 #TEAS2 #TEAS2 #TEAS2 #TEAS2 #TEAS2 #TEAS2 #TEAS2 #TEAS2 #TEAS2
if PTN <= 0
puts "No Pink Teas Needed"
elsif PTN == 12
puts "Pink Teas: 1 Case"
elsif PTN > 12
puts "Pink Teas: 1 Case and " + (PTN - 12).to_s + " extra"
else
puts "Pink Teas: " + PTN.to_s
end
if OTN <= 0
puts "No Orange Teas Needed"
elsif OTN == 12
puts "Orange Teas: 1 Case"
elsif PTN > 12
puts "Orange Teas: 1 Case and " + (OTN - 12).to_s + " extra"
else
puts "Orange Teas: " + OTN.to_s
end
if GTN <= 0
puts "No Green Teas Needed"
elsif GTN == 12
puts "Green Teas: 1 Case"
elsif GTN > 12
puts "Green Teas: 1 Case and " + (GTN - 12).to_s + " extra"
else
puts "Green Teas: " + GTN.to_s
end
if BTN <= 0
puts "No Blue Teas Needed"
elsif BTN == 12
puts "Blue Teas: 1 Case"
elsif BTN > 12
puts "Blue Teas: 1 Case and " + (BTN - 12).to_s + " extra"
else
puts "Blue Teas: " + BTN.to_s
end
puts ''
#RADE2 #RADE2 #RADE2 #RADE2 #RADE2 #RADE2 #RADE2 #RADE2 #RADE2 #RADE2 #RADE2 #RADE2
if GRN <= 0
puts "No Rade Needed"
elsif GRN == 12
puts "Rade: 1 Case"
elsif GRN > 12
puts "Rade: 1 Case and " + (GRN - 12).to_s + " extra"
else
puts "Rade: " + GRN.to_s
end
puts ''
#Coconut2 #Coconut2#Coconut2#Coconut2#Coconut2#Coconut2#Coconut2#Coconut2
if CocoN <= 0
puts "No Coconut Water Needed"
elsif CocoN == 12
puts "Coconut Water: 1 Case"
elsif CocoN > 12
puts "Coconut Water: 1 Case and " + (CocoN - 12).to_s + " extra"
else
puts "Coconut Water: " + CocoN.to_s
end
#JUICE2 #JUICE2 #JUICE2 #JUICE2 #JUICE2 #JUICE2 #JUICE2 #JUICE2 #JUICE2 #JUICE2 #JUICE2
if OJN <= 0
puts "No Orange Juice Needed"
elsif OJN == 24
puts "Orange Juice: 1 Case"
elsif OJN > 24
puts "Orange Juice: 1 Case and " + (OJN - 24).to_s + " extra"
else
puts "Orange Juice: " + OJN.to_s
end
if AJN <= 0
puts "No Apple Juice Needed"
elsif AJN == 24
puts "Apple Juice: 1 Case"
elsif AJN > 24
puts "Apple Juice: 1 Case and " + (AJN - 24).to_s + " extra"
else
puts "Apple Juice: " + AJN.to_s
end
if CJN <= 0
puts "No Cranberry Juice Needed"
elsif CJN == 24
puts "Cranberry Juice: 1 Case"
elsif CJN > 24
puts "Cranberry Juice: 1 Case and " + (CJN - 24).to_s + " extra"
else
puts "Cranberry Juice: " + CJN.to_s
end
puts ''
#REDBULL2 #REDBULL2 #REDBULL2 #REDBULL2 #REDBULL2 #REDBULL2 #REDBULL2 #REDBULL2
if SFRBN <= 0
puts "No Sugar Free Red Bull Needed"
else
puts "Sugar Free Red Bull: " + SFRBN.to_s
end
if RBN <= 0
puts "No Red Bull Needed"
else
puts "Red Bull: " + RBN.to_s
end
#COKE2 COKE2 COKE2 COKE2 COKE2 COKE2 COKE2 COKE2 COKE2 COKE2 COKE2 COKE2
puts ''
DCN6 = (DCN.to_i/6)
if DCN > 6 && DCN < 12
puts "Diet Coke: " + DCN6.to_s + " Six Pack and " + (DCN.to_i - (DCN6.to_i*6)).to_s + " extra"
elsif DCN > 12 && DCN < 18
puts "Diet Coke: " + DCN6.to_s + " Six Packs and " + (DCN.to_i - (DCN6.to_i*6)).to_s + " extra"
elsif DCN > 18
puts "Diet Coke: " + DCN6.to_s + " Six Packs and " + (DCN.to_i - (DCN6.to_i*6)).to_s + " extra"
elsif DCN == 12 || DCN == 18
puts "Diet Coke: " + DCN6.to_s + " Six Packs"
elsif DCN == 6
puts "Diet Coke: " + DCN6.to_s + " Six Pack"
elsif DCN.to_i <= 0
puts "No Diet Coke Needed"
else
puts "Diet Coke: " + DCN.to_s
end
CN6 = (CN.to_i/6)
CN6M = (CN.to_i%6)
if CN <= 0
puts "No Coke Needed"
elsif CN < 6
puts "Coke: " + CN.to_s
elsif CN == 6
puts "Coke: " + CN6.to_s + " Six Pack"
elsif CN > 6 && CN < 12
puts "Coke: " +CN6.to_s+ " Six Pack and " +CN6M.to_s+ " extra"
elsif CN == 12
puts "Coke: " +CN6.to_s+ " Six Packs"
elsif CN > 12
puts "Coke: " +CN6.to_s+ " Six Packs and " +CN6M.to_s+ " extra"
end
puts ''
#SODAS2 SODAS2 SODAS2 SODAS2 SODAS2 SODAS2 SODAS2 SODAS2 SODAS2 SODAS2 SODAS2
if FN <= 0
puts "No Fresca Needed"
else
puts "Fresca: " + FN.to_s
end
puts ''
DGAN6 = (DGAN.to_i/6)
DGAN6M = (DGAN.to_i%6)
if DGAN <= 0
puts "No Diet Ginger Ale Needed"
elsif DGAN < 6
puts "Diet Ginger Ale: " + DGAN.to_s
elsif DGAN == 6
puts "Diet Ginger Ale: " + DGAN6.to_s + " Six Pack"
elsif DGAN > 6
puts "Diet Ginger Ale: " +DGAN6.to_s+ " Six Pack and " +DGAN6M.to_s+ " extra"
end
puts ''
GAN6 = (GAN.to_i/6)
GAN6M = (GAN.to_i%6)
if GAN <= 0
puts "No Ginger Ale Needed"
elsif GAN < 6
puts "Ginger Ale: " + GAN.to_s
elsif GAN == 6
puts "Ginger Ale: " + GAN6.to_s + " Six Pack"
elsif GAN > 6
puts "Ginger Ale: " +GAN6.to_s+ " Six Pack and " +GAN6M.to_s+ " extra"
end
puts ''
DDPN6 = (DDPN.to_i/6)
DDPN6M = (DDPN.to_i%6)
if DDPN <= 0
puts "No Diet Dr. Pepper Needed"
elsif DDPN < 6
puts "Diet Dr. Pepper: " + DDPN.to_s
elsif DDPN == 6
puts "Diet Dr. Pepper: " + DDPN6.to_s + " Six Pack"
elsif DDPN > 6
puts "Diet Dr. Pepper: " +DDPN6.to_s+ " Six Pack and " +DDPN6M.to_s+ " extra"
end
puts ''
SN6 = (SN.to_i/6)
SN6M = (SN.to_i%6)
if SN <= 0
puts "No Sprite Needed"
elsif SN < 6
puts "Sprite: " + SN.to_s
elsif SN == 6
puts "Sprite: " + SN6.to_s + " Six Pack"
elsif SN > 6
puts "Sprite: " +SN6.to_s+ " Six Pack and " +SN6M.to_s+ " extra"
end
puts ''
ON6 = (ON.to_i/6)
ON6M = (ON.to_i%6)
if ON <= 0
puts "No Orangina Needed"
elsif ON < 6
puts "Orangina: " + ON.to_s
elsif ON == 6
puts "Orangina: " + ON6.to_s + " Six Pack"
elsif ON > 6
puts "Orangina: " +ON6.to_s+ " Six Pack and " +ON6M.to_s+ " extra"
end
puts ''
RoBN6 = (RoBN.to_i/6)
RoBN6M = (RoBN.to_i%6)
if RoBN <= 0
puts "No Root Beer Needed"
elsif RoBN < 6
puts "Root Beer: " + RoBN.to_s
elsif RoBN == 6
puts "Root Beer: " + RoBN6.to_s + " Six Pack"
elsif RoBN > 6
puts "Root Beer: " +RoBN6.to_s+ " Six Pack and " +RoBN6M.to_s+ " extra"
end
puts ''
DBN6 = (DBN.to_i/6)
DBN6M = (DBN.to_i%6)
if DBN <= 0
puts "No Dr. Brown Needed"
elsif DBN < 6
puts "Dr. Brown: " + DBN.to_s
elsif DBN == 6
puts "Dr. Brown: " + DBN6.to_s + " Six Pack"
elsif DBN > 6
puts "Dr. Brown: " +DBN6.to_s+ " Six Pack and " +DBN6M.to_s+ " extra"
end
puts ''
if CCN <= 0
puts "No Cherry Coke Needed"
else
puts "Cherry Coke: " + CCN.to_s
end
#SELTZER #SELTZER #SELTZER #SELTZER #SELTZER #SELTZER #SELTZER #SELTZER #SELTZER
puts ''
SeN6 = (SeN.to_i/6)
SeN6M = (SeN.to_i%6)
SeNC = (SeN.to_i/24)
SeN6C = ((SeN.to_i%24)/6)
SeN6CM = ((SeN.to_i%24)%6)
if SeN <= 0
puts "No Seltzer Needed"
elsif SeN == 6
puts "Seltzer: " + SeN6.to_s + " Six Pack"
elsif SeN > 6 && SeN < 12
puts "Seltzer: " +SeN6.to_s+ " Six Pack and " +SeN6M.to_s+ " extra"
elsif SeN == 12 || SeN == 18
puts "Seltzer: " + SeN6.to_s + " Six Packs"
elsif SeN == 24
puts "Seltzer: " + SeNC.to_s + " Case"
elsif SeN == 30
puts "Seltzer: " + SeNC.to_s + " Case and " +SeN6C.to_s+ " Six Pack"
elsif SeN == 36 || SeN == 42
puts "Seltzer: " + SeNC.to_s + " Case and " +SeN6C.to_s+ " Six Packs"
elsif SeN == 48
puts "Seltzer: " + SeNC.to_s + " Cases"
elsif SeN == 54
puts "Seltzer: " + SeNC.to_s + " Cases and " +SeN6C.to_s+ " Six Pack"
elsif SeN == 60
puts "Seltzer: " + SeNC.to_s + " Cases and " +SeN6C.to_s+ " Six Packs"
elsif SeN < 6
puts "Seltzer: " + SeN.to_s
elsif SeN > 6 && SeN < 12
puts "Seltzer: " +SeN6.to_s+ " Six Pack and " +SeN6M.to_s+ " extra"
elsif SeN > 12 && SeN < 24
puts "Seltzer: " +SeN6.to_s+ " Six Packs and " +SeN6M.to_s+ " extra"
elsif SeN > 24 && SeN < 30
puts "Seltzer: " + SeNC.to_s + " Case and " +SeN6M.to_s+ " extra"
elsif SeN > 30 && SeN < 36
puts "Seltzer: " + SeNC.to_s + " Case and " +SeN6C.to_s+ " Six Pack and " +SeN6M.to_s+ " extra"
elsif SeN > 36 && SeN < 48
puts "Seltzer: " + SeNC.to_s + " Case and " +SeN6C.to_s+ " Six Packs and " +SeN6M.to_s+ " extra"
elsif SeN > 48 && SeN < 54
puts "Seltzer: " + SeNC.to_s + " Cases and " +SeN6M.to_s+ " extra"
elsif SeN > 54
puts "Seltzer: " + SeNC.to_s + " Cases and " +SeN6C.to_s+ " Six Packs and " +SeN6M.to_s+ " extra"
end
LSN12 = (LSN.to_i/12)
LSN12M = (LSN.to_i%12)
if LSN <= 0
puts "No Lemon Seltzer Needed"
elsif LSN < 12
puts "Lemon Seltzer: " + LSN.to_s
elsif LSN == 12
puts "Lemon Seltzer: " + LSN12.to_s + " 12-PacK"
elsif LSN > 12
puts "Lemon Seltzer: " +LSN12.to_s+ " 12-Pack and " +LSN12M.to_s+ " extra"
end
#OTHER #OTHER #OTHER #OTHER #OTHER #OTHER #OTHER #OTHER #OTHER #OTHER #OTHER #OTHER
puts ''
OAN6 = (OAN.to_i/6)
OAN6M = (OAN.to_i%6)
if OAN <= 0
puts "No Orange Adirondack Needed"
elsif OAN < 6
puts "Orange Adirondack: " + OAN.to_s
elsif OAN == 6
puts "Orange Adirondack: " + OAN6.to_s + " Six Pack"
elsif OAN > 6 && OAN < 12
puts "Orange Adirondack: " +OAN6.to_s+ " Six Pack and " +OAN6M.to_s+ " extra"
elsif OAN == 12
puts "Orange Adirondack: " +OAN6.to_s+ " Six Packs"
elsif OAN > 12
puts "Orange Adirondack: " +OAN6.to_s+ " Six Packs and " +OAN6M.to_s+ " extra"
end
RAN6 = (RAN.to_i/6)
RAN6M = (RAN.to_i%6)
if RAN <= 0
puts "No Raspberry Adirondack Needed"
elsif RAN < 6
puts "Raspberry Adirondack: " + RAN.to_s
elsif RAN == 6
puts "Raspberry Adirondack: " + RAN6.to_s + " Six Pack"
elsif RAN > 6 && RAN < 12
puts "Raspberry Adirondack: " +RAN6.to_s+ " Six Pack and " +RAN6M.to_s+ " extra"
elsif RAN == 12
puts "Raspberry Adirondack: " +RAN6.to_s+ " Six Packs"
elsif CN > 12
puts "Raspberry Adirondack: " +RAN6.to_s+ " Six Packs and " +RAN6M.to_s+ " extra"
end
WAN6 = (WAN.to_i/6)
WAN6M = (WAN.to_i%6)
if WAN <= 0
puts "No Wild Berry Adirondack Needed"
elsif WAN < 6
puts "Wild Berry Adirondack: " + WAN.to_s
elsif WAN == 6
puts "Wild Berry Adirondack: " + WAN6.to_s + " Six Pack"
elsif WAN > 6 && WAN < 12
puts "Wild Berry Adirondack: " +WAN6.to_s+ " Six Pack and " +WAN6M.to_s+ " extra"
elsif WAN == 12
puts "Wild Berry Adirondack: " +WAN6.to_s+ " Six Packs"
elsif CN > 12
puts "Wild Berry Adirondack: " +WAN6.to_s+ " Six Packs and " +WAN6M.to_s+ " extra"
end
puts ''
if LIN <= 0
puts "No Light Izze Needed"
else
puts "Light Izze: " + LIN.to_s
end
if DIN <= 0
puts "No Dark Izze Needed"
else
puts "Dark Izze: " + DIN.to_s
end
|
4b83c4c5226e9ec69348a79c823fe02a813974a7
|
[
"Ruby"
] | 1 |
Ruby
|
Mikulward/Inventorything
|
612aee393e1ad5246dac6af0ce4dcbee32c54c51
|
b7bca5684adc0a5e4909de6fdb3c02c0aa1386c2
|
refs/heads/master
|
<file_sep>import { Component} from '@angular/core';
@Component({
templateUrl: 'expedition-detail.component.html',
styleUrls: ['./expedition-detail.component.scss']
})
export class ExpeditionDetailComponent {
}
<file_sep>import { NgModule } from '@angular/core';
import { ExpeditionDetailComponent } from './expedition-detail/expedition-detail.component';
import { ExpeditionRoutingModule } from './expedition-routing.module';
import { NewExpeditionComponent } from './new-expedition/new-expedition.component';
import { ExpeditionListComponent } from './expedition-list/expedition-list.component';
import { NgxDatatableModule } from '@swimlane/ngx-datatable';
@NgModule({
imports: [
NgxDatatableModule,
ExpeditionRoutingModule
],
declarations: [ExpeditionListComponent, NewExpeditionComponent, ExpeditionDetailComponent]
})
export class ExpeditionModule { }
<file_sep>export interface NavData {
name?: string;
url?: string;
icon?: string;
badge?: any;
title?: boolean;
children?: any;
variant?: string;
attributes?: object;
divider?: boolean;
class?: string;
}
export const navItems: NavData[] = [
{
name: 'Dashboard',
url: '/dashboard',
icon: 'icon-speedometer'
},
{
name: 'Expedition',
url: '/expedition',
icon: 'icon-paper-plane'
// ,
// children: [
// {
// name: 'Nouvelle expédition',
// url: '/expedition/create',
// icon: 'icon-energy'
// }
// // ,
// // {
// // name: 'Dropdowns',
// // url: '/buttons/dropdowns',
// // icon: 'icon-cursor'
// // },
// // {
// // name: 'Brand Buttons',
// // url: '/buttons/brand-buttons',
// // icon: 'icon-cursor'
// // }
// ]
},
{
name: 'Invoice',
url: '/theme/typography',
icon: 'icon-doc'
},
{
name: 'Settings',
url: '/buttons',
icon: 'icon-settings',
children: [
{
name: 'Buttons',
url: '/buttons/buttons',
icon: 'icon-cursor'
},
{
name: 'Dropdowns',
url: '/buttons/dropdowns',
icon: 'icon-cursor'
},
{
name: 'Brand Buttons',
url: '/buttons/brand-buttons',
icon: 'icon-cursor'
}
]
}
];
<file_sep><div class="row progression">
<div class="col-md-2 col-sm-6 timeline">
<div class="timeline-inner">
<div class="timeline-content">
<div class="post">Acceptée</div>
<div class="description">
17H55 01/02/2018
</div>
</div>
<div class="timeline-icon">
<i class="fa fa-handshake-o"></i>
</div>
</div>
</div>
<div class="col-md-2 col-sm-6 timeline">
<div class="timeline-inner">
<div class="timeline-content">
<div class="post">En approche d'enlévement</div>
<div class="description">
17H55 01/02/2018
</div>
</div>
<div class="timeline-icon">
<i class="fa fa-map-marker"></i>
</div>
</div>
</div>
<div class="col-md-2 col-sm-6 timeline">
<div class="timeline-inner">
<div class="timeline-content">
<div class="post">En cours d'enlévement</div>
<div class="description">
17H55 01/02/2018
</div>
</div>
<div class="timeline-icon">
<i class="fa fa-cubes"></i>
</div>
</div>
</div>
<div class="col-md-2 col-sm-6 timeline">
<div class="timeline-inner">
<div class="timeline-content">
<div class="post">En approche de livraison</div>
<div class="description">
17H55 01/02/2018
</div>
</div>
<div class="timeline-icon">
<i class="fa fa-truck"></i>
</div>
</div>
</div>
<div class="col-md-2 col-sm-6 timeline">
<div class="timeline-inner">
<div class="timeline-content">
<div class="post">En cours de livraison</div>
<div class="description">
17H55 01/02/2018
</div>
</div>
<div class="timeline-icon">
<i class="fa fa-hourglass-half"></i>
</div>
</div>
</div>
<div class="col-md-2 col-sm-6 timeline">
<div class="timeline-inner">
<div class="timeline-content">
<div class="post">Livré</div>
<div class="description">
17H55 01/02/2018
</div>
</div>
<div class="timeline-icon">
<i class="fa fa-flag"></i>
</div>
</div>
</div>
</div>
<div class="row truck">
<div class="col-md-4 col-sm-6 drawing">
<i class="fa fa-cubes"></i>
<i class="fa fa-long-arrow-right"></i>
<i class="fa fa-truck"></i>
</div>
<div class="col-md-4 col-sm-6 info">
<div class="description">Assigner l'expédition à une remorque:</div>
<div class="value">CC-731-PR</div>
<div class="description">Assigner l'expédition à un chauffeur:</div>
<div class="value"> <NAME></div>
</div>
<div class="col-md-4 col-sm-6 comment">
<div class="title">Commentaire:</div>
<div class="value">Enlévement prévu le Mardi en fin de matinée avant 12h00</div>
<div class="value">Livraison prévu le Jeudi en fin d'aprés midi avant 18h00</div>
</div>
</div>
<div class="row path">
<div class="col-md-4 col-sm-6 departure">
<div class="name">
Medo
</div>
<div class="adress">
Place Louis Armand, 75012 Paris France
</div>
<div class="date">
Le 04/07/2017 à 13h00
</div>
</div>
<div class="col-md-4 col-sm-6 timeline">
<div class="steps-timeline">
<div class="steps-one">
<div class="steps-img"></div>
<h3 class="steps-name">
Enlévement
</h3>
</div>
<div class="mileage">Distance: 520KM</div>
<div class="steps-two">
<div class="steps-img"></div>
<h3 class="steps-name">
Livraison
</h3>
</div>
</div>
</div>
<div class="col-md-4 col-sm-6 arrival">
<div class="name">Gosho</div>
<div class="adress">
Rue Gambetta, 83990 Saint Tropez France
</div>
<div class="date">
Le 64/07/2017 à 15h00
</div>
</div>
</div>
<div class="row maps">
<div class="col-md-4 col-sm-6">
</div>
<div class="col-md-4 col-sm-6 timeline">
</div>
<div class="col-md-4 col-sm-6 arrival">
</div>
</div><file_sep>import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ExpeditionDetailComponent } from './expedition-detail/expedition-detail.component';
import { NewExpeditionComponent } from './new-expedition/new-expedition.component';
import { ExpeditionListComponent } from './expedition-list/expedition-list.component';
const routes: Routes = [
{
path: '',
component: ExpeditionListComponent,
data: {
title: 'Expéditions'
}
},
{
path: 'detail',
component: ExpeditionDetailComponent,
data: {
title: 'Détail'
}
},
{
path: 'create',
component: NewExpeditionComponent,
data: {
title: 'Nouvelle expédition'
}
}
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class ExpeditionRoutingModule {}
<file_sep>import { Component} from '@angular/core';
@Component({
templateUrl: 'new-expedition.component.html',
styleUrls: ['./new-expedition.component.scss']
})
export class NewExpeditionComponent {
}
<file_sep>
import { Component} from '@angular/core';
@Component({
templateUrl: 'expedition-list.component.html'
})
export class ExpeditionListComponent {
rows = [];
joke = 'knock knock';
constructor() {
this.fetch((data) => {
this.rows = data.splice(0, 5);
});
}
fetch(cb) {
const req = new XMLHttpRequest();
req.open('GET', `assets/data/company.json`);
req.onload = () => {
cb(JSON.parse(req.response));
};
req.send();
}
}
|
c294904243ddf357d294f37a886a42a430fc1d44
|
[
"TypeScript",
"HTML"
] | 7 |
TypeScript
|
mmansouri/linky
|
1e1950df8dbea908f714e3af0bdd2e449a5feb91
|
d7acf3eb726bd80c3fe978ccb94a8894768f9a18
|
refs/heads/master
|
<repo_name>Apokalipsa/bild-it-2015<file_sep>/src/org/bildit/homework/may19th/TickTacToe.java
package org.bildit.homework.may19th;
import java.util.InputMismatchException;
import java.util.Scanner;
/**
* @author <NAME>
*/
public class TickTacToe {
public static String[] tick = { "1", "2", "3", "4", "5", "6", "7", "8", "9" };
public static String whoWon = null;
public static int inputs = 0;
public static boolean result = false;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int consoleInput = 0;
boolean inputIsOk;
do {
drawGrid();
System.out.print("Choose field: ");
do {
try {
consoleInput = scanner.nextInt();
if (consoleInput > 9 || consoleInput <= 0) {
System.out.println("Imposible position");
System.out.print("Try again: ");
inputIsOk = false;
} else {
inputs++;
inputIsOk = true;
}
} catch (InputMismatchException exception) {
System.out.println("Use numbers only!");
scanner.nextLine();
inputIsOk = false;
}
} while (!inputIsOk);
if (isTaken(consoleInput)) {
if (inputs % 2 == 0) {
tick[consoleInput - 1] = "o";
} else if (isTaken(consoleInput)) {
tick[consoleInput - 1] = "x";
}
} else {
inputs--;
System.out.println("That place is taken, try another one!");
}
} while (!gameOver());
System.out.println("---------------------------");
System.out.println("Game is over");
System.out.println("---------------------------");
if (!(whoWon.equals("I'ts a tie!"))) {
System.out.println("Player: "
+ whoWon.substring(0, whoWon.length() - 2)+" won!");
} else {
System.out.println(whoWon);
}
drawGrid();
scanner.close();
}
public static boolean isTaken(int n) {
return (!("x".equals(tick[n - 1]) || "o".equals(tick[n - 1])));
}
public static boolean gameOver() {
for (int i = 0, a = 0; i < 9; i = i + 3, a++) {
if (wonDiagonal("xxx") || wonDiagonal("ooo")) {
break;
} else if (wonHorizontalOrVertical("xxx", i, a)
|| wonHorizontalOrVertical("ooo", i, a)) {
break;
} else if (inputs > 8) {
whoWon = "It's a tie!";
result = true;
}
}
return result;
}
public static void drawGrid() {
System.out.println("---------------------------");
System.out.println("[" + tick[0] + "]" + "[" + tick[1] + "]" + "["
+ tick[2] + "]");
System.out.println("[" + tick[3] + "]" + "[" + tick[4] + "]" + "["
+ tick[5] + "]");
System.out.println("[" + tick[6] + "]" + "[" + tick[7] + "]" + "["
+ tick[8] + "]");
System.out.println("---------------------------");
}
public static boolean wonDiagonal(String player) {
if (player.equals(String.valueOf(tick[0] + tick[4] + tick[8]))
|| player.equals(String.valueOf(tick[2] + tick[4] + tick[6]))) {
whoWon = player;
result = true;
} else {
result = false;
}
return result;
}
public static boolean wonHorizontalOrVertical(String player, int i, int a) {
if (player.equals(String.valueOf(tick[i] + tick[i + 1] + tick[i + 2]))
|| player.equals(String.valueOf(tick[a] + tick[a + 3]
+ tick[a + 6]))) {
whoWon = player;
result = true;
} else {
result = false;
}
return result;
}
}
|
1dce2742211511674551f7ab03834c795124d320
|
[
"Java"
] | 1 |
Java
|
Apokalipsa/bild-it-2015
|
2b348ffa543b30cd5d6a24893b612709141f94b9
|
5b198a99a55a0fd113aff78328ef01df573aa32f
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Final
{
public partial class WebForm2 : System.Web.UI.Page
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["sportsConnectionString2"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("select * from items where id = @p1", con);
cmd.Parameters.AddWithValue("@p1", DropDownList1.SelectedValue);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
TextBox3.Text = rdr["ItemName"].ToString();
TextBox2.Text = rdr["QtyOnHand"].ToString();
TextBox4.Text = rdr["CostPer"].ToString();
TextBox5.Text = rdr["ReorderPoint"].ToString();
rdr.Close();
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("Update Items set ItemName=@p1, QtyOnHand=@p2, ReorderPoint=@p3, CostPer=@p4 where id= @p5", con);
cmd.Parameters.AddWithValue("@p1", TextBox3.Text );
cmd.Parameters.AddWithValue("@p2", TextBox2.Text);
cmd.Parameters.AddWithValue("@p3", TextBox5.Text);
cmd.Parameters.AddWithValue("@p4", TextBox4.Text);
cmd.Parameters.AddWithValue("@p5", DropDownList1.SelectedValue);
con.Open();
int retval = cmd.ExecuteNonQuery();
con.Close();
if (retval > 0)
{
Label4.Text = "Changes Saved";
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace exercise4
{
public partial class Greenville : Form
{
public Greenville()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string cj = textBox1.Text;
label3.Text= "Thank you for entering" + cj;
}
}
}
<file_sep># CH3CaseProblems
teamwork makes the dreamwork
<file_sep>using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Final
{
public partial class Contact : Page
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["sportsConnectionString2"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("select * from items where id = @p1", con);
cmd.Parameters.AddWithValue("@p1", DropDownList1.SelectedValue);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
Label1.Text = rdr["ItemName"].ToString();
TextBox3.Text = "";
TextBox2.Text = DateTime.Now.ToString("MM-dd-yyyy");
rdr.Close();
con.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
string tbdate = TextBox2.Text;
string dbdate = tbdate.Substring(6, 4) + "-" + tbdate.Substring(0, 2) + "-" + tbdate.Substring(3,2);
SqlCommand cmd = new SqlCommand("insert into Issues (itemId,qty,date,userid) values (@p1,@p2,@p3,@p4)", con);
cmd.Parameters.AddWithValue("@p1", DropDownList1.SelectedValue);
cmd.Parameters.AddWithValue("@p2", TextBox3.Text );
cmd.Parameters.AddWithValue("@p3", dbdate);
cmd.Parameters.AddWithValue("@p4", "2");
con.Open();
int retval = cmd.ExecuteNonQuery();
con.Close();
if (retval > 0)
{
Label4.Text = "Record Saved";
}
int dbamt = Convert.ToInt32(TextBox3.Text);
SqlCommand cmd2 = new SqlCommand("Update Items set QtyOnHand = QtyOnHand - " + dbamt + "where id= @p2", con);
cmd2.Parameters.AddWithValue("@p2", DropDownList1.SelectedValue);
con.Open();
int retval2 = cmd2.ExecuteNonQuery();
con.Close();
if (retval2 > 0)
{
Label4.Text = "Changes Saved";
}
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("select * from Supplier where id = @p1", con);
cmd.Parameters.AddWithValue("@p1", DropDownList1.SelectedValue);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
rdr.Read();
rdr.Close();
con.Close();
}
}
}<file_sep># Homework + Inventory management system I made in 2019...
* current interface issues related to master page make it difficult to navigate. Will fix when I get the time
<file_sep>using System.Web.UI;
namespace Final.Account
{
public partial class ResetPasswordConfirmation : Page
{
}
}<file_sep>// TK
// Date: 2/9/18
// Chapter 4 Case Problem 1
// Modified Ch3 case problem with addition of if-else
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 WindowsFormsApp2
{
public partial class Form1 : Form
{
int thisyearnum, ccount=0;
string [,] cont;
public Form1()
{
InitializeComponent();
}
//comparing revenue
private void ResultsButton_Click(object sender, EventArgs e)
{
int conNum1 = Convert.ToInt32(lastYearTextBox.Text);
int conNum2 = Convert.ToInt32(thisYearTextBox.Text);
int lastRev = conNum1 * 25;
int thisRev = conNum2 * 25;
string compMes;
if (conNum1 > 30 || conNum1 < 0)
{
results.Text = "Last year must use a number 0 through 30";
return;
}
if (conNum2 > 30 || conNum1 < 0)
{
results.Text = "This year must use a number 0 through 30";
return;
}
if (conNum2 > (2 * conNum1))
compMes = "Compared to last year, the competition is over twice as large!";
else if (conNum2 > conNum1)
compMes = "The competition is bigger than ever!";
else if (conNum2 < conNum1)
compMes = "A tighter race this year! Come out and cast your vote!";
else
compMes = "The competition is the same as last year.";
this.results.Text = string.Format("With an entrance fee of $25..." +
"\nLast year's revenue was: ${0}" +
"\nand this year's revenue estimate is: ${1}" +
"\n{2}", lastRev, thisRev, compMes);
this.results.Visible = true;
}
//Method buttonclick to display array of person and their talent
private void button2_Click(object sender, EventArgs e)
{
if (textBox3.Text == "X")
{ results.Text="All Done!!";
textBox3.Enabled=false;
return;
}
label5.Text= label8.Text="";
if(textBox3.Text != "S" && textBox3.Text != "D" && textBox3.Text != "M" && textBox3.Text != "O")
{label8.Text="Invalid Entry"; return;}
int cc=0;
while (cc < ccount)
{
if (cont[cc,1]==textBox3.Text)
{
label5.Text=label5.Text+ cont[cc,0]+"\r\n" ;
}
cc=cc+1;
}
}
//Method buttonclick to display what they entered
private void button3_Click(object sender, EventArgs e)
{
label9.Visible = true;
label10.Visible = true;
label9.Text = "You entered " + lastYearTextBox.Text + " for last year";
label10.Text = "You entered " + thisYearTextBox.Text + " for this year";
groupBox1.Visible = true;
}
//Onleave method toy display comparison between this and last year
private void thisYearTextBox_Leave(object sender, EventArgs e)
{
int ly = Convert.ToInt32 (lastYearTextBox.Text);
int ty = Convert.ToInt32 (thisYearTextBox.Text);
thisyearnum=ty;
cont= new string [thisyearnum,2];
if (ly > ty){
label11.Text = "Last year had a bigger turnout";
}
else if (ty > ly){
label11.Text = "This year has more contestants";
}
else {
label11.Text = "We have the same number of contestants";
}
label11.Visible = true;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
// Storing contestants and their talents into an array
private void button1_Click(object sender, EventArgs e)
{
if (ccount < thisyearnum )
{
cont[ccount,0]=textBox1.Text;
cont[ccount,1]=textBox2.Text;
textBox1.Text=textBox2.Text="";
ccount = ccount + 1;
}
else {textBox3.Focus();
}
if (ccount==thisyearnum)
{textBox3.Focus();}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
using System.Web.Configuration;
namespace Final
{
public partial class Inquiry : Page
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["sportsConnectionString2"].ConnectionString);
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
|
9a16949d9d2fa2026089f99d8d3f63e49e4c1bbe
|
[
"Markdown",
"C#"
] | 8 |
C#
|
calejohn5/C_SHARP
|
2c0d1d1dac9ef76ad4a302f439471badc00455e9
|
86b1412b32aec51fb00371cd04b66926159a5d19
|
refs/heads/master
|
<file_sep>import {
Component, OnInit,
OnChanges,AfterContentChecked,
AfterContentInit, AfterViewChecked,
AfterViewInit, DoCheck,
OnDestroy, Input,
ViewChild,
ContentChild,
} from '@angular/core';
@Component({
selector: 'app-life-cycle',
templateUrl: './life-cycle.component.html',
styleUrls: ['./life-cycle.component.css']
})
export class LifeCycleComponent implements
OnInit , OnChanges , AfterViewChecked
,AfterViewInit,DoCheck,OnDestroy,
AfterContentChecked , AfterContentInit{
constructor() { }
a = true;
@Input() bindable = "it is a bindable variable";
@ViewChild('para')
para;
@ContentChild('paraValue')
paraValue : HTMLElement;
check(){
this.a = !this.a;
}
ngOnChanges() {
this.onClick("OnChanges");
}
ngAfterContentChecked() {
this.onClick("AfterContentChecked");
}
ngAfterContentInit() {
this.onClick("AfterContentInit");
console.log("==================")
console.log(this.paraValue);
console.log("==================")
}
ngAfterViewChecked() {
this.onClick("ngAfterViewChecked");
console.log(this.para);
}
ngAfterViewInit() {
this.onClick("ngAfterViewInit");
}
ngOnDestroy() {
this.onClick("ngOnDestroy");
}
ngDoCheck() {
this.onClick("ngDoCheck");
}
ngOnInit() {
this.onClick("ngOnInit");
console.log(this.bindable);
}
private onClick(a : string){
console.log(a);
}
}
<file_sep>import { Component, Input, EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-property-binding',
templateUrl: './property-binding.component.html',
styleUrls: ['./property-binding.component.css']
})
export class PropertyBindingComponent{
constructor() { }
@Input() result : number = 100;
@Input() anyNumber : number = 500;
@Output() clicked = new EventEmitter<string>();
onClicked(){
this.clicked.emit('This is a string');
}
}
<file_sep>import { Component, ViewChild, ElementRef } from '@angular/core';
import { Element } from '@angular/compiler';
// import {PropertyBindingComponent} from '../property-binding/property-binding.component';
@Component({
selector: 'app-data-binding',
templateUrl: './data-binding.component.html',
styleUrls: ['./data-binding.component.css']
})
export class DataBindingComponent {
stringInterpolation = "This is string interpolation!!";
test = "This is test string!!";
boundValue = "new Bindable Valaue";
@ViewChild('newValue')
newValue : ElementRef;
constructor() { }
check() {
return true;
}
result = 200;
anyNumber = 1000;
onClicked(value: string) {
console.log(value);
}
// public ampere = 1;
// public amount = 2000;
// myresult = this.ampere * this.amount;
person = {
name: "Alex",
ampere: 0,
totalAmount: 0
};
onClick() {
console.log(this.person);
console.log(this.newValue.nativeElement.innerHTML);
}
keyDown(e) {
this.person.totalAmount = 2000 * this.person.ampere;
}
}
|
10498022922d6ad5fd95ed2ad0bf24c56b3c5d17
|
[
"TypeScript"
] | 3 |
TypeScript
|
tabishsudofy/dummyProject
|
b5b3a300dc0400a3594c02eea328f6d2c8d63892
|
a819c141b024f7267e238f31b4e60cf4c67a7ad2
|
refs/heads/master
|
<file_sep>import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class WebtableMethod {
public static WebDriver driver;
@Test
public void WebTableAdd(){
System.setProperty("webdriver.chrome.driver", "E:\\CCC\\chromedriver.exe");
System.setProperty("webdriver.chrome.silentOutput", "true");
driver= new ChromeDriver();
driver.get("https://www.w3schools.com/html/html_tables.asp");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//*[@id="customers"]/tbody/tr[2]/td[1]
//*[@id="customers"]/tbody/tr[2]/td[1]
String Before_xpath= "//*[@id=\"customers\"]/tbody/tr[";
String After_xpath= "]/td[1]";
for(int i=2;i<7;i++) {
String name = driver.findElement(By.xpath(Before_xpath+i+After_xpath)).getText();
System.out.println(name);
if(name.contains("shiv")) {
}
}
}
}
|
4ada87e920862c26076c450fac35aa6fb8c9e19f
|
[
"Java"
] | 1 |
Java
|
shiv4577/HandleWebTable
|
9aa8f444de97e3957c6c4b20ff4ee84d6f65b928
|
5b63581769c0ce5f9c69977d76d21e3996f87ac1
|
refs/heads/main
|
<repo_name>Robinmartin321/Slice<file_sep>/slice2/Assets/ThrowObject.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThrowObject : MonoBehaviour
{
public List<GameObject> prefabs;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(1))
{
GameObject prefab = prefabs[Random.Range(0, prefabs.Count - 1)];
GameObject go = Instantiate(prefab, transform.position, transform.rotation);
Rigidbody rigid = go.GetComponent<Rigidbody>();
rigid.AddForce(Vector3.up * 300);
}
}
}
|
4b852a868b26cd40d55ee80b6b652642471e011c
|
[
"C#"
] | 1 |
C#
|
Robinmartin321/Slice
|
d40acd72141573ccdd1f6a12322005f359d94ec0
|
469e1249038480ac8b572fa5a9a7b95ff8b1cad6
|
refs/heads/master
|
<repo_name>dlee67/JavaGUIPractice<file_sep>/JavaGUIDev/UpTil5thTut/ApOrInnit.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class ApOrInnit{
JTextField field = new JTextField(15);
JFrame frame = new JFrame("Apple!Or!Orange!");
JFrame frameApple = new JFrame("apple");
JFrame frameOrange = new JFrame("orange");
ImageIcon apple = new ImageIcon("apple.jpg");
ImageIcon orange = new ImageIcon("orange.jpg");
JLabel appleLabel = new JLabel(apple);
JLabel orangeLabel = new JLabel(orange);
class ActOn implements ActionListener{
public void actionPerformed(ActionEvent e){
if(field.getText().equalsIgnoreCase("apple")){
frameApple.setVisible(true);
}else if(field.getText().equalsIgnoreCase("orange")){
frameOrange.setVisible(true);
}
}
}
public void startUp(){
/*
JFrame frame = new JFrame("Apple!Or!Orange!");
JFrame frameApple = new JFrame("apple");
JFrame frameOrange = new JFrame("orange");
ImageIcon apple = new ImageIcon("apple.jpg");
ImageIcon orange = new ImageIcon("orange.jpg");
JLabel appleLabel = new JLabel(apple);
JLabel orangeLabel = new JLabel(orange);
*/
frame.setLayout(new FlowLayout());
frame.setSize(1000, 1000);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frameOrange.setLayout(new FlowLayout());
frameOrange.setSize(1000, 1000);
frameOrange.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frameOrange.add(orangeLabel);
frameApple.setLayout(new FlowLayout());
frameApple.setSize(1000, 1000);
frameApple.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
frameApple.add(appleLabel);
JButton button = new JButton("Consume");
ActOn act = new ActOn();
button.addActionListener(act);
frame.add(field);
frame.add(button);
frame.setVisible(true);
}
}
/*
class ActOn implements ActionListener{
public void actionPerformed(ActionEvent e){
if(field.getText().equalsIgnoreCase("apple")){
frameApple.setVisible(true);
}else if(field.getText().equalsIgnoreCase("orange")){
frameOrange.setVisible(true);
}
}
}
*/
|
a193827b47e109a9eda7802570cf243a6ff4ffa8
|
[
"Java"
] | 1 |
Java
|
dlee67/JavaGUIPractice
|
6cc132960dab33184dda82bcbeeb6178e5ea5963
|
0878de328b09b6a2eb3c83fbb77d52a91f4baece
|
refs/heads/master
|
<repo_name>Satyam19946/DigitRecognition<file_sep>/README.md
# DigitRecognition
Trying to achieve a 95%+ accuracy on the MNIST Digit Recognition Dataset.
Since you cannot upload a data file bigger than 25 mb. The dataset can be found here - https://www.kaggle.com/c/digit-recognizer/data
<file_sep>/digit.py
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import tensorflow as tf
import os
os.chdir("C:/Users/Satyam/Desktop/Programs/Datasets/Digit_recognition")
training_data = pd.read_csv('train.csv')
test_data = pd.read_csv('test.csv')
def interference(x,weight,bias):
return tf.add(tf.matmul(x,weight),bias)
def evaluate(output, y):
correct_prediction = tf.equal(tf.argmax(output, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
return accuracy
#Splitting the testing data into X and Y.
X_data = training_data.iloc[:20000,1:]
y_data = training_data.iloc[:20000,0]
y_check = training_data.iloc[:20000,0]
x_check = training_data.iloc[10000:,1:]
def modify_y_data(y_data): #Modifies Y to readable code. Like 3 gets converted to [0,0,0,1,0,0,0,0,0,0]
answers = []
for i in range(len(y_data)):
temp = [0.0] * 10
temp[y_data[i]] = 1.0
answers.append(temp)
return answers
y_data = pd.DataFrame(modify_y_data(y_data))
y_check = pd.DataFrame(modify_y_data(y_check))
#Setting the max number of rows to be displayed at each time.
pd.options.display.max_rows = 5
#Some basic stuff
number_of_attributes = len(X_data.columns)
number_of_samples = len(X_data)
X = tf.placeholder(dtype = tf.float32, shape = [None,number_of_attributes])
y_true = tf.placeholder(dtype = tf.float32, shape = [None,10])
weights1 = tf.Variable(tf.random_normal([number_of_attributes,25],stddev=0.5),name = 'weights1') #connecting layer1 to layer2
bias1 = tf.Variable(tf.zeros(1),name = 'bias1') #bias in the first layer
weights2 = tf.Variable(tf.random_normal([25,10], stddev = 0.5),name = 'weights2') #connecting layer2 to layer3
bias2 = tf.Variable(tf.zeros(1),name = 'bias2') #bias in second layer.
layer2 = interference(X,weights1,bias1)
layer2 = tf.sigmoid(layer2)
layer3 = interference(layer2,weights2,bias2)
y_predict = tf.sigmoid(layer3)
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y_true,logits = y_predict))
learning_rate = 3.0
optimizer = tf.train.GradientDescentOptimizer(learning_rate)
train = optimizer.minimize(loss)
eval_op = evaluate(y_predict,y_true)
losses = []
accuracies = []
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
dict = {X:X_data,y_true:y_data}
for i in range(200):
output = sess.run(loss,feed_dict = dict)
sess.run(train,feed_dict = dict)
print("Loss = ", output)
losses.append(output)
acc = sess.run(eval_op,feed_dict = dict)
print("Accuracy = ",acc)
accuracies.append(acc)
plt.subplot(1,2,1)
plt.plot(losses)
plt.ylabel("Loss")
plt.xlabel("Number of Epochs")
plt.subplot(1,2,2)
plt.plot(accuracies)
plt.ylabel("Accuracy")
plt.xlabel("Number of Epochs")
|
20dc2bd956a6b235667e218ee3f4e88974b7278f
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
Satyam19946/DigitRecognition
|
7d7aec619cb0798df86a7975621c96338c25d50e
|
16941a8bda9754ae36327f765b791d293bc3352a
|
refs/heads/master
|
<file_sep>// AOS
AOS.init({
duration: 1000,
})
jQuery(document).ready(function($){
'use strict';
// Animsition
$(".animsition").animsition();
// Scrollax
$.Scrollax();
// Smooth scroll
var $root = $('html, body');
$('a.js-smoothscroll[href^="#"]').click(function () {
$root.animate({
scrollTop: $( $.attr(this, 'href') ).offset().top - 40
}, 500);
return false;
});
// Owl
$('.wide-slider').owlCarousel({
loop:true,
autoplay: true,
margin:10,
animateOut: 'fadeOut',
animateIn: 'fadeIn',
nav:true,
autoplayHoverPause: false,
items: 1,
autoheight: true,
navText : ["<span class='ion-chevron-left'></span>","<span class='ion-chevron-right'></span>"],
responsive:{
0:{
items:1,
nav:false
},
600:{
items:1,
nav:false
},
1000:{
items:1,
nav:true
}
}
});
// Show menu
if ($(window).width() > 768 ) {
$('body').removeClass('menu-open');
$('.js-templateux-menu').css('display', 'block');
}
// Window Resize
$(window).resize(function(){
var $this = $(this);
$('.js-templateux-menu li').removeClass('staggard');
$('.js-toggle-menu').removeClass('is-active');
if ($this.width() > 768 ) {
$('body').removeClass('menu-open');
$('.js-templateux-menu').css('display', 'block');
} else {
if ($this.width() < 768 ) {
$('.js-templateux-menu').css('display', 'none');
}
}
});
// Hamburger Button
$('.js-toggle-menu').on('click', function(e){
e.preventDefault();
var $this = $(this);
if ($('body').hasClass('menu-open')) {
updateNavColors(isStickyNav());
$this.removeClass('is-active');
$('body').removeClass('menu-open');
$('.js-templateux-menu li').removeClass('staggard');
} else {
updateNavColors(true);
$this.addClass('is-active');
$('body').addClass('menu-open');
$('.js-templateux-menu li').each(function(k){
var $this = $(this);
setTimeout(function(){
$this.addClass('staggard');
}, 100 * k );
});
}
if ( $('.templateux-menu').is(':visible') ) {
$('.js-templateux-menu').fadeOut(300);
} else {
$('.js-templateux-menu').fadeIn(300);
}
})
});
// Copy to clipboard
function copyToClipboard(element) {
var $temp = $('<input>');
$('body').append($temp);
$temp.val($(element).text()).select();
document.execCommand('copy');
$temp.remove();
}
$('#copyEmail').click(function() {
$('#copiedAlert').css('display', 'block');
$('#copiedAlert').delay(1000).fadeOut(300)
});
// Smooth Scroll
$('#logo').click(function() {
$('html, body').animate({
scrollTop: $('#navbar').offset().top
}, 500);
});
$('#portfolioNav').click(function() {
if (isHomepage()) {
event.preventDefault();
}
$('html, body').animate({
scrollTop: $('#portfolioSection').offset().top
}, 500);
$('.js-toggle-menu').removeClass('is-active');
$('body').removeClass('menu-open');
$('.js-templateux-menu li').removeClass('staggard');
function mediaQuery(x) {
if (x.matches) {
$('.js-templateux-menu').fadeOut(300);
}
}
var x = window.matchMedia('(max-width: 768px)')
mediaQuery(x)
x.addListener(mediaQuery)
});
$('#contactNav').click(function() {
if (isHomepage()) {
event.preventDefault();
}
$('html, body').animate({
scrollTop: $('#contactSection').offset().top
}, 1000);
$('.js-toggle-menu').removeClass('is-active');
$('body').removeClass('menu-open');
$('.js-templateux-menu li').removeClass('staggard');
function mediaQuery(x) {
if (x.matches) {
$('.js-templateux-menu').fadeOut(300);
}
}
var x = window.matchMedia('(max-width: 768px)')
mediaQuery(x)
x.addListener(mediaQuery)
});
$('#resumeNav').click(function() {
function mediaQuery(x) {
if (x.matches) {
$('.js-templateux-menu').fadeOut(300);
}
}
var x = window.matchMedia('(max-width: 768px)')
mediaQuery(x)
x.addListener(mediaQuery)
});
function isStickyNav() {
return window.pageYOffset > sticky;
}
function updateNavColors(sticky) {
if (sticky) {
$('#logo img').attr('src','images/logo_rose-gold.svg');
$('.templateux-menu a').css('color', '#c99297');
$('.hamburger-inner').addClass('changed');
} else {
$('#logo img').attr('src','images/logo_white.svg');
$('.templateux-menu a').css('color', '#f4efea');
$('.hamburger-inner').removeClass('changed');
}
}
// Sticky Nav
window.onscroll = function() {stickyNav()};
var navbar = document.getElementById('navbar');
var sticky = navbar.offsetTop;
$('#navbarBG').hide();
function stickyNav() {
if (isStickyNav() || ($('body').hasClass('menu-open'))) {
navbar.classList.add('sticky')
$('#navbarBG').fadeIn();
updateNavColors(true);
} else {
navbar.classList.remove('sticky');
$('#navbarBG').fadeOut();
updateNavColors(false);
}
}
// Homepage Function
function isHomepage() {
return $('body').hasClass('home-page');
}
// Hide cohen class on mobile view
function mediaQuery(x) {
if (x.matches) {
$('#cocoenHideMobile').removeClass('cocoen');
} else {
$('#cocoenHideMobile').addClass('cocoen');
}
}
var x = window.matchMedia('(max-width: 768px)')
mediaQuery(x)
x.addListener(mediaQuery)
<file_sep>
function passWord() {
var testV = 1;
var pass1 = prompt('Please Enter Your Password', ' ');
var projects = document.getElementById('projects');
var bodyBackground = document.getElementById('bodyBackground');
var button = document.getElementById('button');
var about = document.getElementById('about');
while (testV < 3) {
if (!pass1)
history.go(-1);
if (pass1.toLowerCase() == "<PASSWORD>!") {
alert('You can now view Jannon\'\s projects');
// window.open('protectpage.html');
projects.classList.remove('hide');
bodyBackground.classList.remove('body-background');
about.classList.add('new-background');
button.classList.add('hide');
break;
}
testV += 1;
var pass1 =
prompt('Access Denied - Password Incorrect, Please Try Again.', 'Password');
}
if (pass1.toLowerCase() != "password" & testV == 3)
history.go(-1);
return " ";
}
// Icon hover effect
$(document).ready(function () {
$("#resume").hover(
function () {
$("#resumeIcon").removeClass("material-icons").addClass("material-icons-outlined");
},
function () {
$("#resumeIcon").removeClass("material-icons-outlined").addClass("material-icons");
}
);
$("#email").hover(
function () {
$("#emailIcon").removeClass("material-icons").addClass("material-icons-outlined");
},
function () {
$("#emailIcon").removeClass("material-icons-outlined").addClass("material-icons");
}
);
});
// Lightbox
// House rules functions
$(document).ready(function () {
$("#houseRulesClosed").click(function () {
$("#houseRulesOpened").removeClass("hide");
$("#houseRulesOpened .lightbox_content").scrollTop(0);
});
// $(".project-name").click(function () {
// $("#houseRulesOpened").removeClass("hide");
// $("#houseRulesOpened .lightbox_content").scrollTop(0);
// });
$(".close").click(function () {
$("#houseRulesOpened").addClass("hide");
});
$(".back-to-projects").click(function () {
$("#houseRulesOpened").addClass("hide");
});
});
// Decline flow functions
$(document).ready(function () {
$("#declineFlowClosed").click(function () {
$("#declineFlowOpened").removeClass("hide");
$("#declineFlowOpened .lightbox_content").scrollTop(0);
});
// $(".project-name").click(function () {
// $("#declineFlowOpened").removeClass("hide");
// $("#declineFlowOpened .lightbox_content").scrollTop(0);
// });
$(".close").click(function () {
$("#declineFlowOpened").addClass("hide");
});
$(".back-to-projects").click(function () {
$("#declineFlowOpened").addClass("hide");
});
});
// Cancel change functions
$(document).ready(function () {
$("#cancelChangeClosed").click(function () {
$("#cancelChangeOpened").removeClass("hide");
$("#cancelChangeOpened .lightbox_content").scrollTop(0);
});
// $(".project-name").click(function () {
// $("#cancelChangeOpened").removeClass("hide");
// $("#cancelChangeOpened .lightbox_content").scrollTop(0);
// });
$(".close").click(function () {
$("#cancelChangeOpened").addClass("hide");
});
$(".back-to-projects").click(function () {
$("#cancelChangeOpened").addClass("hide");
});
});
// Inbox functions
$(document).ready(function () {
$("#inboxClosed").click(function () {
$("#inboxOpened").removeClass("hide");
$("#inboxOpened .lightbox_content").scrollTop(0);
});
// $(".project-name").click(function () {
// $("#inboxOpened").removeClass("hide");
// $("#inboxOpened .lightbox_content").scrollTop(0);
// });
$(".close").click(function () {
$("#inboxOpened").addClass("hide");
});
$(".back-to-projects").click(function () {
$("#inboxOpened").addClass("hide");
});
});
// Flow Builder functions
$(document).ready(function () {
$("#flowBuilderClosed").click(function () {
$("#flowBuilderOpened").removeClass("hide");
$("#flowBuilderOpened .lightbox_content").scrollTop(0);
});
// $(".project-name").click(function () {
// $("#flowBuilderOpened").removeClass("hide");
// $("#flowBuilderOpened .lightbox_content").scrollTop(0);
// });
$(".close").click(function () {
$("#flowBuilderOpened").addClass("hide");
});
$(".back-to-projects").click(function () {
$("#flowBuilderOpened").addClass("hide");
});
});
// Variant functions
$(document).ready(function () {
$("#variantClosed").click(function () {
$("#variantOpened").removeClass("hide");
$("#variantOpened .lightbox_content").scrollTop(0);
});
// $(".project-name").click(function () {
// $("#variantOpened").removeClass("hide");
// $("#variantOpened .lightbox_content").scrollTop(0);
// });
$(".close").click(function () {
$("#variantOpened").addClass("hide");
});
$(".back-to-projects").click(function () {
$("#variantOpened").addClass("hide");
});
});<file_sep>
// House rules functions
$(document).ready(function(){
$("#houseRulesClosed").click(function() {
$("#houseRulesOpened").removeClass("hide");
});
$(".close").click(function() {
$("#houseRulesOpened").addClass("hide");
});
});
// Decline flow functions
$(document).ready(function(){
$("#declineFlowClosed").click(function() {
$("#declineFlowOpened").removeClass("hide");
});
$(".close").click(function() {
$("#declineFlowOpened").addClass("hide");
});
});
// Cancel change functions
$(document).ready(function(){
$("#cancelChangeClosed").click(function() {
$("#cancelChangeOpened").removeClass("hide");
});
$(".close").click(function() {
$("#cancelChangeOpened").addClass("hide");
});
});
// Inbox functions
$(document).ready(function(){
$("#inboxClosed").click(function() {
$("#inboxOpened").removeClass("hide");
});
$(".close").click(function() {
$("#inboxOpened").addClass("hide");
});
});<file_sep># My Portfolio
### Local Development
```bash
npm start
```
|
2f19dc90c4cc28d9a746f6e4b6ca49245acf1db1
|
[
"JavaScript",
"Markdown"
] | 4 |
JavaScript
|
daebrr/jannonjeffries
|
a665ce15a006308f4b0236eebe9a28929e0ae981
|
42a9e0b09c72e5629e35307808fd5d247647fb5e
|
refs/heads/master
|
<file_sep>"use strict";
function validateForm() {
var uname = document.forms["myForm"]["uname"];
var age = document.forms["myForm"]["age"];
var residentStatus = document.forms["myForm"]["residency"];
var accountType = document.querySelectorAll('input[name=acctype]:checked');
var nationality = document.forms["myForm"]["nationality"];
var regxName = /^([a-zA-Z]+)$/;
if (uname.value.length < 6) {
alert("The username needs to be at least 6 characters long");
uname.focus();
return false;
}
if(!regxName.test(uname.value)){
uname.style.border = "solid 2px red";
document.getElementById('unameLabel').innerHTML = 'The name can only have alphabets';
document.getElementById('unameLabel').style.visibility = 'visible'; return false;
} else{
uname.style.border = "solid 2px green";
document.getElementById('unameLabel').innerHTML = 'The username is valid!';
document.getElementById('unameLabel').style.color = 'green';
document.getElementById('unameLabel').style.visibility='visible';
}
if(age.value < 18) {
alert("You must be at least 18 years old to open an account");
return false;
}
if(accountType.length == 0) {
document.querySelectorAll('input[name=acctype]')[1].checked = true;
}
confirm("Do you want to subbmit the form");
return true;
}<file_sep>"use strict";
let items = [
{ name: "meat", price: 25 },
{ name: "vegetables", price: 17 },
{ name: "cake", price: 20 },
{ name: "drinks", price: 38}
];
let prices = [];
for (let item of items) {
prices.push(item.price);
}
console.log("Price list using for loop : " + prices);
let priceList = items.map(function(item) {
return item.price;
});
console.log("Price list after mapping : " + priceList);
priceList = items.map(item => item.price);
console.log("Price list after mapping (with ES6 syntax): " + priceList);
let total = 0;
for (let item of items) {
total += item.price;
}
console.log("Total cost of items (for loop) : " + total);
let totalReducer = items.reduce((sum,item) => sum + item.price, 0);
console.log("Total cost of items (reduce) : " + totalReducer);
let expensiveItems = items.filter(item => item.price >= 25);
console.log("The expensive items are: ", expensiveItems);
let costExpensiveItems = expensiveItems.reduce((sum, item) => sum + item.price, 0);
console.log("The total cost of the expensive items: ", costExpensiveItems);
const values = [3, 1, 3, 5, 2, 4, 4, 4];
const setOfValues = new Set(values);
const uniqueValues = [...setOfValues];
console.log("Unique elements of the array : " + uniqueValues);<file_sep>"use strict";
function animation() {
var dot = document.getElementById("circle");
var loc = 450;
var time = setInterval(frame, 10);
function frame() {
if (loc == 0) {
clearInterval(time);
} else {
loc--;
dot.style.top = loc + "px";
dot.style.right = loc + "px";
}
}
}<file_sep>"use strict";
/*console.log("while loops");
//console.log("Integers from 1 to 10 : ");
let i = 1;
while(i<= 10) {
console.log(i);
i++;
}
console.log("Even integers from 1 to 20 : ");
i = 1;
while(i <= 20) {
let num = i%2 ;
if(num==0) {
console.log(i);
}
i++;
}
console.log("Increasing order of series (with break) : ")
i = 1;
while(i <=10) {
console.log(i);
i++;
if(i == 5) {
break;
}
}
console.log("Decreasing order of the series (with continue) : ")
i = 11;
while(i > 1) {
i--;
if(i == 5) {
continue;
}
console.log(i);
}
console.log("Do-while loops : ");
let factorial = 1;
let n = 5;
let i = 1;
do {
factorial *= i;
i++;
}
while(i <= n);
console.log("Factorial of " + n + " = " + factorial);*/
console.log("Fibonacci series using for loop : ");
let a = 0, b = 1, c;
let count = 10;
for (let i = 3; i <= count; i++) {
c = a + b;
a = b;
b = c;
console.log(c);
}<file_sep>function getterSetterData() {
var myVar = 1;
return {
getVar: function() {
return myVar;
},
setVar: function(v) {
myVar=v;
}
};
}
let objVar = getterSetterData();
console.log("Initial value of myVar: ", objVar.getVar())
objVar.setVar(2);
console.log("Updated numeric value of myVar: ", objVar.getVar());
<file_sep><!DOCTYPE html>
<html lang="en-US">
<head>
<title>Article, Aside, Section</title>
<style>
header {
background-color: rgb(125,18,67);
color: white;
border: 1px solid black;
padding: 10px;
text-align:center;
}
footer {
background-color: black;
color: white;
text-align:center;
}
summary{
font-style: italic;
}
detail {
text-align: center;
font-size: .65em;
font-style: italic;
display:block;
}
article{
font-family: Arial;
}
#intro {
font-weight: bold;
}
aside
{
font-size: .75em;
width: 200px;
border: 1px solid black;
}
figure {
width: 300px;
float: left;
}
nav
{
width: 250px;
float: left;
}
nav ul li
{
list-style-type: none;
border: 1px solid black;
background-color: rgb(152, 29, 180);
color: white;
padding: 5px;
}
</style>
</head>
<body>
<header><h1>News from Connecticut</h1></header>
<nav>
<ul>
<li>About the State</li>
<li>Contact the Governor</li>
<li>More Connecticut News</li>
</ul>
</nav>
<article>
<section id="intro">
<h1>Main News</h1>
<summary>vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.</summary>
</section>
<p>
<figure>
<img src="maloy.jfif"/>
<figcaption><NAME></figcaption>
</figure>
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.</p>
<detail>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.</detail> <br />
<detail>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.</detail>
</article>
<aside>
<h2>Points to Remember</h2>
<ul>
<li>Dogs are great and sensitive</li>
<li>Cats are very good too</li>
<li>Rats are like AJ</li>
<li>Ajay eshay adlay</li>
</ul>
</aside>
<footer>Copyright fuck ya | No rights in Aus</footer>
</body>
</html>
<file_sep>"use strict";
console.log("Highest number from the list: ", Math.max(10, 100, -200, 50));
console.log("Lowest number from the list: ", Math.min(10, 100, -200, 50));<file_sep>"use strict";
class Vehicle{
constructor(make, model, price){
this.make = make;
this.model = model;
this.price = price;
}
}
let myCar = new Vehicle("Volkswagen", "GTI", 29000);
let yourCar = JSON.parse(JSON.stringify(myCar));
let herCar = {...myCar};
let hisCar = Object.create(myCar);
console.log("Is myCar a Vehicle? ",myCar instanceof Vehicle);<file_sep>function changeStyle(p){
document.getElementById(p).style.color=
document.getElementById("p1").style.color;
}<file_sep>document.write("Hello world! This message is from the JS file!")
console.log("Hello world! THis message is from the JS file and meant for the console!");<file_sep>"use strict";
function demo(x) {
var answer = 0;
try{
let scores = [4,9,6,5,7];
answer = scores[x];
} catch{
answer = "Invalid data!";
} finally {
document.getElementById("p3").innerHTML =
'Finally will always execute!';
}
document.getElementById("p2").innerHTML = answer;
}
<file_sep>"use strict";
console.log("A random value between 0 and 1: ", Math.random());
console.log("Random integer between 0 and 9: ", Math.floor(Math.random() * 10));
console.log("Random integer between 0 and 10: ", Math.floor(Math.random() * 11));<file_sep>document.getElementById("numericsection").innerHTML = 30;
document.getElementById("textsection").innerHTML = "Name: John";
var a;
a = 10;
var b, c;
b = c = 20;
x = a + 30;
console.log("Value of a : " + a);
console.log("Value of b : " + b);
console.log("Value of c : " + c);
console.log("Value of x : " + x);
y = b * c;
console.log("Value of y : " + y);
StudentName="Brianna";
studentName="John";
student_name="David;"
console.log("Value of Uppercase Name: " + StudentName);
console.log("Value of Uppercase Name: " + studentName);
console.log("Value of Uppercase Name: " + student_name);
singleQuoteString = 'Declared within single quotes';
backtickString=`Declared within back ticks`;
console.log('The singleQuoteString : %s', singleQuoteString);
console.log(`The backtickString : ${backtickString}`);
<file_sep>var decCount = 0;
window.onload = function() {
var incButton = document.getElementById("incButton");
var incCount = 0;
var decButton = document.getElementById("decButton");
decButton.onclick = countDec;
incButton.onclick = function() {
incCount++;
var incCountMessage = document.getElementById("incCount");
incCountMessage.innerHTML = " Increment Counter = " + incCount;
}
}
function countDec() {
decCount--;
var decCountMessage = document.getElementById("decCount");
decCountMessage.innerHTML = "Decrement counter = " + decCount;
}<file_sep>const PI = 3
function Circle(r) {
this.radius =r;
}
let getAreaFirst = function(circle) {
console.log("Inside getAreaFirst");
console.log("Area of circle: ",PI * circle.radius * circle.radius);
}
let firstCircle = new Circle(10);
function innerFunction() {
const PI = 3.1;
let getAreaSecond = function(circle){
console.log("Inside getAreaSecond");
console.log("Area of circle: ", PI * circle.radius * circle.radius);
}
let getAreaThird = function(circle) {
const PI = 3.14;
console.log("Inside getAreaThird");
console.log("Area of circle: ", PI * circle.radius * circle.radius);
}
getCircumreference = function(circle) {
console.log("Inside getCircumreference");
console.log("Circumreference of circle: ", 2 * PI * circle.radius);
}
let secondCircle = new Circle(20);
console.log("innerFunction: Calling the functions with firstCircle: ");
getAreaFirst(firstCircle);
getAreaSecond(firstCircle);
getCircumreference(firstCircle);
getAreaThird(firstCircle);
console.log("innerFuction: Calling the functions with secondCircle: ");
getAreaFirst(secondCircle);
getAreaSecond(firstCircle);
getCircumreference(firstCircle);
getAreaThird(firstCircle);
}
innerFunction();<file_sep>"use strict";
function Car(make, model, price, engine) {
this.make = make;
this.model = model;
this.price = price;
this.engine = engine;
}
let s60Engine = {
cylinders: 4,
displacement: 2000,
horsepower: 250
}
let myCar = new Car("Volvo", "S60", 42000, s60Engine);
console.log(`My car is a ${myCar.make} ${myCar.model}`);
let caymanEngine = {
cylinders: 4,
displacement: 2500,
horsepower: 350
}
let yourCar = new Car("Porsche", "718 Cayman", 61000, caymanEngine);
console.log(`Your car is a ${yourCar.make} ${yourCar.model}`);
function Car(make, model, price, engine){
this.make = make;
this.model = model;
this.price = price;
this.engine = engine;
this.details = function(){
console.log(` Make: ${this.make}
Model: ${this.model}
Price: $${this.price}`);
};
this.engine.details = function() {
console.log(` Displacement: ${this.displacement}cc
Horsepower: ${this.horsepower}bhp`);
}
};
myCar = new Car("Volvo", "S60", 42000, s60Engine);
console.log("My car details: \n");
myCar.details();
console.log("My engine details: \n");
myCar.engine.details();
class Vehicle{
constructor(make, model, price, engine){
this.make = make;
this.model = model;
this.price = price;
this.engine = engine;
}
details = function(){
console.log(` Make: ${this.make}
Model: ${this.model}
Price: $${this.price}`);
};
};
myCar = new Vehicle("Volva", "S60", 42000, s60Engine);
console.log("My vehicle details: \n");
myCar.details();
<file_sep>"use strict";
console.log("Comparison operators")
let intValue = 70;
let stringValue = "70";<file_sep>$(document).ready(function(){
$("#p1").on("mouseenter mouseleave",function(){
console.log("You have just entered p1");
})
});<file_sep>$(document).ready(function(){
$("#bbb").hide();
$("#cb").change(function(){
if(this.checked){
$("#bbb").show();
}else{
$("#bbb").hide();
}
});
});<file_sep>"use strict";
let studentGrades = ["A", "B", 3, "D", 5];
/*
console.log("Length : " + studentGrades.length );
console.log("Element at index 3: ", studentGrades[3]);
console.log("Element at index -3: ", studentGrades[-3]);*/
var i;
/*console.log("Iterating over elements with the old syntax : \n");
for(i=0; i<studentGrades.length; i++) {
console.log(studentGrades [i]);
}
console.log("Iterating over elements with the ES6 syntax : \n");
for (i of studentGrades) {
console.log(i);
}*/
/*console.log("Elements in vowels :");
let vowels = new Array("A", "E", "I", "O", "U");
for(i of vowels) {
console.log(i);
}*/
/*let grades =[];
grades[0] = "A";
grades[1] = "B";
grades[2] = "C";
grades[3] = "D";
grades[4] = "E";
console.log("Length : ", grades.length);
console.log("Elements in the grades array: \n");
for(i of grades) {
console.log(i);
}*/
let testScore =[43, 64, 81, 91, 39, 73];
function flagGoodScore(score){
if (score>70){
console.log(`The score of ${score} is good!`);
}
}
console.log("Iterating over the text scores with forEach: ");
testScore.forEach(flagGoodScore);
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Form Input Attribute</title>
</head>
<body>
<form action="formprocess.php" id="personalinfo">
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname"><br>
Telephone: <input type="tel" name="telno"><br>
<input type="submit" value="Submit">
</form>
Email: <input type="email" name="email" form="personalinfo otherinfo"><br>
</body>
</html><file_sep>"use strict";
"use strict";
function Patient(id, name, address, bloodGroup) {
this.id = id;
this.name = name;
var _address = address;
var _bloodGroup = bloodGroup;
this.printDetails = function() {
console.log(`The patient details are:
Patient ID: ${this.id}
Name: ${this.name}
Address: ${_address}
Blood Group: ${_bloodGroup}`)
}
}
var firstPatient = new Patient(12, "<NAME>", "Asheville", "B+");
/*console.log("The details for firstPatient");
console.log("The object: ", firstPatient);
console.log("ID is %s and the name is %s ", firstPatient.id, firstPatient.name);
console.log("From the outside, the address is %s and the blood group %s ", firstPatient._address, firstPatient._bloodGroup);
console.log("The invocation of printDetails gives us:");
firstPatient.printDetails()*/
var secondPatient = new Patient(12, "<NAME>", "Madison", "A-");
console.log("The details for secondPatient");
console.log("The object: ", secondPatient);
console.log("The invocation of printDetails gives us:");
secondPatient.printDetails()
firstPatient.name = "<NAME>";
console.log("The invocation of printDetails after updating the gives us:");
firstPatient.printDetails()<file_sep>"use strict";
var myCar = {
make: "Volvo",
model: "S60",
price: 42000,
color: "Grey",
seats: {
material: "Leather",
color: "Brown"
}
}
//console.log("My car: ", myCar);
var yourCar = myCar;
//console.log("Your car: ", yourCar);
yourCar.tyres = "Pirelli";
yourCar.seats.color = "Grey";
//console.log("Your car: ", yourCar);
//console.log("My car: ", myCar);
var hisCar = Object.assign({}, myCar);
hisCar.color = "Red";
hisCar.seats.color = "Neon Green";
//console.log("The effect of Object.assign():");
//console.log("His car ", hisCar);
//console.log("My car: ", myCar);
var herCar = {...myCar};
//console.log("Her car: ", herCar);
herCar.seats.color = "Black";
//console.log("The effect of the spread syntax:");
//console.log("Her car: ", herCar);
//console.log("My car: ", myCar);
myCar ={
make: "Volva",
model: "S60",
price: 42000,
color: "Grey",
seats: {
material: "Leather",
color: "Brown"
}
}
yourCar = JSON.parse(JSON.stringify(myCar));
yourCar.tyres = "Pirelli";
yourCar.seats.color = "Purple";
console.log("The effect of JSON.parse() and JSON.stringify();");
console.log("Your car: ", yourCar);
console.log("My car: ", myCar);<file_sep><?php
$ok = move_uploaded_file($_FILES['file']['tmp_name'], 'http://localhost/formpic/upload/' . $_FILES['file']['name']);
// This message will be passed to the browser
echo $_FILES['file']['name']; echo $ok ? " uploaded successfully!?" : " upload failed!";
?><file_sep>"use strict";
/*
console.log("Is this == window?", this ===window);
console.log("What is this? ", this);
var age = 35;
console.log("window.age: ", window.age);
console.log("this.age: ", this.age);
this.age = 55;
console.log("window.age : ", window.age);
console.log("age: ", age);
let someFunction = () => this;
console.log("this returned from a function: ", someFunction());
let myCar = {
make: "Volvo",
model : "560",
price : 40000,
printDetails(){
console.log(`
Make: ${this.make}
Model: ${this.model}
Price: $${this.price}`);
},
engine : {
cylinders: 4,
displacement: 2000,
kW: 250,
printDetails() {
console.log(`
Displacement: ${this.displacement}cc
kW: ${this.kW}bhp`)
}
}
};
console.log("The fields of myCar:");
myCar.printDetails();
console.log("Engine details: \n");
myCar.engine.printDetails();*/
let myCar = {
make: "Volvo",
model : "560",
price : 40000,
engine : {
cylinders : 4,
displacement : 2000,
horsepower : 250,
}
};
function printCarDetails(){
console.log(` Make: ${this.make}
Model: ${this.model}
Price: $${this.price}`);
}
function printEngineDetails(){
console.log(` Displacement: ${this.displacement}cc
Horsepower: ${this.horsepower}bhp`);
}
console.log("Car details: \n");
printCarDetails.call(myCar);
console.log("Engine details: \n");
printEngineDetails.call(myCar.engine);
let yourCar = {
make : "Porsche",
model : "718 Cayman",
price : 61000,
engine : {
cylinders : 4,
displacement : 2500,
horsepower : 350,
}
};
console.log("Your car details: \n");
printCarDetails.call(yourCar);
console.log("Your engine details: \n");
printEngineDetails.call(yourCar.engine);<file_sep>"use strict";
const imgURL = "https://www.pexels.com/photo/adventure-alps-cold-dawn-326119/"
let fetchImage = async () => {
var myImageResponse = await fetch(imgURL);
console.log("Image response: \n", myImageResponse.blob());
}<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body bgcolor ="#d3d3d3">
<h2>HTML Forms</h2>
<form name="myForm" action = "../form.html" onsubmit="return validateForm()">
<h3>Registration form</h3>
Username : <input type = "text" placeholder = "Your username"
name = "uname">
<label id = "unameLabel" style="color: red; visibility : hidden;">
Username should have a minimum of 6 characters</label><br>
<br><br>
Age: <input type ="number" name = "age" required><br><br>
Residency : <input type = "radio" name = "residency" value ="residant" checked>Resident
<input type = "radio" name="residency" value = "residant">Non-resident
<br><br>
Select account : <input type ="checkbox" name = "acctype" value ="savings">
Savings
<input type = "checkbox" name ="acctype" value = "checking" checked>Checking
<input type ="checkbox" name ="acctype" value ="mmarket">Money Market
<br><br>
Nationality : <select id ="nationality">
<option value ="1">Australia</option>
<option value ="2">Canada</option>
<option value ="3">Germany</option>
<option value ="4" Selected>India</option>
<option value ="5">Kenya</option>
<option value ="6">USA</option>
</select>
<br><br>
<input type ="submit" name="forms" value="Submit">
<input type ="reset" name ="forms" value ="Reset">
</form>
<script src ="JSformsvalidation.js"></script>
</body>
</body>
</html><file_sep><html>
<body>
Thank you!<br>
You Selected: <?php echo $_GET["car"];?><br>
</body>
</html><file_sep>"use strict";
window.onload = function() {
var openButton = document.getElementById("openButton");
var closeButton = document.getElementById("closeButton");
var historyButton = document.getElementById("historyButton");
var newWindow = null;
openButton.onclick = function() {
newWindow = window.open("https://skillsoft.com/");
}
closeButton.onlick = function() {
if(newWindow != null) {
newWindow.close();
}
}
historyButton.onclick = function() {
var browserHistory = document.getElementById("history");
browserHistory.innerHTML = "Your browser window history has " +
window.history.length + " entries!";
}
wikipediaButton.onclick = function() {
window.location = "https://www.wikipedia.org/";
}
}<file_sep>"use strict";
function Student(name) {
this.name = name;
thisavgScore = (scoreArray) =>
scoreArray.reduce((a,b) => a+b) / scoreArray.length;
}
var heidi = new Student("Heidi");
var ralf = new Student("Ralf");
console.log("The avgScore for each student: ");
console.log("Heidi: ", heidi.avgScore([64, 78, 59]));
console.log("Ralf: ", ralf.avgScore([85, 70, 67]));
console.log("\nWhat do the Student objects contain?: ");
console.log("Heidi: ", heidi);
console.log("Ralf: ", ralf);
function StudentProto(name){
this.name = name;
StudentProto.prototype.avgScore = (scoreArray) =>
scoreArray.reduce((a,b)=> a+b)/scoreArray.length;
}
heidi = new StudentProto("Heidi");
ralf = new StudentProto("Ralf");
console.log("\nThe avgScore for each student (proto): ");
console.log("Heidi: ", heidi.avgScore([64, 78, 59]));
console.log("Ralf: ", ralf.avgScore([85, 70, 67]));
<file_sep>"use strict";
let firstItem = {id: 1, name: "laptop", price: 500};
let secondItem = {id: 2, name: "watch", price: 240, brand: "Sonical"};
console.log(`firstItem has a name of ${firstItem.name} and a price of ${firstItem.price}. `);
console.log(`secondItem has a name of ${secondItem["name"]} and a price of ${secondItem["price"]} and its brand is ${secondItem["brand"]}. `);
console.log(`The brand of firstItem is ${firstItem.brand} while that of secondItem is ${secondItem.brand}`);
const USD_EUR = 0.9;
let thirdItem = {id: 3,
name: "headphones",
brand: "Sonical",
price: 84,
priceEUR: this.price * USD_EUR};
console.log("Price of thirdItem in Euros: ", thirdItem.priceEUR);
thirdItem = {id: 3,
name: "headphones",
brand: "Sonical",
price: 84,
priceEUR: function(){ return this.price * USD_EUR;}};
console.log("Price of thirdItem in Euros: ", thirdItem.priceEUR());
thirdItem = {id: 3,
name: "headphones",
brand: "Sonical",
price: 84,
priceEUR() { return this.price * USD_EUR; }};
console.log("Price of ES6 thirdItem in Euros: ", thirdItem.priceEUR());
thirdItem.mfCountry = "Canada";
console.log("The thirdItem is: ", thirdItem);
let fourthItem = new Object();
fourthItem.id = 4;
fourthItem.name = "cell phone";
fourthItem.price = 450;
console.log("The fourthItem is: ", fourthItem);
delete fourthItem.price;
console.log("The fourthItem is: ", fourthItem);<file_sep>function byTagNames(){
let tagNames = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = tagNames[0].innerHTML;
}
function changeP2(){
document.getElementsById("p2").innerHTML=document.getElementsById("p1").firstChild.nodeValue;
}<file_sep>alert("Welcome to our website!");<file_sep>function validateForm() {
var uname = document.forms["myForm"]["uname"].value;
var age = document.forms["myForm"]["age"].value;
var residentStatus = document.forms["myForm"]["residency"].value;
var accountType = document.querySelectorAll('input[name=acctype]:checked');
var nationality = document.forms["myForm"]["nationality"].value;
if (uname.length < 6) {
alert("The username needs to be at least 6 characters long");
return false;
}else {
var selectedAccounts =[];
for (let i=0; i < accountType.length; i++) {
selectedAccounts.push(accountType[i].value);
}
var alertMsg = "The details supplied: " +
"\nUsername:" + uname +
"\nAge: " + age +
"\nResident status: " + residentStatus +
"\nAccounts selected: " + selectedAccounts +
"\nNationality index: " + nationality;
alert(alertMsg);
return true;
}
}
|
2277f01aef836eedced2131ede63f2eeadbe1e3f
|
[
"JavaScript",
"HTML",
"PHP"
] | 34 |
JavaScript
|
shaek1/Learning-Journey
|
e27a904fcffc18275fcfddd16aef8aa30f8f672c
|
d08030caeeadb20397a553209ac929b806319bba
|
refs/heads/master
|
<repo_name>RikuSyaCyo/visualization<file_sep>/world.js
var width = 700;
var height = 680;
var speed = 0.02;
var startTime = Date.now();
var currentTime = Date.now();
var country=["France","Yemen","Nigeria","Kenya","Syria"];
var count=new Array();
var title=d3.select("body")
.select("h1")
.attr("class","title");
var body = d3.select("body");
var svg = body.append("svg")
.attr("width", width)
.attr("height", height)
.attr("class","svg_position");
var tooltip=d3.select("body")
.append("div")
.attr("class","tooltip")
.style("opacity",0.0);
var news=d3.select("body")
.append("div")
.attr("class","news")
.style("opacity",0.0);
var projection = d3.geo.orthographic()
.scale(250);
var graticule = d3.geo.graticule();
var path = d3.geo.path()
.projection(projection);
var color = d3.scale.category20();
svg.append("text")
.attr("id","loading")
.attr("x",width/2)
.attr("y",height/2)
.text("Now Loading...");
d3.json("world_605kb.json", function(error, root) {
if (error)
return console.error(error);
console.log(root);
var grid = graticule();
console.log(grid);
var map = svg.append("g")
.attr("transform", "translate(" + -100 + "," + 100 + ")");
var n=0;
count[n]=77;
n++;
for(var i=1;i<country.length;i++)
{
for(var k=1;k<root.features.length;k++)
{
if(root.features[k].properties.SOVEREIGNT==country[i])
{
if(root.features[k].geometry!=null) count[n++]=k;
}
}
}
map.append("path")
.datum( grid )
.attr("id","grid_id")
.attr("class","grid_path")
.attr("d",path);
map.selectAll(".map_path")
.data( root.features )
.enter()
.append("path")
.attr("class","map_path")
.attr("fill",function(d,i){
return "#bcbddc";
})
.attr("d", path )
.attr("id",function(d,i)
{
return d.properties.SOVEREIGNT;
})
.on("mouseover",function(d,i){
d3.select(this)
.attr("fill","#756bb1");
var ele=d3.select(this);
//alert(d.properties.SOVEREIGNT==country[1]);
tooltip.html(d.properties.SOVEREIGNT)
.style("opacity",0.75)
.style("left",(d3.event.pageX)+"px")
.style("top",(d3.event.pageY+20)+"px")
}
)
.on("mouseout",function(d,i){
d3.select(this)
.attr("fill","#bcbddc");
tooltip.style("opacity",0.0);
})
svg.select("#loading")
.attr("opacity",0);
var count_val=new Array();
for(var x in count)
{
if(root.features[count[x]].geometry!=null)
count_val.push(count[x]);
}
for(var i=0;i<count_val.length;i++)
{
transition(count_val[i],i);
}
function transition(d,i)
{
var s="#"+country[i];
var p=d3.geo.centroid(root.features[d]);
var r=d3.interpolate(projection.rotate(),[-p[0],-p[1]]);
d3.transition()
.duration(1250)
.each("start",function()
{
//alert(country[ii]);
title.text(country[i]);
console.log("start");
if(i==0)
news.html("attacked by ISIS in 2015.11.13, seriously killed 132 people at least")
.style("opacity",1.0);
else if(i==1)
news.html("attacked by ISIS in 2015.3.20, seriously killed 137 people <br> and injured 350 people at least")
.style("opacity",1.0);
else if(i==2)
news.html("attacked by Boko in Haram 2015.1.3, seriously killed 150-2000 people")
.style("opacity",1.0);
else if(i==3)
news.html("attacked by al-Shabaab in 2015.4.2, seriously injured 147 people at least")
.style("opacity",1.0);
else
news.html("attacked by ISIS in 2015.8.28, seriously injured 154 people")
.style("opacity",1.0);
})
.tween("rotate",function()
{
console.log(d);
return function(t)
{
projection.rotate(r(t));
map.attr("transform", "translate(" + -100 + "," + 100 + ")");
map.select("#grid_id")
.attr("d",path);
map.selectAll(".map_path")
.attr("d",path);
map.selectAll(s)
.attr("fill","#cd5c5c");
}
})
.tween("opacity",function()
{
return function(t)
{
news.style("opacity",t*1.0)
}
})
.transition()
.each("end",function()
{
console.log(i)
console.log("end");
news.style("opacity",0.0);
map.selectAll(s)
.attr("fill","#bcbddc");
if(i>0)
transition(count_val[--i],i);
else
{
i+=4;
transition(count_val[i],i);
}
})
}
});
<file_sep>/drawStatistics.js
function drawStatistics(svgID, mapName, statisID) {
var tID = "tooltip_text";
var svg = d3.select("#" + svgID);
var width = svg.attr("width");
var height = svg.attr("height");
var statisGroups = svg.append("g")
.attr("id", statisID);
var padding = { top: 820, right: 200, bottom: 20, left: 30 };
var color = "#bcbddc";
d3.json("./statistics/" + mapName + ".json", function (error, data) {
if (error) return console.error(error);
var dataset = data.dataset;
var maxCas = d3.max(dataset[0].casualties, function (d) { return d[2] });
var xScale = d3.scale.linear()
.domain([2007, 2016])
.range([0,width - padding.left - padding.right]);
var yScale = d3.scale.linear()
.domain([0, maxCas * 1.1])
.range([height - padding.top - padding.bottom,0]);
var linePath = d3.svg.line()
.x(function (d) { return xScale(d[0]+1.0/12.0*d[1]); })
.y(function (d) { return yScale(d[2]);});
statisGroups.selectAll("path")
.data(dataset)
.enter()
.append("path")
.attr("transform", "translate(" + padding.left + "," + padding.top + ")")
.attr("d", function (d) {
return linePath(d.casualties);
})
.attr("fill", "none")
.attr("stroke-width", "2px")
.attr("stroke", color);
var xAxis = d3.svg.axis()
.scale(xScale)
.ticks(16)
.tickFormat(d3.format("d"))
.orient("bottom")
;
statisGroups.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + padding.left + "," + (height - padding.bottom) + ")")
.call(xAxis);
var focusGroups = statisGroups.append("g")
.attr("class", "focusGroups");
for (var p in dataset[0].casualties)
{
var dP=dataset[0].casualties[p];
if (dP[2] > 0)
{
focusGroups.append("circle")
.datum(dP)
.attr("cx", function (d) { return xScale(d[0] + 1.0 / 12.0 * d[1]) })
.attr("cy", function (d) { return yScale(d[2])})
.attr("transform", "translate(" + padding.left + "," + padding.top + ")")
.attr("r", "18px")
.attr("fill", "none")
.attr("pointer-events","all")
.on("mouseover", function (d) {
d3.select("#" + tID).style("left", function () {
var cx = xScale(d[0] + 1.0 / 12.0 * d[1]);
return cx + "px";
})
.style("top", yScale(d[2])+padding.top-50+"px")
.style("opacity", 1)
.html(d[0]+"."+d[1]+"<br>"+"casualties:"+d[2]);
})
.on("mouseout", function () {
d3.select("#" + tID).style("left","0px")
.style("top","0px")
.style("opacity", 0);
})
.on("mousemove", function (d) {
});
}
}
});
}<file_sep>/drawMap.js
var eventArea=d3.set(["新疆","西藏","云南","China","France"]);
var dataset={"新疆":"2009.07.05打砸抢暴力犯罪事件",
"西藏":"2008.03.14拉萨打砸抢暴力犯罪事件",
"云南":"2014.03.01昆明火车站暴恐案"
};
var t2ID = "tooltip_event";
var orgName=new Array("Al-Qa`ida","Islamic State of Iraq and the Levant (ISIL)","Al-Qa`ida in the Arabian Peninsula (AQAP)","Eastern Turkistan Islamic Movement (ETIM)","Al-Nusrah Front");
var flag={
"Al-Qa`ida":false,
"Islamic State of Iraq and the Levant (ISIL)":false,
"Al-Qa`ida in the Arabian Peninsula (AQAP)":false,
"Eastern Turkistan Islamic Movement (ETIM)":false,
"Al-Nusrah Front":false
};
var orgID=new Array("alq","ISIL","AQAP","ETIM","aln");
var orgbutton=0;
var atkbutton=0;
var color=new Array("#cb2e26","#83c3eb","#f1bd56","#0060a7","#87bb40");
function drawMap(svgID,mapName,t1ID,breturnID)
{
var svg = d3.select("#"+svgID);
var width = svg.attr("width");
var height = svg.attr("height");
var tooltip1 = d3.select("#" + t1ID).style("left", -1000 + "px")
.style("top", -1000 + "px")
.style("opacity", 0.0);
var tooltip_event = d3.select("#" + t2ID).style("left", -1000 + "px")
.style("top", -1000 + "px")
.style("opacity", 0.0);
var button_return = d3.select("#" + breturnID)
.style("opacity", 0.0);
d3.select("#buttonTable")
.style("opacity",1.0);
d3.select("#atkimg")
.style("opacity",1.0);
d3.select("#tagimg")
.style("opacity",1.0);
d3.json("./data/mapData.json", function (error, data) {
if (error) return console.error(error);
var mapData = data[mapName];
var pro = mapData.projection;
var scaleV = mapData.scale;
var center0 = mapData.center0;
var center1 = mapData.center1;
var global = mapData.global;
var projection = d3.geo.mercator();
projection.center([center0, center1])
.scale(scaleV)
.translate([width / 2, height / 2]);
var path = d3.geo.path()
.projection(projection);
var groups = d3.select("#mapGroup");
groups.remove();
groups = svg.append("g")
.attr("id", "mapGroup");
d3.csv("./data/incident/"+mapName+"_inc.csv", function (error, inciData) {
if (error) return console.error(error);
var incidents = new Array();
var areas = new Object();
for (var p in inciData) {
if (inciData[p]["country_txt"] == mapName) {
incidents.push(inciData[p]);
areas[inciData[p]["city"]] = true;
}
}
svg.style("top", "300px")
.style("height", "813px");
d3.selectAll("img")
.style("opacity", 0.0);
d3.selectAll("#printname")
.html(mapName)
.attr("class", "printname")
.style("opacity", 0.9);
d3.selectAll("#buttonTable")
.style("opacity",1);
var timeline = d3.select("body")
.append("div")
.attr("id", "timeline-embed")
.style("height", "350px")
.style("opacity", 1.0);
var data = "data/mydata" + mapName + ".json";
var additionalOptions = {
timenav_height: 200,
marker_padding: 25,
scale_factor: 0.5,
hash_bookmark: true,
start_at_slide: 0,
timenav_position: "top",
default_bg_color: { r: 242, g: 242, b: 242 }
};
timeline = new TL.Timeline('timeline-embed', data, additionalOptions);
d3.json("./geojson/" + mapName + ".geojson", function (error, root) {
if (error) return console.error(error);
//绘制地图
var paths = groups.selectAll("path")
.data(root.features)
.enter()
.append("path")
.attr("class", "area")
.attr("stroke", "#ffffff")
.attr("stroke-width", 1)
.style("fill", function (d, i) {
// if (!(areas.hasOwnProperty(d.properties.name)))
return "#d7d7ea";
// else
// return "#a5a6c9";
})
.attr("d", path);
//增加区域监听事件
paths.on("mouseover", function (d, i) {
//if (areas.hasOwnProperty(d.properties.name)) {
// d3.select(this).style("fill", "#756bb1");
//}
tooltip1.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY + 20) + "px")
.style("opacity", 0.75)
.html(d.properties.name);
})
.on("mouseout", function (d, i) {
//if (!(areas.hasOwnProperty(d.properties.name)))
// d3.select(this).style("fill", "#d7d7ea");
//else
// d3.select(this).style("fill", "#a5a6c9");
tooltip1.style("left", -1000 + "px")
.style("top", -1000 + "px")
.style("opacity", 0.0);
})
.on("mousemove", function (d) {
tooltip1.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY + 20) + "px");
})
.on("click", function (d, i) {
});
//增加事件点
var circleGroups = groups.append("g")
.attr("id", "circleGroup")
.selectAll("g")
.data(incidents)
.enter()
.append("g");
var defs=svg.append("defs");
var gaussian=defs.append("filter")
.attr("id","gaussian");
gaussian.append("feGaussianBlur")
.attr("in","SourceGraphic")
.attr("stdDeviation","1");
circleGroups.each(function (d) {
var px = projection([d["longitude"], d["latitude"]]);
var group = d3.select(this);
group.append("circle")
.attr("id", "C0"+d.eventid)
.attr("cx", px[0])
.attr("cy", px[1])
.attr("r", mapData.circleSize0 + "px")
.style("fill", "#fff3f1")
.style("opacity", 0.75)
.style("filter","url(#gaussian)");
group.append("circle")
.attr("id", "C1"+d.eventid)
.attr("cx", px[0])
.attr("cy", px[1])
.attr("r", mapData.circleSize1 + "px")
.style("fill", "#ff867d")
.style("opacity", 1);
group.on("mouseover", function (d) {
var wd = d["nwound"];
var kill = d["nkill"];
if (!(wd) )
wd = 0;
if (!(kill))
kill = 0;
var base = mapData.base;
var sz = parseInt(wd) + parseInt(kill);
if (sz > base * 15)
sz = base * 15;
var circlesize0 = mapData.circleSize0*(1+sz/base);
var circlesize1 = mapData.circleSize1*(1+sz/base);
// var circlesize0 = mapData.circleSize0 * 1.5;
// var circlesize1 = mapData.circleSize1 * 1.4;
var circle0 = d3.select("#" + "C0" + d.eventid)
.transition().duration(800)
.ease("elastic")
.attr("r", circlesize0 + "px")
.style("opacity", 0.6);
var circle1 = d3.select("#" + "C1" + d.eventid)
.transition().duration(800)
.ease("elastic")
.attr("r", circlesize1 + "px");
tooltip1.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY + 20) + "px")
.style("opacity", 0.75)
.html(d.iyear+ "."+ d.imonth+"." + d.iday);
})
.on("mousemove", function (d) {
tooltip1.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY + 20) + "px");
})
.on("mouseout", function (d) {
var circle0 = d3.select("#" + "C0"+d.eventid)
.transition().duration(80)
.attr("r", mapData.circleSize0 + "px")
.style("opacity", 1);;
var circle1 = d3.select("#" + "C1"+d.eventid)
.transition().duration(80)
.attr("r", mapData.circleSize1 + "px")
.style("opacity", 1);;
tooltip1.style("left", -1000 + "px")
.style("top", -1000 + "px")
.style("opacity", 0.0);
})
.on("click", function (d) {
var tooltip_event = d3.select("#" + t2ID);
tooltip_event.style("left", 30 + "px")
.style("top", 670 + "px")
.style("opacity", 0.75)
.html(d.summary);
// $('html, body').animate({ scrollTop: 0 }, 'slow');
//timeline.goToId(d.eventname);
});
});
//事件之间的联系
var linegroups=svg.append("g")
.attr("id","linegroups");
var linePath=d3.svg.line();
for(var p in incidents)
{
var related=incidents[p].related.split(",");
if(related[0]!=""){
for(var i=0;i<related.length;i++)
{
for(var j in incidents)
{
if(incidents[j].eventid==related[i])
{
var px1 = projection([incidents[p]["longitude"], incidents[p]["latitude"]]);
var px2 = projection([incidents[j]["longitude"], incidents[j]["latitude"]]);
var lines=new Array();
lines[0]=px1;
lines[1]=px2;
linegroups.append("path")
.attr("d",linePath(lines))
.attr("stroke","black")
.attr("stroke-width","2px")
.attr("fill","none")
.style("opacity",0.3)
}
}
}
}
}
//组织筛选
for(var p in orgName)
{
d3.select("#"+orgID[p])
.datum(orgName[p])
.on("click",function(d){
if(flag[d]==false)
{
for(var i in incidents)
{
if (incidents[i]["gname"]!=d)
{
//console.log(d3.select("#C0"+incidents[i].eventid).style("fill"));
if(d3.select("#C0"+incidents[i].eventid).style("fill")=="rgb(255, 243, 241)")
{
d3.select("#C0"+incidents[i].eventid)
.style("fill","none");
d3.select("#C1"+incidents[i].eventid)
.style("fill","none");
}
}
else if (incidents[i]["gname"]==d)
{
// d3.select("#C0"+incidents[i].eventid)
// .style("fill",color[orgbutton]);
d3.select("#C1"+incidents[i].eventid)
.style("fill",color[orgbutton])
.style("opacity",1.0);
d3.select("#C0"+incidents[i].eventid)
.style("fill","white")
.style("opacity",1.0);
//console.log(incidents[i].eventid);
}
}
flag[d]=true;
orgbutton++;
//console.log(orgbutton);
}
else{
flag[d]=false;
orgbutton--;
for(var i in incidents)
{
if((incidents[i]["gname"]!=d)&&(orgbutton==0))
{
d3.select("#C0"+incidents[i].eventid)
.style("fill","rgb(255, 243, 241)")
.style("opacity",1.0);
d3.select("#C1"+incidents[i].eventid)
.style("fill","rgb(255, 134, 125)")
.style("opacity",1.0);
}
else if (incidents[i]["gname"]==d)
{
d3.select("#C0"+incidents[i].eventid)
.style("fill","none");
d3.select("#C1"+incidents[i].eventid)
.style("fill","none");
}
}
}
})
}
//攻击类型筛选
d3.select("#atkButton")
.on("click",function()
{
if(atkbutton==0)
{
for(var p in incidents)
{
var thisevent=d3.select("#C0"+incidents[p].eventid).style("fill");
//console.log(thisevent);
if(thisevent!="none")
{
switch(incidents[p]["attacktype1"]){
case "1":
//onsole.log(incidents[p]["attacktype1"]);
d3.select("#C1"+incidents[p].eventid)
.style("fill","#66cccc");
break;
case "2":
d3.select("#C1"+incidents[p].eventid)
.style("fill","99cc33");
break;
case "3":
d3.select("#C1"+incidents[p].eventid)
.style("fill","#ff6600");
break;
case "4":
d3.select("#C1"+incidents[p].eventid)
.style("fill","#ffbfbf");
break;
case "5":
d3.select("#C1"+incidents[p].eventid)
.style("fill","#666699");
break;
case "6":
d3.select("#C1"+incidents[p].eventid)
.style("fill","#ffff99");
break;
case "7":
d3.select("#C1"+incidents[p].eventid)
.style("fill","#cc99cc");
break;
case "8":
d3.select("#C1"+incidents[p].eventid)
.style("fill","#e1657d");
break;
default: break;
}
}
}
atkbutton=1;
}
else if(atkbutton==1)
{
for(var p in incidents)
{
var thisevent=d3.select("#C0"+incidents[p].eventid).style("fill");
//console.log(thisevent);
if(thisevent!="none")
{
d3.select("#C0"+incidents[p].eventid)
.style("fill","rgb(255, 243, 241)")
.style("opacity",1.0);
d3.select("#C1"+incidents[p].eventid)
.style("fill","rgb(255, 134, 125)")
.style("opacity",1.0);
}
}
atkbutton=0;
}
})
// d3.select("#tagButton")
// .on("click",function()
// {
// for(var p in incidents)
// {
// //console.log(incidents[p].targtype1);
// var px = projection([incidents[p]["longitude"], incidents[p]["latitude"]]);
// //console.log(px);
// svg.append("text")
// .html(incidents[p].targtype1)
// .attr("x",px[0])
// .attr("y",px[1]);
// }
// })
//伤亡堆栈图
var yearkill=new Array(); //年死亡人数
var yearwd=new Array(); //年受伤人数
for(var i=0;i<15;i++)
{
yearkill[i]=0;
yearwd[i]=0;
}
var dataset=new Array();
for(var p in incidents)
{
var wd=parseInt(incidents[p].nwound);
var kill=parseInt(incidents[p].nkill);
//console.log(yearkill[14]);
if ((wd == "")||isNaN(wd))
wd = 0;
if ((kill == "")||isNaN(kill))
kill = 0;
yearkill[incidents[p].iyear-2000]+=kill;
yearwd[incidents[p].iyear-2000]+=wd;
//console.log(yearkill[14]);
}
//console.log(yearkill);
//console.log(yearwd);
dataset[0]=new Object();
dataset[1]=new Object();
dataset[0].name="kill";
dataset[0].number=new Array();
dataset[1].name="injured";
dataset[1].number=new Array();
//console.log(dataset);
for(var i in yearwd)
{
dataset[0].number[i]=new Object();
dataset[0].number[i].year=parseInt(i)+2000;
dataset[0].number[i].count=yearkill[i];
dataset[1].number[i]=new Object();
dataset[1].number[i].year=parseInt(i)+2000;
dataset[1].number[i].count=yearwd[i];
}
var stack=d3.layout.stack()
.values(function(d){return d.number;})
.x(function(d){return d.year;})
.y(function(d){return d.count;});
var data=stack(dataset);
//console.log(data);
var padding={left:1500,right:30,top:350,bottom:500};
var xRangWidth=width-padding.left-padding.right;
var xScale=d3.scale.ordinal()
.domain(data[0].number.map(function(d){
return d.year;
}))
.rangeBands([0,xRangWidth],0.3);
var maxCount=d3.max(data[data.length-1].number,function(d){
return d.y0+d.y;
});
var yRangeWidth=height-padding.top-padding.bottom;
var yScale=d3.scale.linear()
.domain([0,maxCount])
.range([0,yRangeWidth]);
var stackcolor=new Array("#FF99CC","#CCCCFF");
var stackgroups=svg.append("g")
.attr("id","stackgroup")
.selectAll("g")
.data(data)
.enter()
.append("g")
.style("fill",function(d,i){return stackcolor[i];});
var stacktooltip=d3.select("body")
.append("div")
.attr("id","stacktooltip")
.attr("class","tooltip");
var rects=stackgroups.selectAll("rect")
.data(function(d){return d.number;})
.enter()
.append("rect")
.attr("x",function(d){return xScale(d.year);})
.attr("y",function(d){
return yRangeWidth-yScale(d.y0+d.y);
})
.attr("width",function(d){
return xScale.rangeBand();
})
.attr("height",function(d){return yScale(d.y);})
.attr("transform","translate("+padding.left+","+padding.top+")")
.on("mouseover",function(d){
//console.log(d.count);
stacktooltip.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY+10) + "px")
.style("opacity", 0.75)
.html(d.count);
})
.on("mouseout",function(d,i){
stacktooltip.style("opacity",0.0);
});
//目标类型堆栈图
var typetooltip=d3.select("body")
.append("div")
.attr("id","typetooltip")
.attr("class","tooltip");
var type=new Array();
for(var i=0;i<15;i++)
{
type[i]=new Array();
for(var j=0;j<22;j++)
{
type[i][j]=0;
}
}
for(var p in incidents)
{
type[incidents[p].iyear-2000][incidents[p].targtype1-1]+=1;
//console.log(incidents[p].targtype1);
}
var typegroups=svg.append("g")
.attr("id","typegroup")
var x=1508;
var y=630;
for(var i=0;i<15;i++)
{
for(var j=0;j<22;j++)
{
var color_now=204-type[i][j]*30;
if(color_now==0) color_now=0;
var typecolor="rgb("+color_now+","+color_now+",255)";
y-=7;
var rect_now=new Object();
rect_now.type=j;
rect_now.count=type[i][j];
rect_now.year=i;
//console.log(type[recordi][recordj]);
typegroups.append("rect")
.style("fill",typecolor)
.attr("id","rect"+i+j)
.attr("x",x+"px")
.attr("y",y+"px")
.attr("width","20px")
.attr("height","5px")
.datum(rect_now)
.on("mouseover",function(d){
console.log(d);
d3.select("#rect"+d.year+d.type)
.style("stroke","black")
.style("stroke-width","1")
.transition()
.duration(800)
.ease("elastic")
.attr("width","23px")
.attr("height","10px");
typetooltip.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY + 10) + "px")
.style("opacity", 0.75)
.style("font-size","5px")
.html("type:"+d.type+"<br>"+"count:"+d.count);
})
.on("mouseout",function(d){
d3.select("#rect"+d.year+d.type)
.style("stroke-width","0")
.transition()
.duration(800)
.ease("elastic")
.attr("width","20px")
.attr("height","5px");
typetooltip.style("opacity",0.0);
})
}
x+=24;
y=630;
}
//攻击类型堆栈图
var atk=new Array();
for(var i=0;i<15;i++)
{
atk[i]=new Array();
for(var j=0;j<9;j++)
{
atk[i][j]=0;
}
}
var atkdataset=new Array();
for(var p in incidents)
{
atk[incidents[p].iyear-2000][incidents[p].attacktype1-1]+=1;
}
for(var i=0;i<9;i++)
{
atkdataset[i]=new Object();
atkdataset[i].type=i+1;
atkdataset[i].number=new Array();
for(var j=14;j>=0;j--)
{
atkdataset[i].number[14-j]=new Object();
atkdataset[i].number[14-j].year=j+2000;
atkdataset[i].number[14-j].count=atk[j][i];
}
}
var atkstack=d3.layout.stack()
.values(function(d){return d.type;})
.x(function(d){return d.year;})
.y(function(d){return d.count;});
var atkdata=stack(atkdataset);
// console.log(atkdata);
var atkpadding={left:1500,right:30,top:650,bottom:200};
var atkxRangWidth=width-atkpadding.left-atkpadding.right;
var atkxScale=d3.scale.ordinal()
.domain(atkdata[0].number.map(function(d){
return d.year;
}))
.rangeBands([0,atkxRangWidth],0.3);
var atkmaxCount=d3.max(atkdata[atkdata.length-1].number,function(d){
return d.y0+d.y;
});
var atkyRangeWidth=height-atkpadding.top-atkpadding.bottom;
var atkyScale=d3.scale.linear()
.domain([0,atkmaxCount])
.range([0,atkyRangeWidth]);
var atkcolor=new Array("#66cccc","#99cc33","#ff6600","#ffbfbf","#666699","#ffff99","#cc99cc","#e1657d","#ff867d");
var atkgroups=svg.append("g")
.attr("id","atkgroup")
.selectAll("g")
.data(atkdata)
.enter()
.append("g")
.style("fill",function(d,i){return atkcolor[i];});
var atkrects=atkgroups.selectAll("rect")
.data(function(d){return d.number;})
.enter()
.append("rect")
//.attr("class","atkgroup")
.attr("x",function(d){return atkxScale(d.year);})
.attr("y",function(d){
return atkyRangeWidth-atkyScale(d.y0+d.y);
})
.attr("width",function(d){
return atkxScale.rangeBand();
})
.attr("height",function(d){return atkyScale(d.y);})
.attr("transform",function(d){
return "translate("+atkpadding.left+","+atkpadding.top+")"+"rotate(180,185 53)";
})
.on("mouseover",function(d){
//console.log(d);
stacktooltip.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY + 10) + "px")
.style("opacity", 0.75)
.html(d.count);
})
.on("mouseout",function(d,i){
stacktooltip.style("opacity",0.0);
});
//坐标轴
var axScale=d3.scale.linear()
.domain([2000,2014])
.range([0,385]);
var axis=d3.svg.axis()
.scale(axScale)
.orient("top")
.tickValues([2000,2014]);
var gAxis=svg.append("g")
.attr("transform","translate(1493,635)");
gAxis.attr("class","axis")
.attr("id","axis");
axis(gAxis);
//标注
var gradient=defs.append("linearGradient")
.attr("id","myGradient")
.attr("x1","0%")
.attr("x2","0%")
.attr("y1","0%")
.attr("y2","100%");
gradient.append("stop")
.attr("offset","0%")
.attr("stop-color","rgb(0,0,255)");
gradient.append("stop")
.attr("offset","100%")
.attr("stop-color","rgb(204,204,255)");
var markgroups=svg.append("g")
.attr("id","mark");
markgroups.append("rect")
.attr("fill","url(#myGradient)")
.attr("x","1480")
.attr("y","500")
.attr("width","20")
.attr("height","100");
markgroups.append("text")
.attr("x","1484")
.attr("y","612")
.text("0");
markgroups.append("text")
.attr("x","1480")
.attr("y","495")
.text("max");
markgroups.append("circle")
.attr("cx","1430")
.attr("cy","390")
.attr("r","5")
.attr("fill","#FF99CC");
markgroups.append("circle")
.attr("cx","1430")
.attr("cy","370")
.attr("r","5")
.attr("fill","#CCCCFF");
markgroups.append("text")
.attr("x","1440")
.attr("y","395")
.attr("font-size","5px")
.text("fatalities");
markgroups.append("text")
.attr("x","1440")
.attr("y","375")
.attr("font-size","5px")
.text("injuries");
markgroups.append("text")
.attr("x","1430")
.attr("y","750")
.attr("font-size","5px")
.text("number of incidents");
//返回世界地图
var button_return = d3.select("body")
.append("button")
.attr("id", "tooltip_return")
.attr("class", "button")
.html("←return to global")
.on("click", function () {
d3.selectAll("img")
.style("opacity",1.0);
d3.select("#printname")
.style("opacity",0.0);
d3.select("#timeline-embed")
.remove();
d3.select("#circle")
.style("opacity", 0.0);
d3.selectAll("rect")
.remove();
d3.select("#axis")
.remove();
d3.select("#mark")
.remove();
d3.select("#buttonTable")
.style("opacity",0.0);
d3.select("#atkimg")
.style("opacity",0.0);
d3.select("#tagimg")
.style("opacity",0.0);
d3.select("#linegroups")
.remove();
drawGlobalMap("mapSVG", "tooltip", "tooltip_return");
});
button_return.style("opacity", 1);
});
});
});
}
//for (var pA in eventAreas) {
// var pArea = eventAreas[pA];
// for (var pE in pArea) {
// // console.log(pArea[pE]);
// //console.log(pArea[pE].eventID);
// var circles = circleGroup.append("g")
// .datum(pArea[pE]);
// //console.log(circles);
// var px = projection(pArea[pE].location);
// circles.append("circle")
// .datum(px)
// .attr("id", pArea[pE].eventID + "Circle0")
// .attr("cx", px[0])
// .attr("cy", px[1])
// .attr("r", mapData.circleSize0 + "px")
// .style("fill", "white")
// .style("opacity", 0.75);
// circles.append("circle")
// .datum(px)
// .attr("id", pArea[pE].eventID + "Circle1")
// .attr("cx", px[0])
// .attr("cy", px[1])
// .attr("r", mapData.circleSize1 + "px")
// .style("fill", "#cd5c5c")
// .style("opacity", 1)
// //.on("mouseover", function () {
// // d3.select(this).attr("r", mapData.circleSize1 * 1.3 + "px")
// //});
// circles.on("mouseover", function (d) {
// console.log(d);
// var circlesize0 = d.injured / 1080 * 102;
// var circlesize1 = d.dead / 158 * 48;
// var circle0 = d3.select("#" + d.eventID + "Circle0")
// .transition().duration(800)
// .ease("elastic")
// .attr("r", circlesize0 + "px");
// var circle1 = d3.select("#" + d.eventID + "Circle1")
// .transition().duration(800)
// .ease("elastic")
// .attr("r", circlesize1 + "px");
// tooltip1.style("left", (d3.event.pageX) + "px")
// .style("top", (d3.event.pageY + 20) + "px")
// .style("opacity", 0.75)
// .html(d.time);
// //console.log(pArea[pE].eventID);
// })
// .on("mousemove", function (d) {
// tooltip1.style("left", (d3.event.pageX) + "px")
// .style("top", (d3.event.pageY + 20) + "px");
// })
// .on("mouseout", function (d) {
// var circle0 = d3.select("#" + d.eventID + "Circle0")
// .transition().duration(80)
// .attr("r", mapData.circleSize0 + "px");
// var circle1 = d3.select("#" + d.eventID + "Circle1")
// .transition().duration(80)
// .attr("r", mapData.circleSize1 + "px");
// tooltip1.style("left", -1000 + "px")
// .style("top", -1000 + "px")
// .style("opacity", 0.0);
// })
// .on("click", function (d) {
// var tooltip_event = d3.select("#" + t2ID);
// tooltip_event.style("left", 30 + "px")
// .style("top", 670 + "px")
// .style("opacity", 0.75)
// .html(d.text);
// $('html, body').animate({ scrollTop: 0 }, 'slow');
// timeline.goToId(d.eventname);
// });
// }
//}<file_sep>/drawGlobalMap.js
var t1ID = "tooltip";
var t2ID = "tooltip_event";
var svgID = "mapSVG";
var breturnID = "tooltip_return";
var gmIDs = new Array();
var circleStyle = { color: "rgba(255,134,125,0.3)" };
var gname = {
"Taliban": "Taliban",
"Al-Shabaab": "Al-Shabaab",
"Islamic State of Iraq and the Levant (ISIL)": "ISIL",
"Communist Party of India - Maoist (CPI-Maoist)": "CPI-Maoist",
"<NAME>": "BKHR",
"Revolutionary Armed Forces of Colombia (FARC)": "FARC",
"Tehrik-i-Taliban Pakistan (TTP)":"TTP"
};
var gcolor = {
"Taliban": "orange",
"Al-Shabaab": "purple",
"Islamic State of Iraq and the Levant (ISIL)": "#87BB40",
"Communist Party of India - Maoist (CPI-Maoist)": "RGB(130,184,234)",
"<NAME>": "red",
"Revolutionary Armed Forces of Colombia (FARC)": "blue",
"other": "lightgray"
}
function drawGlobalMap()
{
d3.select("#mapGroup")
.remove();
d3.select("#" + svgID).style("top", "0px")
.style("height", "960px");
d3.selectAll("img")
.style("opacity", 1.0);
d3.select("#printname")
.style("opacity", 0.0);
d3.select("#timeline-embed")
.remove();
d3.select("#circle")
.style("opacity", 0.0);
d3.select("#buttonTable")
.style("opacity", 0.0);
d3.select("#orgTable")
.style("opacity", 0.0);
d3.select("#atkimg")
.style("opacity", 0.0);
d3.select("#tagimg")
.style("opacity", 0.0);
d3.selectAll("rect")
.remove();
d3.select("#axis")
.remove();
d3.select("#mark")
.remove();
d3.select("body")
.style("cursor", "wait");
_drawGlobalMap();
d3.csv("./data/organization.csv", function (error, organization) {
if (error) return console.error(error);
_drawAnimation(organization);
});
d3.csv("./data/casualties.csv", function (error, casualties) {
if (error) return console.error(error);
d3.csv("./data/count.csv", function (error, count) {
if (error) return console.error(error);
d3.csv("./data/pieCasual.csv", function (error, pieCasual) {
if (error) return console.error(error);
d3.csv("./data/pieCount.csv", function (error, pieCount) {
if (error) return console.error(error);
_drawStatistics(casualties, count, pieCasual,pieCount);
});
});
});
});
}
function clearTAGS()
{
for (var p in gmIDs)
{
d3.select("#" + gmIDs[p])
.remove();
}
}
function filter(d, year, orga)
{
if (year != "All" && d.iyear != year)
return false;
if (orga != "All" && d.gname != orga)
return false;
return true;
}
function modifyCircles() {
var p = d3.select("#yearSel").property("value");
var t = d3.select("#orgaSel").property("value");
var circles = d3.select("#circleGroup").selectAll("circle");
circles.each(function (d) {
var circle = d3.select(this);
if (p == "All" && t == "All")
{
circle.attr("r", circleStyle.size)
.style("fill", circleStyle.color);
return;
}
var f = filter(d,p,t);
if (f)
circle.attr("r",circleStyle.size)
.style("fill", circleStyle.color);
else
circle.attr("r",circleStyle.size)
.style("fill", "none");
});
}
function update() {
if (!AnimationFlag)
return;
var sel = d3.select("#yearSel");
var p = sel.property("value");
if (p == 2014 || p == "All" )
sel.property("value", "2001");
else
sel.property("value", parseInt(p) + 1);
modifyCircles();
setTimeout(update, 600);
}
var AnimationFlag = false;
function _drawAnimation(organization)
{
var div = d3.select("body")
.append("div")
.attr("id","selDIV")
.attr("class", "selectDIV");
gmIDs.push("selDIV");
//table
var table = div.append("table")
.style("text-align", "left");
var tbody = table.append("tbody")
//.style("table-layout", "fixed")
//.style("position", "relative")
//.style("top", "10%");
//.style("left", "1.5%")
//.style("width", "97%");
//标题
var tr = tbody.append("tr");
var th = tr.append("th")
.attr("colspan",2)
.style("text-align","center")
.html("Select ");
th.append("button")
.html("start")
.on("click", function () {
if (!AnimationFlag) {
AnimationFlag = true;
setTimeout(update, 0);
d3.select(this).html("stop");
}
else {
AnimationFlag = false;
d3.select(this).html("start");
}
});
//选择年份
tr = tbody.append("tr");
tr.append("td")
.html("year:")
var yearSel = tr.append("td").append("select")
.attr("id","yearSel")
.on("change",modifyCircles);
yearSel.append("option")
.html("All");
for (var i = 2000; i <= 2014; i++)
{
yearSel.append("option")
.html(i);
}
//选择组织
tr = tbody.append("tr");
tr.append("td")
.html("organization")
var orgaSel = tr.append("td").append("select")
.attr("id", "orgaSel")
.on("change", modifyCircles);
orgaSel.append("option")
.html("All");
for (var p in organization) {
orgaSel.append("option")
.html(organization[p].gname);
}
}
function transStackData(data)
{
var type = [ "Taliban", "Al-Shabaab", "Islamic State of Iraq and the Levant (ISIL)", "Communist Party of India - Maoist (CPI-Maoist)", "Boko Haram", "other"];
var rs = new Array();
for (var t in type)
{
var k = new Object();
k["name"] = type[t];
k["data"] = new Array();
for (var p in data)
{
var d = data[p];
var o = new Object();
o["year"] = d.iyear;
o["amount"] = parseFloat(d[type[t]]);
o["name"] = type[t];
k["data"].push(o);
}
rs.push(k);
}
return rs;
//var injure = new Object();
//injure["name"] = "woundus";
//injure["data"] = new Array();
//for (var p in data)
//{
// var d = data[p];
// var o = new Object();
// o["year"] = d.iyear;
// o["amount"] = d.nwounds;
// injure["data"].push(o);
//}
//rs.push(injure);
}
function drawStack(svg,dataSet)
{
var width = svg.attr("width");
var height = svg.attr("height");
dataSet = transStackData(dataSet);
var Stack = d3.layout.stack()
.values(function (d) { return d.data; })
.x(function (d) { return d.year; })
.y(function (d) { return d.amount; });
var Data = Stack(dataSet);
var padding = { left: 0, right: 0, top: 30, bottom: 30 };
var xRangeWidth = width - padding.left - padding.right;
var xScale = d3.scale.ordinal()
.domain(Data[0].data.map(function (d) {
return d.year;
}))
.rangeBands([0, xRangeWidth], 0.3);
//var xScale = d3.scale.ordinal()
//.domain([2000,2001,2002,2003,2004,2005,2006])
//.range([10,20,30,40,50,60,70]);
var maxAmount = d3.max(Data[Data.length - 1].data, function (d) {
return d.y0 + d.y;
});
var yRangeWidth = height - padding.top - padding.bottom;
var yScale = d3.scale.linear()
.domain([0, maxAmount])
.range([0, yRangeWidth]);
var color = d3.scale.category10();
var groups = svg.selectAll("g")
.data(Data)
.enter()
.append("g")
.style("fill", function (d, i) {
return gcolor[d.name];
})
var rects = groups.selectAll("rect")
.data(function (d) {
return d.data;
})
.enter()
.append("rect")
.attr("class", function (d,i) {
return "stackrect"
})
.attr("x", function (d) {
return xScale(d.year);
})
.attr("y", function (d) {
return yRangeWidth - yScale(d.y0 + d.y);
})
.attr("width", function (d) {
return xScale.rangeBand();
})
.attr("height", function (d) {
return yScale(d.y);
})
.attr("transform", "translate(" + padding.left + "," + padding.top + ")")
.on("mouseover", function (d) {
mark(d.name, d.year)
})
.on("mouseout", recover);
//绘制坐标轴
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.tickFormat(d3.format(".0f"));
svg.append("g")
.attr("class","axis")
.attr("transform", "translate(" + padding.left + "," + (height - padding.bottom) + ")")
.call(xAxis);
}
function mark(orga,year)
{
var strokecolor = "black";
var strokewidth = "3px";
var div = d3.select("#statisDIV");
var arcs = div.selectAll(".piearc");
arcs.each(function (d) {
if (d.data.gname == orga)
d3.select(this)
.style("stroke", strokecolor)
.style("stroke-width",strokewidth);
});
var rects = div.selectAll("rect");
if (year == "All") {
rects.each(function (d) {
if (d.name == orga)
d3.select(this)
.style("stroke", strokecolor)
.style("stroke-width", strokewidth);
});
}
else {
rects.each(function (d) {
if (d.name == orga && d.year == year)
d3.select(this)
.style("stroke", strokecolor)
.style("stroke-width", strokewidth);
});
}
var highcolor = "rgba(230,0,0,0.2)";
var circles = d3.select("#circleGroup").selectAll("circle");
//circles.each(function (d) {
// if (d.gname !== orga)
// {
// d3.select(this).style("opacity", 0);
// return;
// }
// if (year != "All" && d.iyear != year)
// {
// d3.select(this).style("opacity", 0);
// return;
// }
// if (d.gname == orga)
// d3.select(this).style("fill", highcolor);
//});
}
function recover()
{
var strokecolor = "rgba(255, 255, 255, 0.6)";
var strokewidth = "1.5px";
var div = d3.select("#statisDIV");
var arcs = div.selectAll(".piearc")
.style("stroke", strokecolor)
.style("stroke-width", strokewidth);
var rects = div.selectAll("rect")
.style("stroke", strokecolor)
.style("stroke-width", strokewidth);
var circles = d3.select("#circleGroup").selectAll("circle");
//circles.each(function (d) {
// d3.select(this).style("fill", circleStyle.color)
// .style("opacity",1);
//});
}
function drawPie(svg, dataset)
{
var width = svg.attr("width");
var height = svg.attr("height");
//画饼图
var pie = d3.layout.pie()
.value(function (d) {
return d.amount;
});
var piedata = pie(dataset);
var outerRadius = height / 2.5;
var innerRadius = 0;
var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
var color = d3.scale.category10();
var arcs = svg.selectAll("g")
.data(piedata)
.enter()
.append("g")
.attr("transform", "translate(" + (width / 2) + "," + (height / 2) + ")");
arcs.append("path")
.attr("class", "piearc")
.attr("fill", function (d, i) {
return gcolor[d.data.gname];
})
.attr("d", function (d) {
return arc(d);
})
.on("mouseover", function (d) {
mark(d.data.gname, "All");
})
.on("mouseout", function(d){
recover();
});
}
function _drawStatistics(casualties,count,pieCasual,pieCount)
{
var width = 1000;
var height = 650;
var div = d3.select("body")
.append("div")
.attr("id", "statisDIV")
.attr("class", "statisDIV")
.style("width", width + "px")
.style("height",height + "px");
gmIDs.push("statisDIV");
//table
var table = div.append("table")
.style("text-align", "center")
.style("table-layout", "fixed")
.style("position", "absolute")
.style("top", "1.5%")
.style("left", "1.5%")
.style("width", "97%")
.style("height","97%");
var tbody = table.append("tbody")
//.style("table-layout", "fixed")
//.style("position", "relative")
//.style("top", "10%");
//.style("left", "1.5%")
//.style("width", "97%");
var base = 2.1;
//堆叠图
var tr = tbody.append("tr");
//数量
svg = tr.append("td").append("svg")
.attr("width", width / base)
.attr("height", height / base)
.style("background-color", "white");
drawStack(svg, count);
//伤亡
var svg = tr.append("td").append("svg")
.attr("width", width/base)
.attr("height", height/base)
.style("background-color", "white");
//var casDIV = div.append("div")
// .style("position", "relative")
// //.style("left", 0)
// //.style("top",0)
// .style("width", width/2+"px")
// .style("height", height/2+"px");
drawStack(svg, casualties);
//饼图
tr = tbody.append("tr");
//数量
svg = tr.append("td").append("svg")
.attr("width", width / base)
.attr("height", height / base)
.style("background-color", "white");
drawPie(svg, pieCount);
//伤亡
svg = tr.append("td").append("svg")
.attr("width", width / base)
.attr("height", height / base)
.style("background-color", "white");
drawPie(svg, pieCasual);
//div.append("div")
//.attr("id", "tlp")
//.attr("class", "toolDIV");
}
function _drawGlobalMap()
{
var mapName = "world";
var svg = d3.select("#"+svgID);
var width = svg.attr("width");
var height = svg.attr("height");
var tooltip1 = d3.select("#" + t1ID).style("left", -1000 + "px")
.style("top", -1000 + "px")
.style("opacity", 0.0);
var tooltip_event = d3.select("#" + t2ID).style("left", -1000 + "px")
.style("top", -1000 + "px")
.style("opacity", 0.0);
var button_return = d3.select("#" + breturnID)
.style("opacity", 0.0);
var groups = svg.append("g")
.attr("id", "mapGroup");
gmIDs.push("mapGroup");
d3.json("./data/mapData.json",function(error, data){
if (error) return console.error(error);
var mapData=data[mapName];
var pro=mapData.projection;
var scaleV=mapData.scale;
var center0=mapData.center0;
var center1 = mapData.center1;
var global = mapData.global;
var projection = d3.geo.equirectangular();
projection.center([center0, center1])
.scale(scaleV)
.translate([width/2.4, height/2.3]);
var path = d3.geo.path()
.projection(projection);
d3.csv("./data/incident/world_inc.csv", function (error, incidents) {
if (error) return console.error(error);
d3.csv("./data/eventCountry.csv", function (error, eventCountries) {
if (error) return console.error(error);
var Areas = new Object();
for (var p in eventCountries)
{
Areas[eventCountries[p]["country"]]=true;
}
d3.json("./data/map/world.geojson", function (error, root) {
if (error) return console.error(error);
//绘制地图
var paths = groups.selectAll("path")
.data(root.features)
.enter()
.append("path")
.attr("class", "area")
.attr("stroke", "#ffffff")
.attr("stroke-width", 1)
.style("fill", function (d, i) {
if (!(Areas.hasOwnProperty(d.properties.name))) {
return "#d7d7ea";
}
else
{
return "#a5a6c9";
}
})
.attr("d", path)
.style("cursor", function (d, i) {
if (Areas.hasOwnProperty(d.properties.name))
return "pointer";
else
return "default";
});
//增加区域监听事件
paths.on("mouseover", function (d, i) {
if (Areas.hasOwnProperty(d.properties.name))
{
d3.select(this).style("fill", "#756bb1");
}
tooltip1.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY + 20) + "px")
.style("opacity", 0.75)
.html(d.properties.name);
})
.on("mouseout", function (d, i) {
if (!(Areas.hasOwnProperty(d.properties.name)))
d3.select(this).style("fill","#d7d7ea");
else
d3.select(this).style("fill","#a5a6c9");
tooltip1.style("left", -1000 + "px")
.style("top", -1000 + "px")
.style("opacity", 0.0);
})
.on("mousemove", function (d) {
tooltip1.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY + 20) + "px");
})
.on("click", function (d, i) {
if (Areas.hasOwnProperty(d.properties.name ))
{
clearTAGS();
drawMap(svgID,d.properties.name,t1ID,breturnID);
}
});
//增加事件点
circleStyle["size"] = mapData.circleSize1;
var circleGroup = groups.append("g")
.attr("id", "circleGroup");
circleGroup.selectAll("circle")
.data(incidents)
.enter()
.append("circle")
.attr("r", circleStyle.size + "px")
.attr("id", function (d, i) {
return d["eventid"];
})
.attr("class", function (d, i) {
return "normalCir";
//if (!d["gname"])
// return "other";
//if (gname.hasOwnProperty(d["gname"])) {
// return gname[d["gname"]];
//}
//else
// return "other";
})
.style("fill",circleStyle.color)
.each(function (d) {
var px = projection([d["longitude"], d["latitude"]]);
d3.select(this).attr("cx", px[0]);
d3.select(this).attr("cy", px[1]);
// console.log(d["gname"]);
})
.on("mouseover", function (d, i) {
});
d3.select("body")
.style("cursor", "default");
//for (var pA in incidents) {
// var pinc = eventAreas[pA];
// for (var pE in pinc) {
// var circles = circleGroup.append("g")
// .datum(pArea[pE]);
// var px = projection(pArea[pE].location);
// circles.append("circle")
// .datum(px)
// .attr("id", pArea[pE].eventID + "Circle1")
// .attr("cx", px[0])
// .attr("cy", px[1])
// .attr("r", mapData.circleSize1 + "px")
// .style("fill", "#cd5c5c")
// .style("opacity", 1);
// }
//}
});
});
});
});
} <file_sep>/choose.js
var orgOpen=0;
var atkOpen=0;
var tagOpen=0;
function chooseOrg()
{
if(orgOpen==0)
{
d3.select("#orgTable")
.style("opacity",1.0);
orgOpen=1;
}
else if(orgOpen==1)
{
d3.select("#orgTable")
.style("opacity",0);
orgOpen=0;
}
}
function chooseAtk()
{
if(atkOpen==0)
{
d3.select("#atkimg")
.style("opacity",1.0);
atkOpen=1;
}
else if(atkOpen==1)
{
d3.select("#atkimg")
.style("opacity",0);
atkOpen=0;
}
}
function chooseTag()
{
if(tagOpen==0)
{
d3.select("#tagimg")
.style("opacity",1.0);
tagOpen=1;
}
else if(tagOpen==1)
{
d3.select("#tagimg")
.style("opacity",0);
tagOpen=0;
}
}
|
0e45699dff2db95454aa13b47810627c2c17ad3b
|
[
"JavaScript"
] | 5 |
JavaScript
|
RikuSyaCyo/visualization
|
5d06b82f16ed77b81e65c337474b01ee2e69a74c
|
d2f8807ec49ebcd8497e8dd887f4187e4405d946
|
refs/heads/master
|
<file_sep>//页面相关配置
import Vue from 'vue'
import config from '@/config'
const Config = {
namespaced: true,
state: {
pageConfig: Object.assign({}, config)
},
mutations: {
Update_Page_Config(state, data) {
Vue.set(state.pageConfig, data.key, data.value)
},
Reset_Page_Config(state, data) {
state.indexInfo = null
}
},
actions: {
async UpdatePageConfigAsync({
commit, state
}) {
try {
//var res = await HomeService.getIndex()
//commit('Set_IndexInfo', res.data)
} catch (error) {
//console.log(error)
}
}
},
getters: {
pageConfig: state => state.pageConfig
}
}
export default Config
<file_sep>import httpRequest from './httpRequest'
export default {
getInfo(){
return httpRequest.get('/aa/aa')
}
}<file_sep>import Vue from 'vue'
import { formatDate } from '../utils/date'
Vue.filter('dateTimeFilter', (timestamp, format)=>{
if(!timestamp){
return 'qwe'
}
if(!format){
format = 'yyyy-MM-dd hh:mm'
}
return formatDate(new Date(timestamp), format)
})<file_sep>import CommonService from './commonService'
import LoginService from './login'
export {
CommonService,
LoginService,
}
<file_sep>var config = {
//默认打开左侧菜单栏
collapsed: false,
showSort: false
}
export default config;
<file_sep>import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/components/login'
import Home from '@/components/home'
import Main from '@/components/main'
import Real from '@/components/main/real'
import Management from '@/components/management'
import NotFound from '@/components/other/notfound'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/login',
name: 'login',
component: Login
},
{
path: '/home',
component: Home,
children:[
{
path: '',
component: Main,
name: 'main'
},
{
path: 'real',
component: Real,
name: 'real'
},
{
path: 'management',
component: Management,
name: 'management'
},
{
path:'*',
component: NotFound,
name: 'notfound'
}
]
},
{
path: '*',
component: NotFound
}
]
})
<file_sep>import {
HomeService
}
from '@/api'
const App = {
namespaced: true,
state: {
indexInfo: null
},
mutations: {
Set_IndexInfo(state, data) {
state.indexInfo = Object.assign({}, data)
},
Clear_Store_App(state, data) {
state.indexInfo = null
}
},
actions: {
async getIndexInfo({
commit, state
}) {
try {
var res = await HomeService.getIndex()
commit('Set_IndexInfo', res.data)
} catch (error) {
console.log(error)
}
}
},
getters: {
indexInfo: state => state.indexInfo
}
}
export default App
<file_sep>// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
//import ElementUI from 'element-ui'
import App from './App'
import router from './router'
import store from './store'
//import Vuelidate from 'vuelidate'
//import './assets/element-custom.scss'
//import './assets/fixed.scss'
import './assets/app.scss'
import './filters/commonFilter'
// import {
// ThemePick,
// Breadcrumb,
// Aprogress,
// Echarts
// }
// from './modules'
//const eventHub = new Vue()
Vue.config.productionTip = false
// Vue.use(ElementUI)
// Vue.use(Vuelidate)
// Vue.use(ThemePick)
// Vue.use(Breadcrumb)
// Vue.use(Aprogress)
//Vue.use(Echarts)
Vue.prototype.$eventHub = new Vue(); // Global event bus
// Vue.prototype.auth = function(menus, code, authType) {
// for (var i = 0; i < menus.length; i++) {
// if (code == menus[i]) {
// return menus[i].permission.indexOf(authType) >= 0
// } else {
// if (menus[i].childrens && menus[i].childrens.length > 0) {
// for (var j = 0; j < menus[i].childrens.length; j++) {
// if (menus[i].childrens[j].code == code) {
// return menus[i].childrens[j].permission.indexOf(authType) >= 0
// }
// }
// }
// }
// }
// }
var app = new Vue({
el: '#app',
router,
store,
components: {
App
},
template: '<App/>'
})
export default app
<file_sep>import Vuex from 'vuex'
import Vue from 'vue'
import app from './app'
import theme from './theme'
import config from './config'
Vue.use(Vuex)
const debug = process.env.NODE_ENV !== 'production'
const modules = {
app,
theme,
config
}
export default new Vuex.Store({
modules,
strict: debug
})<file_sep>var navs = [{
code: 'management',
url: '/management',
childrens: [{
code: 'user',
url: '/home/users'
}, {
code: 'role',
url: '/home/roles'
}, {
code: 'menus',
url: '/home/menus'
}]
}, {
code: 'about',
url: '/home/about'
}, {
code: 'setting',
url: '/setting',
childrens: [{
code: 'basicInfo',
url: '/home/basicInfo'
}, {
code: 'changepwd',
url: '/home/changepwd'
}]
}]
const dataMapFunc = {
getMappedLocalNav(code) {
for (var i = 0; i < navs.length; i++) {
if (code == navs[i].code) {
return navs[i]
}
}
return null
},
getMappedNavs: (mappingNavs) => {
var _nav, mappedNewNavs = []
for (var i = 0; i < mappingNavs.length; i++) {
_nav = mappingNavs[i]
var foundLocal = dataMapFunc.getMappedLocalNav(_nav.code)
if (!foundLocal) {
continue
}
_nav.url = foundLocal.url
if (!foundLocal.childrens || foundLocal.childrens.length <= 0) {
mappedNewNavs.push(_nav)
continue
}
//for(var j = 0;j<foundLocal.childrens.length;j++){
var _code;
for (var j = 0; j < _nav.childrens.length; j++) {
_code = _nav.childrens[j].code
var findSub = foundLocal.childrens.filter((n) => n.code == _code)
if (findSub.length > 0) {
_nav.childrens[j].url = findSub[0].url
}
// if(_nav.childrens[k].code == foundLocal.childrens[j].code){
// _nav.childrens[k].url = foundLocal.childrens[j].url
// break
// }
}
//}
_nav.childrens.sort((a, b) => {
return a.order > b.order ? 1 : -1
})
mappedNewNavs.push(_nav)
}
mappedNewNavs.sort((a, b) => {
return a.order > b.order ? 1 : -1
})
return mappedNewNavs
}
}
export default dataMapFunc
<file_sep>const Theme = {
namespaced: true,
state: {
themeName: localStorage.getItem('theme')?localStorage.getItem('theme'):''
},
mutations: {
Set_Theme(state, theme){
state.themeName = theme
localStorage.setItem('theme', theme)
}
},
actions:{
getInfo({commit, state}){
}
},
getters:{
themeName: state=>state.themeName
}
}
export default Theme
|
b285e5d055c75cc19f26ff9048a02dfddbca70f4
|
[
"JavaScript"
] | 11 |
JavaScript
|
yukai1202/portalmanage
|
f63946d874076ca4920cadcbf6a82a9ea9414b10
|
fb0c507001975944bcd3afd3034abdc1c9ea5f8e
|
refs/heads/main
|
<file_sep>using System;
using EmployeeManagement.Protobuf;
using Grpc.Core;
namespace EmployeeManagement.Client
{
class Program
{
static void Main(string[] args)
{
Channel channel = new Channel("127.0.0.1:8006", ChannelCredentials.Insecure);
var client = new EmployeeManagementOpsService.EmployeeManagementOpsServiceClient(channel);
Console.WriteLine("Retrieving employee data...");
Console.WriteLine();
var response = client.GetEmployeeList(new EmployeeListRequest());
foreach (var employee in response.EmployeeList)
{
Console.WriteLine($"Id: {employee.Id} Name: {employee.FirstName} {employee.LastName} Address: {employee.Address}");
}
Console.WriteLine();
Console.WriteLine("Enter employee Id to get details:");
var id= Console.ReadLine();
if (int.TryParse(id, out int empId))
{
var result = client.GetEmployeeById(new EmployeeByIdRequest {Id = empId });
Console.WriteLine($"Id: {result.Employee.Id} Name: {result.Employee.FirstName} {result.Employee.LastName} Address: {result.Employee.Address}");
}
else
{
Console.WriteLine("Employee not exist");
}
Console.ReadLine();
}
}
}
<file_sep># gRPC-Demo
A small gRPC client-server demo app using C# .NET
<file_sep>using System;
using System.Runtime.CompilerServices;
using System.Threading;
using EmployeeManagement.Protobuf;
using Factory;
using Grpc.Core;
using GrpcServer = Grpc.Core.Server;
namespace EmployeeManagement.Service
{
class Program
{
private const string ServerIpAddress = "127.0.0.1";
private const int ServerPort = 8006;
private static GrpcServer _server;
static void Main(string[] args)
{
try
{
var employeeMaintenance = ObjectCreator.CreateEmployeeMaintenanceInstance();
_server = new GrpcServer
{
Services =
{
EmployeeManagementOpsService.BindService(new EmployeeManagementServiceImpl(employeeMaintenance))
},
Ports = { new ServerPort(ServerIpAddress, ServerPort, ServerCredentials.Insecure) }
};
_server.Start();
Console.WriteLine("Employee management service running...");
Console.WriteLine();
Console.WriteLine("Press Enter to exit");
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
finally
{
_server?.ShutdownAsync();
Environment.Exit(0);
}
}
}
}
<file_sep>using System;
using System.Threading.Tasks;
using EmployeeManagement.Contracts;
using EmployeeManagement.Protobuf;
using Google.Protobuf.Collections;
using Grpc.Core;
namespace EmployeeManagement.Service
{
public class EmployeeManagementServiceImpl : EmployeeManagementOpsService.EmployeeManagementOpsServiceBase
{
private readonly IEmployeeManagement _employeeManagement;
public EmployeeManagementServiceImpl(IEmployeeManagement employeeManagement)
{
_employeeManagement = employeeManagement;
}
public override Task<EmployeeListResponse> GetEmployeeList(EmployeeListRequest request, ServerCallContext context)
{
try
{
var employeeList = _employeeManagement.GetEmployeeList();
var employeeMessageList = new RepeatedField<EmployeeMessage>();
foreach (var employee in employeeList)
{
var empployee = new EmployeeMessage
{
Id = employee.Id, FirstName = employee.FirstName, LastName = employee.LastName,
Address = employee.Address
};
employeeMessageList.Add(empployee);
}
return Task.FromResult(new EmployeeListResponse { EmployeeList = { employeeMessageList } });
}
catch (Exception ex)
{
throw ex;
}
}
public override Task<EmployeeResponse> GetEmployeeById(EmployeeByIdRequest request, ServerCallContext context)
{
try
{
var employee = _employeeManagement.GetEmployeeById(request.Id);
return Task.FromResult(new EmployeeResponse
{
Employee = new EmployeeMessage
{
Id = employee.Id, FirstName = employee.FirstName, LastName = employee.LastName,
Address = employee.Address
}
});
}
catch (Exception ex)
{
throw ex;
}
}
public override Task<AddEmployeeResponse> AddEmployee(EmployeeRequest request, ServerCallContext context)
{
try
{
var employeeMessage = request.Employee;
var employee = new Employee
{
Id = employeeMessage.Id, FirstName = employeeMessage.FirstName, LastName = employeeMessage.LastName,
Address = employeeMessage.Address
};
var isAdded = _employeeManagement.AddEmployee(employee);
return Task.FromResult(new AddEmployeeResponse {IsAdded = true});
}
catch (Exception ex)
{
throw ex;
}
}
}
}
<file_sep>using System.Collections.Generic;
namespace EmployeeManagement.Contracts
{
public interface IEmployeeManagement
{
IList<Employee> GetEmployeeList();
Employee GetEmployeeById(int employeeId);
bool AddEmployee(Employee employee);
}
}
<file_sep>using EmployeeManagement.Contracts;
namespace Factory
{
public static class ObjectCreator
{
public static IEmployeeManagement CreateEmployeeMaintenanceInstance() =>
new EmployeeManagement.EmployeeManagement();
}
}
<file_sep>using System.Collections.Generic;
using System.Linq;
using EmployeeManagement.Contracts;
namespace EmployeeManagement
{
public class EmployeeManagement: IEmployeeManagement
{
private readonly IList<Employee> _employeeList;
public EmployeeManagement()
{
_employeeList = new List<Employee>
{
new Employee {Id = 1, FirstName = "Albert", LastName = "Deshpande", Address = "Pune"},
new Employee {Id = 2, FirstName = "Sopanrao", LastName = "Gupta", Address = "Mumbai"},
new Employee {Id = 3, FirstName = "Micky", LastName = "Kelkar", Address = "Nasik"},
new Employee {Id = 4, FirstName = "Babu", LastName = "Lal", Address = "Goa"},
new Employee {Id = 5, FirstName = "Venkat", LastName = "Disoza", Address = "Delhi"},
new Employee {Id = 6, FirstName = "Munna", LastName = "Swami", Address = "Solapur"}
};
}
public IList<Employee> GetEmployeeList()
{
return _employeeList;
}
public Employee GetEmployeeById(int employeeId)
{
return _employeeList.FirstOrDefault(emp => emp.Id == employeeId);
}
public bool AddEmployee(Employee employee)
{
if (_employeeList.Any(emp => emp.Id == employee.Id))
return false;
_employeeList.Add(employee);
return true;
}
}
}
|
4c6094b886c2baa6a7480a5cf659d58eb506cd98
|
[
"Markdown",
"C#"
] | 7 |
C#
|
nileshpagdal83/gRPC-Demo
|
3526410c203b249eae37662a706b9466d61f5555
|
aa5d0672b9604244a00e9043e746ab1de2f3189b
|
refs/heads/master
|
<file_sep>const User = require("../modals/UserSchema.js");
const generateToken = require("../utils/generateToken.js");
// const protected = (req, res) => {
// res.send("protected route here");
// };
const register = async (req, res) => {
const { username, email, password, profilepic } = req.body;
const usernameistaken = await User.findOne({ username });
const emailexists = await User.findOne({ email });
if (!username || !email || !password) {
return res.status(404).json({ error: "Please Fill all the details" });
}
if (usernameistaken) {
return res.status(400).json({ error: "username is already taken" });
} else if (emailexists) {
return res.status(400).json({ error: "email already exists!" });
} else {
res
.status(200)
.json({ message: "Registration Successfully.Welcome Fam!!" });
}
try {
const user = await new User({
username,
email,
password,
profilepic: profilepic,
});
await user.save();
} catch (error) {
res.status(404).json({ error });
}
};
const login = async (req, res) => {
// console.log("login running");
const { email, password, profilepic } = req.body;
const user = await User.findOne({ email });
// console.log(await user.matchPassword(password));
try {
if (!email || !password) {
return res.status(404).json({ error: "Please Fill all the details" });
}
if (user && (await user.matchPassword(password))) {
res.json({
_id: user._id,
username: user.username,
email: user.email,
token: generateToken(user._id),
profilepic: user.profilepic,
});
res.status(200).json({ message: "User found" });
} else {
res.status(422).json({ error: "Invalid Credentials" });
}
} catch (error) {
// console.log(error);
res.status(404).json({ error: "Something went Wrong" });
}
};
module.exports = { register, login };
<file_sep>const Post = require("../modals/postSchema.js");
const createPost = async (req, res) => {
const { title, body, pic } = req.body;
if (!title || !body || !pic) {
return res.status(422).json({ error: "Please add all the fields" });
}
const post = await new Post({
title,
body,
pic,
postedBy: req.user,
});
try {
await post.save();
res.status(202).json({ message: "post saved successfully" });
} catch (error) {
res.status(402).json({ error: error + "Please Try again" });
}
};
const viewPost = async (req, res) => {
try {
const posts = await Post.find().populate("postedBy", "_id username");
res
.status(202)
.json({ message: "all post viewed successfully", posts: posts });
} catch (error) {
console.log("error occurred", error);
res.status(402).json({ error: error });
}
};
const myPost = async (req, res) => {
try {
const myposts = await Post.find({ postedBy: req.user._id }).populate(
"postedBy",
"_id username"
);
res.status(202).json({ message: "my post ", myposts: myposts });
} catch (error) {
res.status(402).json({ error: error });
}
};
const like = (req, res) => {
Post.findByIdAndUpdate(
req.body.postId,
{
$push: { likes: req.user._id },
},
{
new: true, //to get new record);
}
).exec((err, result) => {
if (err) {
return res.status(422).json({ error: err });
} else {
// console.log(result);
res.json(result);
}
});
};
const dislike = (req, res) => {
Post.findByIdAndUpdate(
req.body.postId,
{
$pull: { likes: req.user._id },
},
{
new: true, //to get new record);
}
).exec((err, result) => {
if (err) {
return res.status(422).json({ error: err });
} else {
res.json(result);
}
});
};
const makecomment = (req, res) => {
const comments = {
text: req.body.text,
postedBy: req.user._id,
};
// console.log(comments);
Post.findByIdAndUpdate(
req.body.postId,
{
$push: { comments: comments },
},
{
new: true, //to get new record);
}
)
.populate("comments.postedBy", "_id username")
.populate("postedBy", "_id username")
.exec((err, result) => {
if (err) {
return res.status(422).json({ error: err });
} else {
// console.log(result);
res.json(result);
}
});
};
const deletepost = (req, res) => {
// console.log("delete post form backend");
Post.findOne({ _id: req.params.postId })
.populate("postedBy", "_id")
.exec((error, post) => {
if (error || !post) {
return res.status(422).json({ error: error });
}
if (post.postedBy._id.toString() === req.user._id.toString()) {
post
.remove()
.then((result) => {
res.json(result);
})
.catch((err) => console.log(err));
}
});
};
module.exports = {
createPost,
viewPost,
myPost,
like,
dislike,
makecomment,
deletepost,
};
<file_sep>import React, { useContext, useEffect, useState } from "react";
import { useHistory } from "react-router-dom";
import { UserContext } from "../../App";
import CreatePost from "./CreatePost";
function Home() {
const history = useHistory();
const [token, settoken] = useState();
const { state, dispatch } = useContext(UserContext);
const [postData, setpostData] = useState([]);
const [currentuser, setcurrentuser] = useState(null);
useEffect(() => {
const currentUser = JSON.parse(localStorage.getItem("userInfo"));
const token = JSON.parse(localStorage.getItem("userInfo")).token;
settoken(token);
setcurrentuser(currentUser);
if (token === "null") {
history.push("/signin");
}
fetch("/allpost", {
headers: {
Authorization: "Bearer " + token,
},
})
.then((res) => res.json())
.then((data) => {
setpostData(data.posts);
})
.catch((error) => console.log(error));
}, [postData]);
const likepost = (id) => {
fetch("http://localhost:5000/like", {
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
body: JSON.stringify({
postId: id,
}),
}).then((result) => {
const newData = postData.map((item) => {
if (item._id === result._id) {
return result;
} else {
return item;
}
});
setpostData(newData);
});
};
const dislikepost = (id) => {
fetch("http://localhost:5000/dislike", {
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
body: JSON.stringify({
postId: id,
}),
})
.then((res) => res.json())
.then((result) => {
const newData = postData.map((item) => {
if (item._id === result._id) {
return result;
} else {
return item;
}
});
setpostData(newData);
})
.catch((err) => console.log(err));
};
const deletePost = (postid) => {
fetch(`http://localhost:5000/deletepost/${postid}`, {
method: "delete",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
})
.then((res) => res.json())
.then((result) => {
console.log("result from delete", result);
const newdata = postData.filter((item) => {
return item.id !== result._id;
});
setpostData(newdata);
});
console.log("delete post form frontend", postid);
};
// console.log(postData);
const makecomments = (text, postId) => {
fetch("http://localhost:5000/comment", {
method: "put",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
body: JSON.stringify({
text,
postId,
}),
})
.then((res) => res.json())
.then((result) => {
const newData = postData.map((item) => {
if (item._id === result._id) {
return result;
} else {
return item;
}
});
setpostData(newData);
})
.catch((err) => console.log(err));
};
return (
<>
<CreatePost />
{postData
.map((item, id) => (
<div className="home" key={item._id}>
<div className="card home-card">
<span className="deletecontainer">
<h5 className="username">
<strong>{item.postedBy.username}</strong>
</h5>
{item.postedBy._id === state._id && (
<i
className="material-icons"
onClick={() => deletePost(item._id)}
>
delete
</i>
)}
</span>
<div className="card-image ">
<img src={item.pic} />
</div>
<div className="card-content">
<div className="likescontainer">
{item.likes.includes(state._id) ? (
<div>
<i
style={{ Color: "red" }}
className="material-icons"
onClick={() => dislikepost(item._id)}
>
favorite
</i>
</div>
) : (
<div>
<i
className="material-icons"
onClick={() => likepost(item._id)}
>
favorite
</i>
</div>
)}
</div>
<span>{item.likes.length} likes </span>
<h6>{item.title}</h6>
<p>{item.body}</p>
<hr></hr>
{item.comments.map((record) => (
<h6 key={record._id}>
<span className="commentusername">
{record.postedBy.username}
</span>
{record.text}
</h6>
))}
{currentuser ? (
<form
onSubmit={(e) => {
e.preventDefault();
makecomments(e.target[0].value, item._id);
}}
>
<input type="text" placeholder="Add a comment" />
</form>
) : (
""
)}
</div>
</div>
</div>
))
.reverse()}
</>
);
}
export default Home;
<file_sep>import React, { useContext } from "react";
import { Link, useHistory } from "react-router-dom";
import { UserContext } from "../App";
import "../components/Navbar.css";
function Navbar() {
const history = useHistory();
const { state, dispatch } = useContext(UserContext);
const logouthandler = () => {
localStorage.removeItem("userInfo");
dispatch({ type: "LOGOUT" });
history.push("/signin");
};
const renderList = () => {
if (state) {
return [
<div>
<button className="logoutbtn" onClick={logouthandler}>
Log out
</button>
</div>,
];
} else {
return [
<div className="links">
<div className="registerlink">
<Link to="/register">Sign Up</Link>
</div>
<div className="signinlink">
<Link to="/signin">Login</Link>
</div>
</div>,
];
}
};
return (
<div className="header">
<div className="header__left">
<Link to={state ? "/" : "/signin"} className="logo">
<h5>🔥🔥🔥</h5>
</Link>
</div>
<div className="header__right">{renderList()}</div>
</div>
);
}
export default Navbar;
<file_sep>import React, { useState, useEffect } from "react";
import { Link, useHistory } from "react-router-dom";
import "../../App.css";
import M from "materialize-css";
function Signup() {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [email, setemail] = useState("");
const history = useHistory();
const [profileimage, setprofileimage] = useState("");
const [url, setUrl] = useState("");
useEffect(() => {
if (url) {
fieldsdata();
}
}, [url]);
const uploadPic = () => {
const data = new FormData();
data.append("file", profileimage);
data.append("upload_preset", "firegram");
data.append("cloud_name", "nayak-shubham");
fetch("https://api.cloudinary.com/v1_1/nayak-shubham/image/upload", {
method: "post",
body: data,
})
.then((res) => res.json())
.then((data) => {
setUrl(data.secure_url);
})
.catch((err) => {
console.log(err);
});
};
const fieldsdata = () => {
if (
!/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(
email
)
) {
return M.toast({
html: "Enter Valid Email ",
classes: "#d50000 red accent-4",
});
}
if (confirmPassword === password) {
fetch("/register", {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
username,
password,
email,
profilepic: url,
}),
})
.then((res) => res.json())
.then((data) => {
if (data.error) {
M.toast({ html: data.error, classes: "#d50000 red accent-4" });
} else {
M.toast({
html: data.message,
classes: "#00c853 green accent-4",
});
history.push("/signin");
}
})
.catch((error) => {
M.toast({
html: error,
classes: "#d50000 red accent-4",
});
console.log(error);
});
} else {
M.toast({
html: "Password Does not Match",
classes: "#d50000 red accent-4",
});
}
};
const usersignupdata = () => {
if (profileimage) {
uploadPic();
} else {
fieldsdata();
}
};
return (
<div className="cardcontainer">
<div className="mycard">
<div className="card auth_card">
<h2>Signup Here </h2>
<input
type="text"
placeholder="Enter Username here"
value={username}
onChange={(e) => {
setUsername(e.target.value);
}}
required
/>
<input
type="email"
placeholder="Enter Email here"
value={email}
onChange={(e) => {
setemail(e.target.value);
}}
required
/>
<input
type="<PASSWORD>"
placeholder="Enter Password here"
value={password}
onChange={(e) => {
setPassword(e.target.value);
}}
required
/>
<input
type="password"
placeholder="Confirm Password here"
value={confirmPassword}
onChange={(e) => {
setConfirmPassword(e.target.value);
}}
required
/>
<div className="file-field input-field">
<div className="btn">
<span>Upload Profile Picture</span>
<input
type="file"
onChange={(e) => {
setprofileimage(e.target.files[0]);
}}
/>
</div>
<div className="file-path-wrapper">
<input className="file-path validate" type="text" />
</div>
</div>
<center>
<button className="signupbtn" onClick={usersignupdata}>
Signup ↔
</button>
<div class="linkto">
<p>Don't have an account?</p>
<Link to="/signin">
<span>Login</span>
</Link>
</div>
</center>
</div>
</div>
</div>
);
}
export default Signup;
<file_sep>const express = require("express");
const dotenv = require("dotenv");
const cors = require("cors");
const connectDB = require("./dbconfig/db.js");
const userAuthRoute = require("./routes/userAuthRoute.js");
const userRoute = require("./routes/userRoute.js");
const postRoute = require("./routes/postRoute.js");
// const PORT = ;
const app = express();
app.use(express.json());
app.use(cors());
dotenv.config();
connectDB();
// const mycustommiddleware = (req, res, next) => {
// console.log("i am a middleware...");
// next();
// };
// app.use(mycustommiddleware);
// app.get("/about", mycustommiddleware, (req, res) => {
// console.log("hello /about");
// return res.send("hello about");
// });
app.use("/", userAuthRoute);
app.use("/", postRoute);
app.use("/", userRoute);
if (process.env.NODE_ENV === "production") {
app.use(express.static("client/build"));
const path = require("path");
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
}
app.listen(process.env.PORT || 5000, () => console.log("hello SERVER"));
|
27c243d7dc6406f54a29cd144641522b59e5e5e0
|
[
"JavaScript"
] | 6 |
JavaScript
|
imnayakshubham/Firegram-MERN-APP-SOCIAL-MEDIA
|
f7e44c41ad05cfa0ed4fa644cf2c86b3c59ca77a
|
139415fca38c7630fc9f1a2474264c5fbd6e9876
|
refs/heads/master
|
<repo_name>radical-edo/api.test<file_sep>/source/js/views/auth/login.js
'use strict';
var ACCEPTABLE_ERROR_RESPONSE = [400, 401, 500];
var Login = Backbone.View.extend({
el: 'form',
events: {
'keyup input' : 'populateModel',
'click input[type="submit"]' : 'login',
},
login: function (ev) {
var view = this;
ev.preventDefault();
this.model.urlRoot = this.el.action;
this.model.save().done(function (auth, type, res) {
if (201 === res.status) {
view['handle' + res.status + 'Response']();
}
}).fail(function (res) {
if (_.includes(ACCEPTABLE_ERROR_RESPONSE, res.status)) {
view['handle' + res.status + 'Response']();
}
});
},
handle201Response: function () {
var message = 'Login successful';
this.showApiResponse(message, { type: 'success' });
this.$el.hide();
},
handle500Response: function () {
var message = 'Service unavailable';
this.showApiResponse(message, { type: 'error' });
},
handle400Response: function () {
var message = 'Incorrect credentials';
this.showApiResponse(message, { type: 'error' });
},
handle401Response: function () {
var message = 'Incorrect password or email';
this.showApiResponse(message, { type: 'error' });
},
showApiResponse: function (message, options) {
var el = $('.api-response');
el.html(message);
if ('error' === options.type) {
el.removeClass('bg-success');
el.addClass('bg-danger');
} else {
el.removeClass('bg-danger');
el.addClass('bg-success');
}
},
initialize: function () {
this.disableForm();
this.unbindValidation();
this.bindValidation();
},
disableForm: function () {
this.$el.find('.btn.btn-primary').addClass('disabled');
},
unbindValidation: function () {
Backbone.Validation.unbind(this, this._bindSettings());
},
bindValidation: function () {
Backbone.Validation.bind(this, this._bindSettings());
},
_bindSettings: function () {
return {
model: this.model,
valid: function () {
},
invalid: function (view, attr, message) {
var error = {}
error[attr] = message
view.showErrors(error);
},
};
},
showErrors: function (error) {
Object.keys(error).forEach(function (attr) {
var errorField = this.$('span[data-error-'+attr+']')
errorField.parent().addClass('has-error');
errorField.html(error[attr]);
}, this)
},
populateModel: function () {
this.clearErrors();
this.model.setState(this.getData())
if (this.model.isValid()) {
this.enableForm()
} else {
this.disableForm();
}
},
clearErrors: function () {
var errorField = this.$('span.error');
errorField.html('');
errorField.parent().removeClass('has-error');
},
getData: function () {
return Backbone.Syphon.serialize(this);
},
enableForm: function () {
this.$el.find('.btn.btn-primary').removeClass('disabled');
},
});
module.exports = Login;
<file_sep>/source/js/application.js
_.extend(Backbone.Model.prototype, Backbone.Validation.mixin);
window.Auth = require('./models/auth');
window.Login = require('./views/auth/login');
$.ajaxSetup({
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
}
});
$(function () {
var auth = new Auth
var login = new Login({ model: auth });
});
<file_sep>/README.md
### api.test
Login functionality written in with Backbone.js
### Dependencies
- node
- npm
- bower
- some way to serve static files ( I've used `nginx`)
#### Example nginx configuration
```nginx
server {
listen 80;
server_name api.test.lvh;
root /path/to/directory/with/project;
location ~* /build/.+\.(js|css) {
}
location / {
root /path/to/directory/with/project/build;
add_header Access-Control-Allow-Origin *;
index index.html;
}
access_log /usr/local/var/log/nginx/access.log;
error_log /usr/local/var/log/nginx/error.log;
}
```
Also add the `server_name` to the `/etc/hosts` file like so:
```bash
127.0.0.1 api.test.lvh
```
Or with whatever `server_name` you might have chosen.
#### Run project
1. `npm install`
2. `bower install`
3. `./node_modules/.bin/gulp watch` (if you have `gulp` installed globaly `gulp watch` will do)
|
4be37d5b0f28f6eaf7c90317c127efd15641911c
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
radical-edo/api.test
|
00c132cedd8fe0690005f2b2b9db40a1369a321d
|
caccff62bbec650df801003a7e497c8cf329d181
|
refs/heads/master
|
<repo_name>shadowfiend2509/miniqueryremake<file_sep>/client/query.js
class SweetSelector {
static select (type) {
if(type[0]=='#'){
return document.getElementById(type.slice(1));
}else if(type[0]=='.'){
return document.getElementsByClassName(type.slice(1))[0];
}else{
return document.getElementsByTagName(type)[0];
}
}
}
SweetSelector.select('#eyed');
SweetSelector.select('.btn');
SweetSelector.select('a');
class DOM {
static hide(query){
SweetSelector.select(query).style.display = 'none';
}
static show(query){
SweetSelector.select(query).style.display = 'block';
}
static addClass(query,newClass){
SweetSelector.select(query).classList.add(`${newClass}`);
}
static removeClass(query,target){
SweetSelector.select(query).classList.remove(`${target}`)
}
}
DOM.hide('#eyed');
DOM.hide('.btn');
DOM.hide('a');
DOM.show('#eyed');
DOM.show('.btn');
DOM.show('a');
DOM.addClass('.btn','shadi')
DOM.addClass('#eyed', 'shadi')
DOM.addClass('a', 'shadi')
DOM.removeClass('.btn','shadi');
DOM.removeClass('#eyed','shadi');
DOM.removeClass('a','shadi');
class EventDispatcher {
static on(query, method ,cb){
SweetSelector.select(query).addEventListener(method,cb)
}
static trigger(query,method){
const event = new Event(method);
SweetSelector.select(query).dispatchEvent(event)
}
}
EventDispatcher.on('.btn','click', function(){
console.log('awesome')
})
EventDispatcher.trigger('.btn','click');
|
506da1038d7fe3cb2dcf2d7c292a4db25f692496
|
[
"JavaScript"
] | 1 |
JavaScript
|
shadowfiend2509/miniqueryremake
|
0eb87aba3d992394d19158fe75f23536d9831c57
|
452117a6d73b458d372a596b8635a179438bec6b
|
refs/heads/master
|
<repo_name>hejw123/Python001-class01<file_sep>/week02/NOTE.md
# 第二周学习笔记
## Python - 连接数据库(mysql)
### pymysql
#### 打开数据库连接
DB = pymysql.connect("IP","USER","PASSWORD","DATABASE")
#### 执行SQL语句
DB.execute(SQL)
#### 使用cursor()方法 开启事务
cursor = DB.cursor()
#### 提交事务
DB.commit()
#### 回滚事务
DB.rollback()
## Python - 模拟浏览器
## WebDriver
使用浏览器的功能来模拟登陆,获取header
## Python - 分布式爬虫
通信中间价 - redis
队列通信
<file_sep>/week02/scrapys/scrapys/spiders/maoyan.py
import scrapy
import time
from scrapy import Selector
from scrapys.items import MaoyanItem
from selenium import webdriver
class MaoyanSpider(scrapy.Spider):
name = 'maoyan'
allowed_domains = ['maoyan.com']
start_urls = ['https://maoyan.com/films?showType=3']
def __init__(self):
try:
browser = webdriver.Chrome()
browser.get('https://passport.meituan.com/account/unitivelogin')
time.sleep(1)
# 输入账号和密码
browser.find_element_by_xpath('//*[@id="login-email"]').send_keys('13552656607')
browser.find_element_by_xpath('//*[@id="login-password"]').send_keys('')
time.sleep(1)
# 点击登陆
browser.find_element_by_xpath('//*[@id="J-normal-form"]/div[5]/input[5]').click()
cookie = browser.get_cookies()
self.headers(cookie)
except Exception as e :
print("----获取header头失败,可能会抓取失败!----")
print(e)
finally:
browser.close()
def start_requests(self):
url = 'https://maoyan.com/films?showType=3'
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
movies = Selector(response=response).xpath('//*[@class="movie-item film-channel"]')
for movie in movies :
link = "https://maoyan.com" + movie.xpath('./a/@href').extract_first()
yield scrapy.Request(url=link,callback=self.parse2)
def parse2(self ,response):
item = MaoyanItem()
time = Selector(response=response).xpath('//div[3]/div/div[2]/div[1]/ul/li[3]/text()').extract_first()
name = Selector(response=response).xpath('//div[3]/div/div[2]/div[1]/h1/text()').extract_first()
list_t = ""
tyeps = Selector(response=response).xpath('//div[3]/div/div[2]/div[1]/ul/li[1]/a')
for type in tyeps :
list_t = list_t + type.xpath('./text()').extract_first()
item['time'] = time
item['name'] = name
item['type'] = list_t.strip()
yield item
<file_sep>/week01/scrapy/scrapys/spiders/maoyan.py
import scrapy
from scrapy import Selector
from scrapys.items import MaoyanItem
class MaoyanSpider(scrapy.Spider):
name = 'maoyan'
allowed_domains = ['maoyan.com']
start_urls = ['https://maoyan.com/films?showType=3']
def start_requests(self):
url = 'https://maoyan.com/films?showType=3'
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
movies = Selector(response=response).xpath('//*[@class="movie-item film-channel"]')
for movie in movies :
link = "https://maoyan.com" + movie.xpath('./a/@href').extract_first()
yield scrapy.Request(url=link,callback=self.parse2)
def parse2(self ,response):
item = MaoyanItem()
time = Selector(response=response).xpath('//div[3]/div/div[2]/div[1]/ul/li[3]/text()').extract_first()
name = Selector(response=response).xpath('//div[3]/div/div[2]/div[1]/h1/text()').extract_first()
list_t = ""
tyeps = Selector(response=response).xpath('//div[3]/div/div[2]/div[1]/ul/li[1]/a')
for type in tyeps :
list_t = list_t + type.xpath('./text()').extract_first()
item['time'] = time
item['name'] = name
item['type'] = list_t.strip()
yield item
<file_sep>/week01/scrapy/scrapys/pipelines.py
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
class ScrapysPipeline:
def process_item(self, item, spider):
time = item['time']
name = item['name']
type = item['type']
output = f'{time},{name},{type}\r\n'
with open('./maoyanmovie.csv', 'a+', encoding='utf-8') as article:
article.write(output)
return item
<file_sep>/week01/NOTE.md
## 第一周作业
### 作业1 : 利用 Python requests、bs4 抓取 10 个 电影名称、电影类型和上映时间,
py : requests_maoyan.com.py
### 作业2 : 使用 Scrapy 框架和 XPath 抓取猫眼电影的前 10 个电影名称、电影类型和上映时间
dir : scrapy
<file_sep>/week01/requests_maoyan.com.py
#使用requests库获取猫眼 top10
import requests
from bs4 import BeautifulSoup as bs
import pandas as pd
import time
# 获取猫眼Top10影片详细链接
def getMylist(agent, cookie, url) -> list:
# 判断请求参数
if agent == '' or cookie == '' or url == '':
return []
header = {
'user-agent': agent,
'Cookie': cookie
}
response = requests.get(url, headers=header)
# 判断请求返回码
if response.status_code != 200:
return []
info = bs(response.text, 'html.parser')
# 创建列表
List = []
for tags in info.find_all('div', attrs={'class': 'movie-item film-channel'}):
href = "https://maoyan.com" + tags.find('a').get('href')
List.append(href)
if len(List) > 10:
break
return List
def getMyInfo(agent, cookie, url) -> list :
# 判断请求参数
if agent == '' or cookie == '' or url == '' :
return []
# 设置请求header
header = {
'user-agent': agent,
'Cookie': cookie
}
response = requests.get(url, headers=header)
# 判断请求返回码
if response.status_code != 200:
return []
info = bs(response.text, 'html.parser')
# 名称
name = info.find('div',attrs={"class":"movie-brief-container"}).find("h1",attrs={'class':'name'}).text
# 类型
lists = info.find_all("li",attrs={"class":"ellipsis"})
ellipsis = lists[0].text.replace("\n","").strip()
# 上映日期
time = info.find_all("li",attrs={"class":"ellipsis"})[2].text
data = []
data.append(name)
data.append(ellipsis)
data.append(time)
return data
# 开始抓取
print("start-time:"+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
user_agent = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'
coookie = '__mta=174397341.1593166132263.1593166146560.1593166258587.3; uuid_n_v=v1; uuid=08940570B79511EAA1F189776DB49E05C2ADF24E320243268AAED2B04040EE34; _csrf=274090bc3afea611b5c6be428852fa61754c55fbfed87b7b8d2dc07e9323d1e3; Hm_lvt_703e94591e87be68cc8da0da7cbd0be2=1593166132; _lxsdk_cuid=172f019f29bc8-0c195289997faa-143f6256-13c680-172f019f29bc8; _lxsdk=08940570B79511EAA1F189776DB49E05C2ADF24E320243268AAED2B04040EE34; mojo-uuid=e4a79b862f7ffbe071a73e14872d964c; mojo-session-id={"id":"dca07b1449c124511dfbb6ba8eb8d187","time":1593172637349}; mojo-trace-id=2; Hm_lpvt_703e94591e87be68cc8da0da7cbd0be2=1593172668; __mta=174397341.1593166132263.1593166258587.1593172668394.4; _lxsdk_s=172f07d36b0-c5a-882-9f2%7C%7C4'
myurl = 'https://maoyan.com/films?showType=3'
data = []
list = getMylist(user_agent,coookie,myurl)
for url in list :
listtemp = getMyInfo(user_agent,coookie,url)
data.append(listtemp)
movie1 = pd.DataFrame(data = data)
movie1.to_csv('./movie1.csv', encoding='utf8', index=False, header=False)
print("end-time:"+time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))<file_sep>/week02/scrapys/scrapys/pipelines.py
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
import pymysql
dbInfo = {
'host' : 'localhost',
'port' : 3306,
'user' : 'root',
'password' : '',
'db' : 'scrapys'
}
class ScrapysPipeline:
def __init__(self):
try :
self.conn = pymysql.connect(
host = dbInfo['host'],
port = dbInfo['port'],
user = dbInfo['user'],
password = dbInfo['<PASSWORD>'],
db = dbInfo['db']
)
except Exception as e:
print("----未能正常连接数据库----")
self.conn = None
def process_item(self, item, spider):
time = item['time']
name = item['name']
type = item['type']
output = f'{time},{name},{type}\r\n'
with open('./maoyanmovie.csv', 'a+', encoding='utf-8') as article:
article.write(output)
if self.conn != None :
self.commitmysql(self,item)
return item
def commitmysql(self , item ):
try:
sql = "INSERT INTO scrapys_maoyan (name.type,time) VALUES (%s,%s,%s)"
self.conn.execute(sql,item)
except Exception as e :
creatTable = "CREATE TABLE scrapys_maoyan (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL DEFAULT '', type VARCHAR(255) NOT NULL DEFAULT '', time VARCHAR(255) NOT NULL DEFAULT '')"
self.conn.execute(creatTable)
sql = "INSERT INTO scrapys_maoyan (name.type,time) VALUES (%s,%s,%s)"
self.conn.execute(sql, item)
<file_sep>/week04/NOTE.md
学习笔记
data = pandas.DataFrame({
'id':numpy.arange(1,16),
'age':numpy.random.randint(20,90,15)
})
1. SELECT * FROM data;
data
2. SELECT * FROM data LIMIT 10;
data.iloc[:10]
3. SELECT id FROM data; //id 是 data 表的特定一列
data['id']
4. SELECT COUNT(id) FROM data;
data.id.shape[0]
5. SELECT * FROM data WHERE id<1000 AND age>30;
data[(data['id']<1000) & (data['age']>30)]
6. SELECT id,COUNT(DISTINCT order_id) FROM table1 GROUP BY id;
data.groupby('id').aggregate({'id': 'count', })
7. SELECT * FROM table1 t1 INNER JOIN table2 t2 ON t1.id = t2.id;
data.merge(data, left_on='id', right_on='id2')
8. SELECT * FROM table1 UNION SELECT * FROM table2;
pd.concat([data, data2])
9. DELETE FROM table1 WHERE id=10;
data = data.loc[data['id'] != 10]
10. ALTER TABLE table1 DROP COLUMN column_name;
data.rename(columns={'gender': 'id'}, inplace=True)<file_sep>/week02/requsets_webdriver.py
from selenium import webdriver
import time
try:
browser = webdriver.Chrome()
browser.get('https://shimo.im/login?from=home')
time.sleep(1)
browser.find_element_by_xpath('//*[@id="root"]/div/div[2]/div/div/div/div[2]/div/div/div[1]/div[1]/div/input').send_keys("")
browser.find_element_by_xpath('//*[@id="root"]/div/div[2]/div/div/div/div[2]/div/div/div[1]/div[2]/div/input').send_keys("")
time.sleep(1)
browser.find_element_by_xpath('//*[@id="root"]/div/div[2]/div/div/div/div[2]/div/div/div[1]/button').click()
cookie = browser.get_cookies()
print(cookie)
time.sleep(3)
except Exception as e:
print(e)
finally:
browser.close()
|
9d87ac18b2b5e37863d45676385411c48fbf23af
|
[
"Markdown",
"Python"
] | 9 |
Markdown
|
hejw123/Python001-class01
|
483194d119788e1db7c8f71c9c3805d4303f5cf6
|
d7192e4abb52ae68a894dcf898bf6f12a5a4f89e
|
refs/heads/main
|
<repo_name>Synammon/MonoGame.Android.HighScores<file_sep>/HighScores/HighScoreDataStore.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using SQLite;
namespace HighScores
{
class HighScoreDataStore
{
readonly SQLiteAsyncConnection _database;
public HighScoreDataStore()
{
string dbPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData);
dbPath = Path.Combine(dbPath, "highscoredata.sqlite");
_database = new SQLiteAsyncConnection(dbPath);
_database.CreateTableAsync<HighScore>().Wait();
}
public async Task<bool> AddAsync(HighScore HighScore)
{
await _database.InsertAsync(HighScore);
return await Task.FromResult(true);
}
public async Task<bool> DeleteAsync(string id)
{
await _database.DeleteAsync(id);
return await Task.FromResult(true);
}
public async Task<HighScore> GetAsync(string id)
{
return await _database.GetAsync<HighScore>(id);
}
public async Task<List<HighScore>> GetAsync(bool forceRefresh = false)
{
return await _database.Table<HighScore>().ToListAsync();
}
public async Task<int> UpdateAsync(HighScore HighScore)
{
return await _database.UpdateAsync(HighScore);
}
}
}<file_sep>/README.md
# MonoGame.Android.HighScores
How to save high scores using SQlite
<file_sep>/HighScores/Game1.cs
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HighScores
{
public class Game1 : Game
{
private GraphicsDeviceManager _graphics;
private SpriteBatch _spriteBatch;
HighScoreDataStore _highScores;
SpriteFont _font;
public Game1()
{
_graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
IsMouseVisible = true;
_highScores = new HighScoreDataStore();
// Task<bool> result = InsertData(); // Only run this once
}
public async Task<bool> InsertData()
{
try
{
await _highScores.AddAsync(new HighScore() { Id = 0, Name = "Jill", Score = 10000 });
await _highScores.AddAsync(new HighScore() { Id = 1, Name = "Dave", Score = 5000 });
await _highScores.AddAsync(new HighScore() { Id = 2, Name = "Fred", Score = 9000 });
}
catch
{
return false;
}
return true;
}
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
}
protected override void LoadContent()
{
_spriteBatch = new SpriteBatch(GraphicsDevice);
// TODO: use this.Content to load your game content here
_font = Content.Load<SpriteFont>("fonts/font");
}
protected override void Update(GameTime gameTime)
{
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
// TODO: Add your update logic here
base.Update(gameTime);
}
protected async override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
List<HighScore> scores = await _highScores.GetAsync(false);
List<HighScore> sorted = scores.OrderByDescending(o => o.Score).ToList();
_spriteBatch.Begin();
Vector2 position = new Vector2();
foreach (HighScore score in sorted)
{
_spriteBatch.DrawString(_font, score.Name + " - " + score.Score, position, Color.White);
position.Y += _font.LineSpacing;
}
_spriteBatch.End();
base.Draw(gameTime);
}
}
}
|
8bec92f87ea2e27fcee0fae2b8602a8556c4c746
|
[
"Markdown",
"C#"
] | 3 |
C#
|
Synammon/MonoGame.Android.HighScores
|
c98a6f79d7e05966c91374c93f77838c7d9441fb
|
4b8428da4bdeac0427d2ec2432aaae242e758e87
|
refs/heads/master
|
<file_sep>class Zydis < Formula
desc "Fast and lightweight x86/x86-64 disassembler library."
homepage "https://github.com/zyantific/zydis"
url "https://github.com/zyantific/zydis/archive/v2.0.2.tar.gz"
sha256 "bd711102a5a30096562a7cb60bafbc9c4a2441ce5463a59f4d16f2dd73f9fb72"
head "https://github.com/zyantific/zydis.git"
version "2.0.2"
depends_on "cmake" => :build
depends_on :macos => :sierra
def install
system "cmake", ".", *std_cmake_args
system "make", "install"
end
end
<file_sep>class Netmaj < Formula
desc "Network Mahjong game."
homepage "https://github.com/CecilHarvey/netmaj"
url "https://github.com/CecilHarvey/netmaj/archive/50ab9a5d7f34c739daa5b742972692e7656c02ad.tar.gz"
sha256 "1fb79bb85d2c35a7845348aed3dca249ef2874811f8306c294bc44f615bb3764"
head "https://github.com/CecilHarvey/netmaj.git"
version "0.9.git20190904"
depends_on :x11
def install
system "make", "PREFIX=#{prefix}"
system "make", "PREFIX=#{prefix}", "install"
end
end
<file_sep>class Brpc < Formula
desc "Industrial-grade RPC framework used throughout Baidu, with 1,000,000+ instances and thousands kinds of services."
homepage "https://github.com/apache/incubator-brpc"
url "https://github.com/apache/incubator-brpc/archive/d4fa4e87bee955dea2d9a1bb0090ad48b068e9a3.tar.gz"
sha256 "e82d5d9e548e44c336b0a2df11dc70d073edf6c080680fe411f15d991c884347"
head "https://github.com/apache/incubator-brpc.git"
version "0.9.git20190904"
depends_on "cmake" => :build
depends_on "boost"
depends_on "leveldb"
depends_on "protobuf"
depends_on "gflags"
depends_on "openssl"
depends_on :macos => :sierra
def install
system "cmake", ".", *std_cmake_args
system "make", "install"
end
end
|
b083d4f080fef2207802d8ff18d34a17d74e021b
|
[
"Ruby"
] | 3 |
Ruby
|
CecilHarvey/homebrew-Whistler
|
ebe156c3dc36dc8d45f73fea599e84f4ff9646ee
|
40699af9eae5f4cfb0555dac46b4d35f50df09fa
|
refs/heads/main
|
<repo_name>Fernandovi4/React_Social_Network<file_sep>/src/Api/Api-service.js
import axios from "axios";
const axiosInstance = axios.create({
withCredentials: true,
baseURL: `https://social-network.samuraijs.com/api/1.0/`,
headers: {
'API-KEY': '<KEY>'
}
})
export const usersApi = {
getUsers(currentPage = 1, pageSize = 10) {
return axiosInstance.get(`users/?page=${currentPage}&count=${pageSize}`)
.then(response => response.data)
},
unfollowUser(userId) {
return axiosInstance.delete(`follow/${userId}`)
},
followUser(userId) {
return axiosInstance.post(`follow/${userId}`)
},
getUsersProfile(userId) {
console.log('Use profilrApi.getUsersProfile')
return profileApi.getUsersProfile(userId)
}
}
export const profileApi = {
getUsersProfile(userId) {
return axiosInstance.get(`profile/${userId}`)
.then(responce => responce.data)
},
getUsersStatus(userId){
return axiosInstance.get(`profile/status/${userId}`)
.then(responce => responce.data)
},
updateStatus(status){
return axiosInstance.put('profile/status', {status})
}
}
export const authApi = {
authUser() {
return axiosInstance.get(`auth/me`)
.then(responce => responce.data)
},
}
<file_sep>/src/redux/profile-reducer.js
import {profileApi, usersApi} from '../Api/Api-service';
const ADD_POST = 'ADD-POST';
const SET_USER_PROFILE = 'SET-USER-PROFILE'
const SET_USERS_STATUS = 'SET-USERS-STATUS'
const initialState = {
postsData: [
{
id: 1,
likes: 15,
message: '"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."'
},
{
id: 2,
likes: 15,
message: '"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."'
},
{
id: 3,
likes: 15,
message: '"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."'
},
{
id: 4,
likes: 15,
message: '"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."'
},
{
id: 5,
likes: 15,
message: '"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."'
}
],
selectedProfile: null,
status: ''
}
const profileReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_POST:
let newPost = {
id: Date.now(), likes: 0, message: action.text
}
return {
...state,
postsData: [newPost, ...state.postsData]
}
case SET_USER_PROFILE:
return {...state, selectedUser: action.selectedProfile}
case SET_USERS_STATUS:
return {...state, status: action.status}
default:
return state
}
}
export const addPostActionCreator = (text => {
return {type: ADD_POST, text}
})
export const setUserProfile = (selectedProfile) => {
return {type: SET_USER_PROFILE, selectedProfile}
}
export const setUserStatus = (status) => {
return {type: SET_USERS_STATUS, status}
}
//thunks
export const getUserProfileInfo = (userId) => {
return (dispatch) => {
usersApi.getUsersProfile(userId)
.then(data => dispatch(setUserProfile(data)))
}
}
export const getUserStatus = (userId) => {
return (dispatch) => {
profileApi.getUsersStatus(userId)
.then(data => dispatch(setUserStatus(data)))
}
}
export const updatetUserStatus = (status) => {
return (dispatch) => {
profileApi.updateStatus(status)
.then(responce => {
if(responce.data.resultCode === 0){
dispatch(setUserStatus(status))
}
})
}
}
export default profileReducer<file_sep>/src/Components/pages/Profile/MyPosts/Status/Status.jsx
import React, {useRef} from "react";
import cl from './Satus.module.css'
const Status = (props) => {
console.log(props)
const [editMode, setEditmode] = React.useState(false)
const [status, setStatus] = React.useState(props.status)
const inputEl = useRef(null);
const editModeOn = () => {
setEditmode(true)
}
const editModeOff = () => {
setEditmode(false)
props.updatetUserStatus(status)
}
return(
<div className={cl.status__wrapper}>
<span>Status: </span>
{!editMode &&
<h3
className={cl.status__title}
onDoubleClick={editModeOn}
>"{props.status || 'no status for this user'}"</h3>
}
{editMode &&
<input
autoFocus={true}
className={cl.status__input}
ref={inputEl}
onChange={(e) => setStatus(e.target.value)}
onBlur={editModeOff}
value={status}
/>
}
</div>
)
}
export default Status<file_sep>/src/Components/pages/Login/Login.jsx
import React from "react";
import cl from './Login.module.css'
import LoginReduxForm from "./LoginForm/LoginForm";
const Login = () => {
const onSubmit = (loginData) => {
console.log(loginData)
}
return (
<div className={cl.login__wrapper}>
<h1 className={cl.form__title} >Login</h1>
<LoginReduxForm onSubmit={onSubmit}/>
</div>
);
}
export default Login<file_sep>/src/Components/pages/Profile/MyPosts/MyPosts.jsx
import React from 'react'
import cl from './MyPosts.module.css'
import Post from './Post/Post'
import {Field, reduxForm} from "redux-form";
import {Button} from "../../../shared/Button/Button";
const MyPosts = (props) => {
const postElements = props.postsData.map((p) => <Post
key={p.id} message={p.message} likes={p.likes}/>)
const addNewMessage = (values) => {
console.log('values: ', values)
props.onAddPost(values.newPost)
}
return (
<div>
<div>
<NewPostReduxForm onSubmit={addNewMessage}/>
</div>
<div className={cl.posts__wrapper}>
{postElements}
</div>
</div>
)
}
const NewPostForm = (props) => {
return (
<form className={cl.post__create} onSubmit={props.handleSubmit}>
<Field
component="textarea"
name='newPost'
cols='125'
/>
<Button
title={'New Post'}
className={cl.newPost__btn}
width={'150px'}/>
</form>
)
}
const NewPostReduxForm = reduxForm({form: 'newPostForm'})(NewPostForm)
export default MyPosts<file_sep>/src/Components/pages/Test/Button/Button.jsx
import React from 'react';
import classes from './Button.module.css'
const Button = ({
parentCallback,
parentCallback2,
parentCallback4,
parentCallback5,
counter,
clickCounter
}) => {
return (
<div className={classes.wrapper}>
<div className={classes.buttons}>
<button
className={classes.btn}
onClick={() => {
parentCallback2(counter += 1)
parentCallback(clickCounter += 1)
}
}
>Increase
</button>
<button
className={classes.btn}
onClick={() => {
parentCallback2(counter -= 1)
parentCallback(clickCounter += 1)
}
}
>Decrease
</button>
<button
className={classes.btn}
onClick={() => parentCallback4()}
onDoubleClick={() => parentCallback5()}
>Reset
</button>
</div>
</div>
)
}
export default Button<file_sep>/src/Components/pages/Users/UsersContainer.jsx
import React from 'react';
import {connect} from 'react-redux';
import {
follow,
unfollow,
getUsersList,
setUsers,
toogleFollowingProgress,
followUser,
unfollowUser
} from '../../../redux/users-reduser';
import UsersFuncComponent from './UsersFuncComponent';
import Loader from '../../shared/Loader/Loader';
import {WithAuthRedirect} from '../../../HighOrderComponents/WithAuthRedirect';
import {compose} from 'redux';
class UsersClassComponent extends React.Component {
componentDidMount() {
this.props.getUsersList(this.props.currentPage, this.props.pageSize)
}
onPageChange = (page) => {
this.props.getUsersList(page, this.props.pageSize)
}
render() {
return (
<>
{this.props.isFetchingData ?
<Loader/> :
<UsersFuncComponent
pageSize={this.props.pageSize}
currentPage={this.props.currentPage}
unfollow={this.props.unfollow}
follow={this.props.follow}
users={this.props.users}
onPageChange={this.onPageChange}
followingInProgress={this.props.followingInProgress}
toogleFollowingProgress={this.props.toogleFollowingProgress}
followUser={this.props.followUser}
unfollowUser={this.props.unfollowUser}
/>}
</>
);
}
}
const mapStateToProps = (state) => {
return {
users: state.usersPage.users,
pageSize: state.usersPage.pageSize,
totalUsersCount: state.usersPage.totalUsersCount,
currentPage: state.usersPage.currentPage,
isFetchingData: state.usersPage.isFetchingData,
followingInProgress: state.usersPage.followingInProgress
}
}
export default compose(
connect(mapStateToProps, {
follow, unfollow,
getUsersList, setUsers,
followUser, unfollowUser,
toogleFollowingProgress
}),
WithAuthRedirect
)(UsersClassComponent)<file_sep>/src/Components/shared/Button/Button.jsx
import React from 'react'
import cl from './Button.module.css'
export const Button = ({title, width}) => {
return (
<button
className={cl.buttonComponent}
style={{width: width}}
>
{title}
</button>
)
}
<file_sep>/src/Components/pages/Profile/MyPosts/ProfileInfo/ProfileInfo.jsx
import React from "react";
import Loader from "../../../../shared/Loader/Loader";
import cl from './ProfileInfo.module.css'
import Status from "../Status/Status";
const ProfileInfo = (props) => {
// console.log('PROPS:', props)
if(!props.selectedUser){
return <Loader/>
}
return(
<>
<div className={cl.profileInfo__wrapper}>
<img className={cl.profileInfo__img} src={props.selectedUser.photos.large} alt="user large ava"/>
<div>
<p><span className={cl.profileInfo__titles}>My Name: </span> {props.selectedUser.fullName}</p>
<p><span className={cl.profileInfo__titles}>About Me: </span> {props.selectedUser.aboutMe}</p>
<p><span className={cl.profileInfo__titles}>Job status: </span> {props.selectedUser.lookingForAJob ? props.selectedUser.lookingForAJobDescription : 'Leave me alone!!!'}</p>
</div>
<div className={cl.profileInfo__contacts}>
<p><span className={cl.profileInfo__titles}>facebook: </span> {props.selectedUser.contacts.facebook}</p>
<p><span className={cl.profileInfo__titles}>github: </span> {props.selectedUser.contacts.github}</p>
<p><span className={cl.profileInfo__titles}>instagram: </span> {props.selectedUser.contacts.instagram}</p>
</div>
</div>
<Status {...props}/>
<hr/>
</>
)
}
export default ProfileInfo<file_sep>/src/Components/pages/Posts/Search/Search.jsx
import React from 'react';
import classes from './Search.module.css';
const Search = ({searchInPosts}) => {
return (
<div className={classes.searchComponent}>
<input className={classes.search}
type='search'
placeholder={'Find what YOU want!'}
onChange={event => {
searchInPosts(event.target.value)
}}
/>
<button className={classes.searchBtn} type='button'>Search</button>
</div>
)
}
export default Search<file_sep>/src/redux/redux-store.js
import {applyMiddleware, combineReducers, compose, createStore} from 'redux'
import profileReducer from './profile-reducer'
import dialogsReducer from './dialogs-reduser'
import sidebarReducer from './sidebar-reduser'
import usersReducer from './users-reduser'
import authReduser from './auth-reducer'
import thunkMiddleware from 'redux-thunk'
import { reducer as formReducer } from 'redux-form'
const redusers = combineReducers({
profilePage: profileReducer,
dialogsPage: dialogsReducer,
sideBar: sidebarReducer,
usersPage: usersReducer,
auth: authReduser,
form: formReducer
})
let store = createStore(redusers,
compose(
applyMiddleware(thunkMiddleware),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
)
)
window.store = store
export default store<file_sep>/src/Components/pages/Posts/PlacegolderPost/PlaceholderPost.jsx
import React, {useState} from 'react';
import classes from './PlaceholderPost.module.css'
const PlaceholderPost = ({post, handleRemove}) => {
let [isEditable, setContentEditable] = useState(false);
const handleClick = () => {
setContentEditable(isEditable = !isEditable)
}
return (
<div className={classes.singlePost}>
<div className={classes.singlePostInner}>
<span className={classes.id}>Id:{(post.id)}</span>
<h4 className={classes.title}> Title: {(post.title)}</h4>
<p className={classes.text} contentEditable={isEditable}>Text: {(post.body)}</p>
</div>
<div className={classes.buttonsWrapper}>
<button className={`${classes.editBtn} ${classes.btn}`}
onClick={() => handleClick()}
>
Edit / Save
</button>
<button
onClick={() => handleRemove(post.id)}
className={`${classes.removeBtn} ${classes.btn}`}>
Delete
</button>
</div>
</div>
)
}
export default PlaceholderPost<file_sep>/src/App.js
import React from 'react';
import './App.css';
import {Route} from 'react-router';
import {BrowserRouter} from 'react-router-dom'
import News from './Components/pages/News/News';
import Music from './Components/pages/Music/Music';
import Test from './Components/pages/Test/Test'
import Settings from './Components/pages/Settings/Settings';
import Footer from './Components/shared/Footer/Footer';
import Posts from './Components/pages/Posts/Posts'
import SuperDialogsContainer from "./Components/pages/Dialogs/DialogsContainer";
import NavbarContainer from "./Components/shared/Navbar/NavbarContainer";
import UsersContainer from "./Components/pages/Users/UsersContainer";
import ProfileContainer from "./Components/pages/Profile/ProfileContainer";
import HeaderContainer from "./Components/shared/Header/HeaderContainer";
import Login from "./Components/pages/Login/Login";
const App = (props) => {
return (
<BrowserRouter>
<div className='app-wrapper'>
<HeaderContainer />
<NavbarContainer />
<div className='app-wrapper-content'>
<Route path='/login' render={() => <Login />}
/>
<Route path='/profile/:userId?'
render={() => <ProfileContainer />}
/>
<Route path='/dialogs'
render={() => <SuperDialogsContainer />}
/>
<Route path='/users' render={() => <UsersContainer />}
/>
<Route path='/news' render={() => <News />}
/>
<Route path='/music' render={() => <Music />}
/>
<Route path='/settings' render={() => <Settings />}
/>
<Route path='/test' render={() => <Test />}
/>
<Route path='/posts' render={() => <Posts />}
/>
</div>
</div>
<Footer />
</BrowserRouter>
);
}
export default App;
<file_sep>/src/redux/users-reduser.js
import {usersApi} from '../Api/Api-service';
const FOLLOW = 'FOLLOW'
const UNFOLLOW = 'UNFOLLOW'
const SET_USERS = 'SET-USERS'
const SET_CURRENT_PAGE = 'SET-CURRENT-PAGE'
const SET_TOTAL_USERS_COUNT = 'SET-TOTAL-USERS-COUNT'
const TOGGLE_LOADER = 'TOGGLE-LOADER'
const FOLLOWING_IN_PROGRESS = 'FOLLOWING-IN-PROGRESS'
const initialState = {
users: [],
pageSize: 10,
totalUsersCount: 0,
currentPage: 1,
isFetchingData: false,
followingInProgress: []
}
const usersReducer = (state = initialState, action) => {
switch (action.type) {
case FOLLOW:
return {
...state,
users: state.users.map(u => {
return (u.id !== action.userId) ? u : {...u, followed: true}
})
}
case UNFOLLOW:
return {
...state,
users: state.users.map(u => {
return (u.id !== action.userId) ? u : {...u, followed: false}
})
}
case SET_USERS:
return {
...state,
users: action.users
}
case SET_CURRENT_PAGE:
return {
...state,
currentPage: action.page
}
case SET_TOTAL_USERS_COUNT:
return {
...state,
totalUsersCount: action.totalUsersCount
}
case TOGGLE_LOADER:
return {
...state,
isFetchingData: action.isFetchingData
}
case FOLLOWING_IN_PROGRESS:
return {
...state,
followingInProgress: action.isFetchingData ?
[state.followingInProgress, action.userId] :
state.followingInProgress.filter(el => el.id !== action.userId)
}
default:
return state
}
}
export const follow = (userId) => ({type: FOLLOW, userId})
export const unfollow = (userId) => ({type: UNFOLLOW, userId})
export const setUsers = (users) => ({type: SET_USERS, users})
export const setCurrentPage = (page) => ({type: SET_CURRENT_PAGE, page})
export const setTotalUsersCount = (totalUsersCount) => ({type: SET_TOTAL_USERS_COUNT, totalUsersCount})
export const toggleLoader = (isFetchingData) => ({type: TOGGLE_LOADER, isFetchingData})
export const toogleFollowingProgress = (isFetchingData, userId) => ({
type: FOLLOWING_IN_PROGRESS,
isFetchingData,
userId
})
export const getUsersList = (currentPage, pageSize) => {
return (dispatch) => {
dispatch(toggleLoader(true))
usersApi.getUsers(currentPage, pageSize)
.then((data) => {
dispatch(setCurrentPage(currentPage))
dispatch(setUsers(data.items))
dispatch(setTotalUsersCount(data.totalCount))
dispatch(toggleLoader(false))
})
}
}
export const followUser = (userId) => {
return (dispatch) => {
dispatch(toogleFollowingProgress(true, userId))
usersApi.followUser(userId)
.then((response) => {
if (response.data.resultCode === 0) {
dispatch(follow(userId))
}
dispatch(toogleFollowingProgress(false, userId))
})
}
}
export const unfollowUser = (userId) => {
return (dispatch) => {
dispatch(toogleFollowingProgress(true, userId))
usersApi.unfollowUser(userId)
.then((response) => {
if (response.data.resultCode === 0) {
dispatch(unfollow(userId))
}
dispatch(toogleFollowingProgress(false, userId))
})
}
}
export default usersReducer<file_sep>/src/Components/pages/Dialogs/Dialogs.jsx
import React from 'react'
import cl from './Dialogs.module.css'
import Dialog from './Dialog/Dialog';
import Message from './Message/Message';
import {Field, reduxForm} from "redux-form";
const Dialogs = (props) => {
const addNewMessage = values => props.onAddMessage(values.newMessage)
const dialogsElements = props.dialogsPage.dialogs.map((d) => <Dialog
key={d.id} name={d.name} id={d.id}/>)
const messageElements = props.dialogsPage.messages.map((m) => <Message
key={m.id} message={m.message} authorId={m.authorId}/>)
return (
<div className={cl.dialogs}>
<div className={cl.dialogs__wrapper}>
<h4 className={cl.title}>Dialogs</h4>
<div className={cl.dialog_name}>
{dialogsElements}
</div>
</div>
<div className={cl.messages__wrapper}>
<h4 className={cl.title}>Messages</h4>
<div className={cl.messages}>
{messageElements}
</div>
<hr/>
<AddMessageFormRedux onSubmit={addNewMessage}/>
<hr/>
</div>
</div>
)
}
const AddMessageForm = (props) => {
return(
<form onSubmit={props.handleSubmit} className={cl.newMessage__wrapper}>
<Field component= "textarea" name='newMessage'/>
<button className={cl.sendBtn}>Send ➣</button>
</form>
)
}
const AddMessageFormRedux = reduxForm({form:'DialogAddMessageForm'})(AddMessageForm)
export default Dialogs <file_sep>/src/Components/pages/Test/Test.jsx
import React from 'react'
import classes from './Test.module.css'
import Button from './Button/Button.jsx'
import Display from './Display/Display';
import Input from './Input/Input';
const Test = () => {
let [clickCounter, setClickCounter] = React.useState(0)
let [counter, setCount] = React.useState(0);
let [user, setUser] = React.useState({name: '', age: 0})
const handleClickCounter = (clickCounter) => setClickCounter(clickCounter)
const handleClicks = (counter) => setCount(counter)
const resetCounter = () => setCount(0)
const resetClickCounter = () => setClickCounter(0)
const handleNameChange = (name, age) => setUser({name, age})
return (
<div className={classes.parent}>
<Button
parentCallback={handleClickCounter}
parentCallback2={handleClicks}
parentCallback4={resetCounter}
parentCallback5={resetClickCounter}
counter={counter}
clickCounter={clickCounter}
/>
<Input
parentCallback6={handleNameChange}
name={user.name}
age={user.age}
/>
<Display
user={user}
counter={counter}
clickCounter={clickCounter}
name={user.name}
age={user.age}
/>
</div>
)
}
export default Test<file_sep>/src/Components/pages/Dialogs/Dialog/Dialog.jsx
import React from 'react';
import cl from './Dialog.module.css'
import {NavLink} from 'react-router-dom';
const Dialog = ({name, id}) => {
return (
<div>
<NavLink
to={'/dialogs/' + id}
className={cl.link}
activeClassName={cl.active}
>{name}</NavLink>
</div>)
}
export default Dialog<file_sep>/src/redux/dialogs-reduser.js
const ADD_MESSAGE = 'ADD-MESSAGE'
const initialState = {
dialogs: [
{id: 1, name: 'Peter'},
{id: 2, name: 'Lena'},
{id: 3, name: 'Arina'},
{id: 4, name: 'Emily'},
{id: 5, name: 'Lakuka'}
],
messages: [
{id: 1, authorId: 1, message: 'Hello'},
{id: 2, authorId: 2, message: 'Hello Hello'},
{id: 3, authorId: 1, message: 'Hello Hello Hello'},
{id: 4, authorId: 2, message: 'Hello Hello Hello Hello'},
{id: 5, authorId: 1, message: 'Hello Hello Hello Hello Hello'}
]
}
const dialogsReducer = (state = initialState, action) => {
switch (action.type) {
case ADD_MESSAGE:
let newMessage = {
id: Date.now(),
authorId: 1,
message: action.newMessageText
}
return {
...state,
messages: [...state.messages, newMessage]
}
default:
return state
}
}
export const addMessageActionCreator = (newMessageText) => ({type: ADD_MESSAGE, newMessageText})
export default dialogsReducer<file_sep>/src/redux/store.js
// import sidebarReducer from './sidebar-reduser';
// import profileReducer from './profile-reducer';
// import dialogsReducer from './dialogs-reduser';
//
// let store = {
// _state: {
// loggedUser: {userid: 1, name: 'Peter'},
// profilePage: {
// postsData: [
// {
// id: 1,
// likes: 15,
// message: '"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."'
// },
// {
// id: 2,
// likes: 15,
// message: '"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."'
// },
// {
// id: 3,
// likes: 15,
// message: '"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."'
// },
// {
// id: 4,
// likes: 15,
// message: '"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."'
// },
// {
// id: 5,
// likes: 15,
// message: '"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."'
// }
// ],
// newPostText: 'козяка-базяка',
// },
// dialogsPage: {
// newMessageText: 'козямбендо',
// dialogs: [
// {id: 1, name: 'Peter'},
// {id: 2, name: 'Lena'},
// {id: 3, name: 'Arina'},
// {id: 4, name: 'Emily'},
// {id: 5, name: 'Lakuka'}
// ],
// messages: [
// {id: 1, authorId: 1, message: 'Hello'},
// {id: 2, authorId: 2, message: 'Hello Hello'},
// {id: 3, authorId: 1, message: 'Hello Hello Hello'},
// {id: 4, authorId: 2, message: 'Hello Hello Hello Hello'},
// {id: 5, authorId: 1, message: 'Hello Hello Hello Hello Hello'}
// ]
// },
// sideBar: {
// friends: [
// {
// id: 1,
// name: 'Ivan',
// avaURL: 'https://st4.depositphotos.com/5934840/23454/v/950/depositphotos_234548768-stock-illustration-construction-worker-profile-avatar-icon.jpg'
// },
// {
// id: 2,
// name: 'Nataly',
// avaURL: 'https://st4.depositphotos.com/5934840/23454/v/950/depositphotos_234548768-stock-illustration-construction-worker-profile-avatar-icon.jpg'
// },
// {
// id: 3,
// name: 'Frank',
// avaURL: 'https://st4.depositphotos.com/5934840/23454/v/950/depositphotos_234548768-stock-illustration-construction-worker-profile-avatar-icon.jpg'
// },
// {
// id: 4,
// name: 'John',
// avaURL: 'https://st4.depositphotos.com/5934840/23454/v/950/depositphotos_234548768-stock-illustration-construction-worker-profile-avatar-icon.jpg'
// },
// {
// id: 5,
// name: '<NAME>',
// avaURL: 'https://st4.depositphotos.com/5934840/23454/v/950/depositphotos_234548768-stock-illustration-construction-worker-profile-avatar-icon.jpg'
// }
// ],
// }
// },
// _callSubscriber() {
// console.log('renderEntireTree')
// },
//
// getState() {
// return this._state
// },
// subscribe(observer) {
// this._callSubscriber = observer
// },
//
// dispatch(action) {
//
// this._state.profilePage = profileReducer(this._state.profilePage, action);
// this._state.dialogsPage = dialogsReducer(this.getState().dialogsPage, action);
// this._state.sideBar = sidebarReducer(this.getState().sideBar, action);
// this._callSubscriber(this.getState());
//
// }
// }
//
//
// export default store;
//
//
//
//
//
<file_sep>/src/Components/shared/Header/Header.jsx
import React from 'react';
import cl from './Header.module.css'
import {NavLink} from "react-router-dom";
const Header = (props) => {
return (
<header className={cl.header}>
<h1 className={cl.header_title}>Social-Dance-Network</h1>
<div className={cl.loginBlock}>
{props.isAuth ? <p>user: {props.login}</p> :
<NavLink to={'/login'} className={cl.navlink}>Log IN</NavLink>
}
</div>
</header>
)
}
export default Header<file_sep>/src/Components/pages/Profile/Profile.jsx
import React from 'react'
import classes from './Profile.module.css'
import MyPostsContainer from "./MyPosts/MyPostsContainer";
import ProfileInfo from "./MyPosts/ProfileInfo/ProfileInfo";
import Status from "./MyPosts/Status/Status";
const Profile = (props) => {
return(
<div >
<div className={classes.content__img} />
{/*<Status status={props.status} updateUserStatus={props.updatetUserStatus}/>*/}
<ProfileInfo {...props} />
<MyPostsContainer store={props.store} />
</div>
)
}
export default Profile <file_sep>/src/Components/pages/Test/Display/Display.js
import React from 'react';
import classes from './Display.module.css'
const Display = ({counter, clickCounter, name, age}) => {
return (
<div className={classes.display}>
<div className={classes.title}>Counter: <span>{counter} </span></div>
<div className={classes.title}>Clicks: <span>{clickCounter}</span></div>
<div className={classes.title}>Name: <span>{name}</span></div>
<div className={classes.title}>Age: <span>{age}</span></div>
Button clicked <span> {clickCounter}</span> times
</div>
)
}
export default Display<file_sep>/src/Components/shared/Navbar/Navbar.jsx
import React from 'react';
import {NavLink} from 'react-router-dom';
import cl from './Navbar.module.css'
import MyFriendInfo from "./myFriendInfo/MyFriendInfo";
const Navbar = ({sideBar}) => {
let friendsElements = sideBar.friends.map(friend => <MyFriendInfo key={friend.id} friend={friend}/>)
return (
<nav className={cl.nav}>
<div className={cl.pageNavigation__wrapper}>
<div className={cl.item}>
<NavLink to="/profile" activeClassName={cl.active}>Profile</NavLink>
</div>
<div className={cl.item}>
<NavLink to="/dialogs" activeClassName={cl.active}>Dialogs</NavLink>
</div>
<div className={cl.item}>
<NavLink to="/users" activeClassName={cl.active}>Users</NavLink>
</div>
<div className={cl.item}>
<NavLink to="/news" activeClassName={cl.active}>News</NavLink>
</div>
<div className={cl.item}>
<NavLink to="/music" activeClassName={cl.active}>Music</NavLink>
</div>
<div className={cl.item}>
<NavLink to="/settings" activeClassName={cl.active}>Settings</NavLink>
</div>
<div className={cl.item}>
<NavLink to="/test" activeClassName={cl.active}>Test</NavLink>
</div>
<div className={cl.item}>
<NavLink to='/posts' activeClassName={cl.active}>PostsJP</NavLink>
</div>
</div>
<h5 className={cl.myFriendsTitle}>My friends</h5>
<div className={cl.friendsInfo__Wrapper}>
{friendsElements}
</div>
</nav>
)
}
export default Navbar<file_sep>/src/redux/sidebar-reduser.js
const initialState = {
friends: [
{
id: 1,
name: 'Ivan',
avaURL: 'https://st4.depositphotos.com/5934840/23454/v/950/depositphotos_234548768-stock-illustration-construction-worker-profile-avatar-icon.jpg'
},
{
id: 2,
name: 'Nataly',
avaURL: 'https://st4.depositphotos.com/5934840/23454/v/950/depositphotos_234548768-stock-illustration-construction-worker-profile-avatar-icon.jpg'
},
{
id: 3,
name: 'Frank',
avaURL: 'https://st4.depositphotos.com/5934840/23454/v/950/depositphotos_234548768-stock-illustration-construction-worker-profile-avatar-icon.jpg'
},
{
id: 4,
name: 'John',
avaURL: 'https://st4.depositphotos.com/5934840/23454/v/950/depositphotos_234548768-stock-illustration-construction-worker-profile-avatar-icon.jpg'
}
],
}
const sidebarReducer = (state = initialState, action) => {
return state
}
export default sidebarReducer
<file_sep>/src/Components/pages/Test/Input/Input.jsx
import React from 'react';
import classes from './Input.module.css'
const Input = ({parentCallback6, name, age}) => {
return (
<div className={classes.inputs}>
<div className={classes.inputsInner}>
<label
className={classes.label}
htmlFor='name'>Name: </label>
<input
className={classes.input}
name={'name'}
type='text'
placeholder={'type name here'}
value={name}
onChange={e => parentCallback6(e.target.value, age)}/>
</div>
<div className={classes.inputsInner}>
<label
className={classes.label}
htmlFor='age'>Age: </label>
<input type='number'
className={classes.input}
name={'age'}
placeholder={'choose age'}
value={age}
onChange={e => parentCallback6(name, e.target.value)}/>
</div>
</div>
)
}
export default Input<file_sep>/src/Components/pages/Posts/Posts.jsx
import React, {useState} from 'react'
import PlaceholderPost from './PlacegolderPost/PlaceholderPost';
import classes from './Posts.module.css'
import Loader from '../../shared/Loader/Loader';
import Search from './Search/Search';
const Posts = () => {
const URL = 'https://jsonplaceholder.typicode.com/posts'
let isLoading = false
let [posts, setPosts] = useState(null);
let [searchString, setSearchString] = useState('')
const getFiltrationTarget = (string) => {
setSearchString(string)
filtratePosts(searchString)
}
const filtratePosts = (searchString) => {
if (searchString !== '') {
const results = posts.filter((post) => {
return post.title.toLowerCase().startsWith(searchString.toLowerCase());
});
setPosts(results);
} else {
setPosts(posts);
}
}
const getData = async () => {
isLoading = true
let response = await fetch(URL);
if (response.ok) {
let json = await response.json();
setPosts(posts = json)
} else {
console.log('Ошибка HTTP: ' + response.status)
}
}
const handleRemove = index => {
setPosts(posts = posts.filter((item) => item.id !== index))
}
return (
<div>
<div className={classes.header}>
<Search
searchInPosts={getFiltrationTarget}
searchString={searchString}
/>
<button onClick={getData} className={classes.btn}>
Get posts from server
</button>
</div>
{isLoading && <Loader/>}
{posts && posts.map((post) => <PlaceholderPost
key={post.id}
post={post}
handleRemove={handleRemove}/>)
}
</div>
)
}
export default Posts<file_sep>/src/Components/shared/Navbar/myFriendInfo/MyFriendInfo.jsx
import React from "react";
import cl from './MyFrienInfo.module.css'
const MyFriendInfo = (props) => {
return (
<div className={cl.myFriendInfo}>
<img className={cl.myFriendAvatar} src={props.friend.avaURL} alt="user avatar"/>
<h6 className={cl.friendName}>{props.friend.name}</h6>
</div>
)
}
export default MyFriendInfo
|
9fc6768742dd03d27523505c5c54b5e4e6ddfe34
|
[
"JavaScript"
] | 27 |
JavaScript
|
Fernandovi4/React_Social_Network
|
493fcbe17b564ad4c76c0cd3cddd055c0fc87a0f
|
ac7031f59ca930ef70b6a4641b45724b2c19c841
|
refs/heads/main
|
<repo_name>nachovera93/heroku-prueba<file_sep>/requirements.txt
#Adafruit-Blinka==6.10.3
#adafruit-circuitpython-dht==3.6.1
#Adafruit-DHT==1.4.0
#Adafruit-PlatformDetect==3.14.2
#Adafruit-PureIO==1.1.9
#Adafruit-Python-DHT==1.4.0
click==8.0.1
continuous-threading==2.0.4
DateTime==4.3
Flask==2.0.1
gunicorn==20.1.0
importlib-metadata==4.6.0
itsdangerous==2.0.1
Jinja2==3.0.1
MarkupSafe==2.0.1
numpy==1.21.0
#pkg-resources==0.0.0
psutil==5.8.0
pyftdi==0.53.1
pyserial==3.5
pytz==2021.1
pyusb==1.1.1
rpi-ws281x==4.3.0
RPi.GPIO==0.7.0
scipy==1.7.0
sysv-ipc==1.1.0
typing-extensions==3.10.0.0
Werkzeug==2.0.1
zipp==3.4.1
zope.interface==5.4.0
<file_sep>/medidor/lib/python3.7/site-packages/continuous_threading/__meta__.py
name = 'continuous_threading'
version = '2.0.4'
description = 'Library to help manage threads that run continuously for a long time.'
url = 'https://github.com/justengel/continuous_threading'
author = '<NAME>'
author_email = '<EMAIL>'
<file_sep>/app.py
#import ast
#import csv
import threading
#from PIL import ImageTk, Image
#import pytz
#from datetime import datetime
import datetime
#import matplotlib
from scipy import interpolate
from scipy.fft import fft, fftfreq
from scipy.interpolate import lagrange
from scipy import signal
from scipy.signal import savgol_filter
#import pandas as pd
import numpy as np
from flask import Flask,render_template, redirect, request
import subprocess
from time import sleep
#import psutil
import sys
import socket
import RPi.GPIO as GPIO
import time
#from PIL import Image
#from PIL import ImageTk
import glob
import os
import serial
#from matplotlib.backends.backend_tkagg import (
# FigureCanvasTkAgg, NavigationToolbar2Tk)
#import matplotlib.pyplot as plt
#from matplotlib.figure import Figure
#plt.style.use('ggplot')
#from flask_moment import Moment
import math
import board
#import adafruit_dht
#dhtDevice = adafruit_dht.DHT11(board.D18)
app = Flask(__name__)
#global list_Current1
#global list_Current2
#global list_Current3
#global list_Voltage1
#global list_temp
#moment = Moment(app)
"""
if not os.path.exists('log/'):
os.makedirs('log/')
if not os.path.exists('images/'):
os.makedirs('images/')
if not os.path.exists('images/fft'):
os.makedirs('images/fft')
if not os.path.exists('images/fft/voltage'):
os.makedirs('images/fft/voltage')
if not os.path.exists('images/fft/current1'):
os.makedirs('images/fft/current1')
if not os.path.exists('images/fft/current2'):
os.makedirs('images/fft/current2')
if not os.path.exists('images/fft/current3'):
os.makedirs('images/fft/current3')
if not os.path.exists('images/señal'):
os.makedirs('images/señal')
if not os.path.exists('images/señal/current1'):
os.makedirs('images/señal/current1')
if not os.path.exists('images/señal/current2'):
os.makedirs('images/señal/current2')
if not os.path.exists('images/señal/current3'):
os.makedirs('images/señal/current3')
if not os.path.exists('images/señal/voltage'):
os.makedirs('images/señal/voltage')
#font = {'family': 'serif',
# 'color': 'darkred',
# 'weight': 'normal',
# 'size': 16,
# }
"""
esp32 = serial.Serial('/dev/ttyUSB0', 250000, timeout=0.5)
esp32.flushInput()
#TRIG = 4
#ECHO = 24
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setup(4,GPIO.OUT)
GPIO.setup(24,GPIO.IN)
GPIO.setup(23, GPIO.OUT)
GPIO.setup(8, GPIO.OUT)
GPIO.output(8, GPIO.LOW)
GPIO.setwarnings(False)
return()
setup()
pins = {
8 : {'name' : 'GPIO 8', 'state' : GPIO.LOW}
}
for pin in pins:
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, GPIO.LOW)
def get_ip_address():
global ip_address
ip_address = ''
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip_address = s.getsockname()[0]
s.close()
#return ip_address
get_ip_address()
def cpu_temp():
thermal_zone = subprocess.Popen(
['cat', '/sys/class/thermal/thermal_zone0/temp'], stdout=subprocess.PIPE)
out, err = thermal_zone.communicate()
cpu_temp = int(out.decode())/1000
return(cpu_temp)
def get_cpuload():
cpuload = psutil.cpu_percent(interval=1, percpu=False)
return str(cpuload)
CPU_temp = 0.0
def getTEMP():
global CPU_temp
CPU_temp = round(cpu_temp(),0)
#print(f'temp cpu: {CPU_temp}')
if CPU_temp > 50:
#print("Ventilador on")
GPIO.output(23, True)
elif CPU_temp <= 40:
#print("Ventilador off")
GPIO.output(23, False)
temperatura = 0.0
humedad = 0.0
"""
def temphum():
global temperatura
global humedad
try:
temperatura = dhtDevice.temperature
#temperature_f = temperature_c * (9 / 5) + 32
humedad = dhtDevice.humidity
#print("Temp: {:.1f} C Humidity: {}% ".format( temperatura, humedad))
#return humidity,temperature
except RuntimeError as error:
# Errors happen fairly often, DHT's are hard to read, just keep going
print(error.args[0])
#time.sleep(2.0)
#continue
#except Exception as error:
# dhtDevice.exit()
# raise error
"""
def distance():
global puerta
global start
global end
try:
GPIO.output(4, True)
time.sleep(0.00001)
GPIO.output(4, False)
while GPIO.input(24) == False:
start = time.time()
while GPIO.input(24) == True:
end = time.time()
sig_time = end-start
distance = round(sig_time / 0.000058,1) #cm
if(distance > 15):
puerta = "Abierta"
elif(distance<15):
puerta = "Cerrada"
print('Distance: {} centimeters'.format(distance))
except RuntimeError as error:
# Errors happen fairly often, DHT's are hard to read, just keep going
print(error.args[0])
# def get_uptime():
# with open('/proc/uptime', 'r') as f:
# uptime_seconds = float(f.readline().split()[0])
# uptime = (timedelta(seconds = uptime_seconds))
# Label(root, text=uptime,font=('Arial', 16)).grid(row=15, column=1)
# return str(uptime)
def getMaxValues(myList, quantity):
return(sorted(list(set(myList)), reverse=True)[:quantity])
#print(f'max : {max(myList)}')
def getMinValues(myList, quantity):
return(sorted(list(set(myList)))[:quantity])
#print(f'max : {max(myList)}')
"""
715/z=282Vpk
z=2.53
748/z=309VPk
z=2.42
"""
def EscalaVoltaje(voltaje):
if(max(voltaje)>=735):
newvoltaje=voltaje*0.57
elif(max(voltaje)<735):
newvoltaje=voltaje*0.545
return newvoltaje
def EscalaCorriente(corriente):
if(max(corriente)>=850):
newcorriente=corriente/54
elif(max(corriente)<850):
newcorriente=corriente/140
return newcorriente
"""
918 = 11.17APeak
"""
"""
428 = 308VPk
392 = 282Vpk
"""
def VoltajeRms(listVoltage):
#global vrms
print(f'maximo voltaje 2 : {max(listVoltage)}')
#listVoltage=listVoltage*0.81
if(max(listVoltage)>=405):
listVoltage=listVoltage*0.73
elif(max(listVoltage)<400):
listVoltage=listVoltage*0.65
N = len(listVoltage)
Squares = []
for i in range(0,N,1): #elevamos al cuadrado cada termino y lo amacenamos
listsquare = listVoltage[i]*listVoltage[i]
Squares.append(listsquare)
SumSquares=0
for i in range(0,N,1): #Sumatoria de todos los terminos al cuadrado
SumSquares = SumSquares + Squares[i]
MeanSquares = (1/N)*SumSquares #Dividimos por N la sumatoria
vrms=np.sqrt(MeanSquares)
print(f'Voltaje RMS : {vrms}')
return vrms
def CorrienteRms(listCurrent):
print(f'maximo corriente 2 : {max(listCurrent)}')
if(max(listCurrent)>1):
listCurrent=listCurrent*1.2
elif(max(listCurrent)<1):
listCurrent=listCurrent/1.5
N = len(listCurrent)
Squares = []
for i in range(0,N,1): #elevamos al cuadrado cada termino y lo amacenamos
listsquare = listCurrent[i]*listCurrent[i]
Squares.append(listsquare)
SumSquares=0
for i in range(0,N,1): #Sumatoria de todos los terminos al cuadrado
SumSquares = SumSquares + Squares[i]
MeanSquares = (1/N)*SumSquares #Dividimos por N la sumatoria
irms=np.sqrt(MeanSquares)
print(f'Corriente RMS : {irms}')
return irms
def graphVoltageCurrent(listVoltage,listCurrent,samplings): ##Grafica corriente y Voltaje
global labelsfp
global valuesvoltage
global valuescurrent
global maxvoltaje
global minvoltaje
#global maxcorriente
#global mincorriente
tiempo = 1/(samplings*(0.001/4200))
tiempoms = np.arange(0,tiempo,tiempo/4096)
my_formatted_list = [ '%.2f' % elem for elem in tiempoms ]
#f = interpolate.interp1d(tiempoms, listVoltage)
#xnew = np.arange(0, 4096, 5) # 2550
# print(f'largo xnew : {len(xnew)}')
#ynew = f(xnew)
valores = listVoltage#[200:4000]
valores2 = listCurrent#[200:4000]
#valores=round(val,1)
valuesvoltage = [ i for i in valores ]
valuescurrent = [ i for i in valores2 ]
#labelsfp = [ i for i in range(0,len(valuesvoltage))]
labelsfp = [ i for i in my_formatted_list]
maxvoltaje = max(valores)+300
minvoltaje = min(valores)-300
def graphVoltage1(list_fftVoltage,maximovoltaje,minimovoltaje,samplings): ##Grafica voltaje CGE
global labelsvoltaje1
global valuesvoltaje1
global ejeyV11
global ejeyV12
valores = list_fftVoltage#[1000:4000]
tiempo = 1/(samplings*(0.001/4200))
tiempoms = np.arange(0,tiempo,tiempo/4096)
my_formatted_list = [ '%.2f' % elem for elem in tiempoms ]
#valores=round(val,1)
valuesvoltaje1 = [ i for i in valores ]
labelsvoltaje1 = [ i for i in my_formatted_list ]
ejeyV11 = maximovoltaje + 100
ejeyV12 = minimovoltaje - 100
print(f'values voltaje: {len(labelsvoltaje1)}')
#Graficar png
# plt.figure(figsize=(15, 5))
#plt.plot(list_fftVoltage)
#oldepoch = time.time()
#st = datetime.datetime.fromtimestamp(
# oldepoch).strftime('%Y-%m-%d-%H:%M:%S')
#plt.title("Voltaje Fase 1", fontdict=font)
#plt.ylabel("Voltage (V-Peak-Peak) ", fontdict=font)
#plt.xlabel("Tiempo(s)", fontdict=font)
# plt.savefig("images/señal/voltage/"+st+"Voltage1.png")
# plt.close(fig)
def graphVoltage2(list_fftVoltage,maximovoltaje,minimovoltaje,samplings): ##Grafica voltaje Paneles
global labelsvoltaje2
global valuesvoltaje2
global ejeyV21
global ejeyV22
valores = list_fftVoltage#[1000:4000]
tiempo = 1/(samplings*(0.001/4200))
tiempoms = np.arange(0,tiempo,tiempo/4096)
my_formatted_list = [ '%.2f' % elem for elem in tiempoms ]
#valores=round(val,1)
valuesvoltaje2 = [ i for i in valores ]
labelsvoltaje2 = [ i for i in my_formatted_list ]
ejeyV21 = maximovoltaje + 100
ejeyV22 = minimovoltaje - 100
def graphVoltage3(list_fftVoltage,maximovoltaje,minimovoltaje,samplings): ##Grafica voltaje Carga
global labelsvoltaje3
global valuesvoltaje3
global ejeyV31
global ejeyV32
valores = list_fftVoltage#[1000:4000]
tiempo = 1/(samplings*(0.001/4200))
tiempoms = np.arange(0,tiempo,tiempo/4096)
my_formatted_list = [ '%.2f' % elem for elem in tiempoms ]
#valores=round(val,1)
valuesvoltaje3 = [ i for i in valores ]
labelsvoltaje3 = [ i for i in my_formatted_list ]
ejeyV31 = maximovoltaje + 100
ejeyV32 = minimovoltaje - 100
def graphCurrent1(list_fftCurrent,samplings): ##Grafica corriente CGE
global labelscurrent1
global valuescurrent1
global ejeycurrent11
global ejeycurrent12
maximocorriente2sinmedia=getMaxValues(list_fftCurrent, 20)
minimocorriente2sinmedia=getMinValues(list_fftCurrent, 20)
maximocorriente = np.median(maximocorriente2sinmedia)
minimocorriente = np.median(minimocorriente2sinmedia)
valores = list_fftCurrent#[1000:4000]
tiempo = 1/(samplings*(0.001/4200))
tiempoms = np.arange(0,tiempo,tiempo/4096)
my_formatted_list = [ '%.2f' % elem for elem in tiempoms ]
#valores2=round(val,1)
valuescurrent1 = [ i for i in valores ]
#labelsI = [ i for i in range(0,len(values2)) ]
labelscurrent1 = [ i for i in my_formatted_list ]
ejeycurrent11 = maximocorriente +1
ejeycurrent12 = minimocorriente -1
def graphCurrent2(list_fftCurrent,samplings): ##Grafica corriente Paneles
global labelscurrent2
global valuescurrent2
global ejeycurrent21
global ejeycurrent22
maximocorriente2sinmedia=getMaxValues(list_fftCurrent, 20)
minimocorriente2sinmedia=getMinValues(list_fftCurrent, 20)
maximocorriente = np.median(maximocorriente2sinmedia)
minimocorriente = np.median(minimocorriente2sinmedia)
valores = list_fftCurrent#[1000:4000]
tiempo = 1/(samplings*(0.001/4200))
tiempoms = np.arange(0,tiempo,tiempo/4096)
my_formatted_list = [ '%.2f' % elem for elem in tiempoms ]
#valores2=round(val,1)
valuescurrent2 = [ i for i in valores ]
#labelsI = [ i for i in range(0,len(values2)) ]
labelscurrent2 = [ i for i in my_formatted_list ]
ejeycurrent21 = maximocorriente +1
ejeycurrent22 = minimocorriente -1
def graphCurrent3(list_fftCurrent,samplings): ##Grafica corriente Carga
global labelscurrent3
global valuescurrent3
global ejeycurrent31
global ejeycurrent32
maximocorriente2sinmedia=getMaxValues(list_fftCurrent, 20)
minimocorriente2sinmedia=getMinValues(list_fftCurrent, 20)
maximocorriente = np.median(maximocorriente2sinmedia)
minimocorriente = np.median(minimocorriente2sinmedia)
valores = list_fftCurrent#[1000:4000]
tiempo = 1/(samplings*(0.001/4200))
tiempoms = np.arange(0,tiempo,tiempo/4096)
my_formatted_list = [ '%.2f' % elem for elem in tiempoms ]
#valores2=round(val,1)
valuescurrent3 = [ i for i in valores ]
#labelsI = [ i for i in range(0,len(values2)) ]
labelscurrent3 = [ i for i in my_formatted_list ]
ejeycurrent31 = maximocorriente +1
ejeycurrent32 = minimocorriente -1
#def graphCurrentjpg(list_fftVoltage, i): #Grafica Corriente
# y = np.linspace(0,len(list_fftVoltage),len(list_fftVoltage))
# i = str(i)
# x = list_fftVoltage*10
#print(f'corriente fase : {i}')
# plt.figure(figsize=(15, 5))
# plt.plot(x)
# oldepoch = time.time()
# st = datetime.datetime.fromtimestamp(
# oldepoch).strftime('%Y-%m-%d-%H:%M:%S')
#plt.title("Corriente Fase"+i+".", fontdict=font)
#plt.ylabel("Corriente (mA-Peak-Peak)", fontdict=font)
# plt.xlabel("Tiempo(s)", fontdict=font)
# print("images/señal/current"+i+"/"+st+"Current"+i+".png")
# plt.savefig("images/señal/current"+i+"/"+st+"Current"+i+".png")
# plt.close(fig)
def graphFFTV1(list_fftVoltages, samplings):
global valuesfftv1
global labelsfftv1
global largoejeyv1
N = len(list_fftVoltages)
T = 1 / samplings
list_fftVoltages -= np.mean(list_fftVoltages)
datosfft = list_fftVoltages * np.hamming(4096)
yf = np.fft.rfft(datosfft)
# yf=fft(list_fftVoltages)
xf = fftfreq(N, T)[:N//2] # tiene un largo de 2048
#print(f'largo xf : {len(xf)}')
mitad = samplings/2
razon = mitad/2048
intervalo = int(np.round(2600/razon,1))
#ejey = np.abs(20*np.log10(yf[:N]))
ejey = 2.0/N * np.abs(yf[0:N//2])
valuesfftv1 = [ i for i in ejey]
xf1 = np.round(xf,1)
labelsfftv1 = [ i for i in xf1[:intervalo] ]
largoejeyv1 = max(ejey)
def graphFFTV2(list_fftVoltages, samplings):
global valuesfftv2
global labelsfftv2
global largoejeyv2
N = len(list_fftVoltages)
T = 1 / samplings
list_fftVoltages -= np.mean(list_fftVoltages)
datosfft = list_fftVoltages * np.hamming(4096)
yf = np.fft.rfft(datosfft)
# yf=fft(list_fftVoltages)
xf = fftfreq(N, T)[:N//2] # tiene un largo de 2048
mitad = samplings/2
razon = mitad/2048
intervalo = int(np.round(2600/razon,1))
ejey = 2.0/N * np.abs(yf[0:N//2])
valuesfftv2 = [ i for i in ejey]
xf1 = np.round(xf,1)
labelsfftv2 = [ i for i in xf1[:intervalo] ]
largoejeyv2 = max(ejey)
def graphFFTV3(list_fftVoltages, samplings):
global valuesfftv3
global labelsfftv3
global largoejeyv3
N = len(list_fftVoltages)
T = 1 / samplings
list_fftVoltages -= np.mean(list_fftVoltages)
datosfft = list_fftVoltages * np.hamming(4096)
yf = np.fft.rfft(datosfft)
# yf=fft(list_fftVoltages)
xf = fftfreq(N, T)[:N//2] # tiene un largo de 2048
mitad = samplings/2
razon = mitad/2048
intervalo = int(np.round(2600/razon,1))
ejey = 2.0/N * np.abs(yf[0:N//2])
valuesfftv3 = [ i for i in ejey]
xf1 = np.round(xf,1)
labelsfftv3 = [ i for i in xf1[:intervalo] ]
largoejeyv3 = max(ejey)
def graphFFTI1(list_fftVoltages, samplings):
global valuesffti1
global labelsffti1
global largoejeyi1
N = len(list_fftVoltages)
T = 1 / samplings
list_fftVoltages -= np.mean(list_fftVoltages)
datosfft = list_fftVoltages * np.hamming(4096)#np.kaiser(N,100)
yf = np.fft.rfft(datosfft)
#yf=fft(list_fftVoltages)
mitad = samplings/2
razon = mitad/((N/2))
intervalo = int(np.round(2600/razon,1))
# print(f'largo yf : {len(yf)}')
xf = fftfreq(N, T)[:N//2] # tiene un largo de 4096
# print(f'largo xf : {len(xf)}')
ejey = 2.0/N * np.abs(yf[0:N//2])
#ejey = np.abs(20*np.log10(yf[:N]))
#print(f'ejey: {ejey}')
valuesffti1 = [ i for i in ejey]
xf1 = np.round(xf,1)
labelsffti1 = [ i for i in xf1[:intervalo] ]
largoejeyi1 = max(ejey)
def graphFFTI2(list_fftVoltages, samplings):
global valuesffti2
global labelsffti2
global largoejeyi2
N = len(list_fftVoltages)
T = 1 / samplings
list_fftVoltages -= np.mean(list_fftVoltages)
datosfft = list_fftVoltages * np.hamming(4096)#np.kaiser(N,100)
yf = np.fft.rfft(datosfft)
#yf=fft(list_fftVoltages)
mitad = samplings/2
razon = mitad/((N/2))
intervalo = int(np.round(2600/razon,1))
# print(f'largo yf : {len(yf)}')
xf = fftfreq(N, T)[:N//2] # tiene un largo de 4096
# print(f'largo xf : {len(xf)}')
ejey = 2.0/N * np.abs(yf[0:N//2])
#ejey = np.abs(20*np.log10(yf[:N]))
#print(f'ejey: {ejey}')
valuesffti2 = [ i for i in ejey]
xf1 = np.round(xf,1)
labelsffti2 = [ i for i in xf1[:intervalo] ]
largoejeyi2 = max(ejey)
def graphFFTI3(list_fftVoltages, samplings):
global valuesffti3
global labelsffti3
global largoejeyi3
N = len(list_fftVoltages)
T = 1 / samplings
list_fftVoltages -= np.mean(list_fftVoltages)
datosfft = list_fftVoltages * np.hamming(4096)#np.kaiser(N,100)
yf = np.fft.rfft(datosfft)
#yf=fft(list_fftVoltages)
mitad = samplings/2
razon = mitad/((N/2))
intervalo = int(np.round(2600/razon,1))
# print(f'largo yf : {len(yf)}')
xf = fftfreq(N, T)[:N//2] # tiene un largo de 4096
# print(f'largo xf : {len(xf)}')
ejey = 2.0/N * np.abs(yf[0:N//2])
#ejey = np.abs(20*np.log10(yf[:N]))
#print(f'ejey: {ejey}')
valuesffti3 = [ i for i in ejey]
xf1 = np.round(xf,1)
labelsffti3 = [ i for i in xf1[:intervalo] ]
largoejeyi3 = max(ejey)
DATVoltajeCGE=0.0
phasevoltajeCGE=0.0
FDvoltajeCGE=0.0
DATVoltajePaneles=0.0
phasevoltajePaneles=0.0
FDvoltajePaneles=0.0
DATVoltajeCarga=0.0
phasevoltajeCarga=0.0
FDvoltajeCarga=0.0
def VoltageFFT(list_fftVoltages, samplings,i):
global j
j = str(i)
global DATVoltajeCGE
global phasevoltajeCGE
global FDvoltajeCGE
global DATVoltajePaneles
global phasevoltajePaneles
global FDvoltajePaneles
global DATVoltajeCarga
global phasevoltajeCarga
global FDvoltajeCarga
#global FaseArmonicoFundamentalVoltaje
N = len(list_fftVoltages)
T = 1 / samplings
list_fftVoltages -= np.mean(list_fftVoltages)
datosfft = list_fftVoltages * np.hamming(4096)
yf = np.fft.rfft(datosfft)
#yf = fft(list_fftVoltages)
#ejeyfase = 2.0/N * np.abs(yf[:50])
#index_max2 = np.argmax(ejeyfase[:50])
#a2 = yf[index_max2]/2048
xf = fftfreq(N, T)[:N//2] # tiene un largo de 4096
#ejey = 2.0/N * np.abs(yf[:N//2])
if (samplings > 5100):
#f = interpolate.interp1d(xf, ejey)
f = interpolate.interp1d(xf, yf[:N//2] )
xnew = np.arange(0, 2575, 1) # 2550
# print(f'largo xnew : {len(xnew)}')
ynew = f(xnew)
ejeyabsolut = 2.0/4096 * np.abs(ynew)#ynew
#print(f'm2: {ynew[450:550]} ')
#ejeyabsolut = 2.0/N * abs(ynew)
#valuesfftv = [ i for i in ynew ]
#labelsfftv = [ i for i in range(0,1000) ]
#n = 0
#ax = fig.add_subplot(111)
#ax.plot(xnew,ynew)
#rangex = np.zeros(56)
#for h in range(0, 2600, 50):
# rangex[n]=h
# n = n+1
#ax.xaxis.set_ticks(rangex)
#ax.grid(True)
#plt.title("FFT Voltaje Fase 1",fontdict=font)
#ax.set_xlabel('Frecuencia (Hz)',fontdict=font)
#ax.set_ylabel('|dB|',fontdict=font)
#oldepoch = time.time()
#st = datetime.datetime.fromtimestamp(oldepoch).strftime('%Y-%m-%d-%H:%M:%S')
#plt.savefig("images/fft/voltage/"+st+"Voltage1.png")
#z=0
FD = []
complejo = []
real=[]
imag=[]
#dccomponent = max(ynew[0:10])
z=0
for i in range(45, 2575, 50):
a2 = max(ynew[i:i+10])
arra = max(ejeyabsolut[i:i+10])
complejo.append(a2)
#index_max = np.argmax(ejeyabsolut[i-10:i+20])
#print(f'a : {a}')
#a = ynew[i+index_max]
real1 = a2.real
real.append(real1)
imag1 = a2.imag
imag.append(imag1)
#radiani = np.arctan(real1/imag1)
#degrees = math.degrees(radians)
#print(f'index max2 : {i+index_max}')
z=z+1
FD.append(arra)
#print(f'Armonico numero:{z} {i+index_max} + magnitud de {arra} + magnitud2 {abs(ynew[i+index_max])} + forma rectangular de {a} o {a*2/N} y radianes : {np.angle(a)}')
#print(f'Armonico corriente numero: {z} => {round(arra,3)} + {a2} + .. + {round(radiani,4)})')
#print(f'Armonico corriente numero: {z} => {round(arra,3)}')
FD2=[]
for i in range(0,len(FD)):
if(FD[i]>(FD[0]/10)):
FD2.append(FD[i])
SumMagnitudEficaz = (np.sum([FD2[0:len(FD2)]]))
print(f'Vrms total: {round(SumMagnitudEficaz,2)}')
Magnitud1 = FD[0]
print(f'V rms armonico 1: {round(Magnitud1,2)}')
#razon=Magnitud1/SumMagnitudEficaz
#armonico1voltaje=valor*razon
#print(f'FD Voltaje: {round(FD,2)}')
#DATVoltaje = np.sqrt((valor**2-armonico1voltaje**2)/(armonico1voltaje**2))
#sincvoltaje1 = 0
if(j=="1"):
global sincvoltaje1
phasevoltajeCGE = np.arctan(real[0]/(imag[0]))
#FaseArmonicoFundamentalVoltaje1=round(np.angle(complejo[0]),2)
FDvoltajeCGE = Magnitud1/SumMagnitudEficaz
DATVoltajeCGE = np.sqrt(((SumMagnitudEficaz**2)-(Magnitud1**2))/(Magnitud1**2))
sincvoltaje1 = 1
#return phasevoltajeCGE,FDvoltajeCGE,DATVoltajeCGE
#sincvoltaje2 = 0
if(j=="2"):
global sincvoltaje2
phasevoltajePaneles = np.arctan(real[0]/(imag[0]))
#FaseArmonicoFundamentalVoltaje1=round(np.angle(complejo[0]),2)
FDvoltajePaneles = Magnitud1/SumMagnitudEficaz
DATVoltajePaneles = np.sqrt(((SumMagnitudEficaz**2)-(Magnitud1**2))/(Magnitud1**2))
sincvoltaje2 = 1
#return phasevoltajePaneles,FDvoltajePaneles,DATVoltajePaneles
#sincvoltaje3 = 0
if(j=="3"):
global sincvoltaje3
phasevoltajeCGE = np.arctan(real[0]/(imag[0]))
#FaseArmonicoFundamentalVoltaje1=round(np.angle(complejo[0]),2)
FDvoltajeCarga = Magnitud1/SumMagnitudEficaz
DATVoltajeCarga = np.sqrt(((SumMagnitudEficaz**2)-(Magnitud1**2))/(Magnitud1**2))
sincvoltaje3 = 1
#return phasevoltajeCarga,FDvoltajeCarga,DATVoltajeCarga
DATCorrienteCGE = 0.0
DATCorrientePaneles= 0.0
DATCorrienteCarga= 0.0
FDCorrienteCGE= 0.0
FDCorrientePaneles= 0.0
FDCorrienteCarga= 0.0
FDCorrienteCGE= 0.0
phasecorrienteCGE= 0.0
phasecorrientePaneles= 0.0
phasecorrienteCarga= 0.0
FPCGE= 0.0
cosphiCGE= 0.0
FPPaneles= 0.0
cosphiPaneles= 0.0
FPCarga= 0.0
cosphiCarga= 0.0
def CurrentFFT(list_fftVoltages, samplings, i):
global DATCorrienteCGE
global a2
global FDCorrienteCGE
global phasecorrienteCGE
global FDCorrientePaneles
global DATCorrientePaneles
global phasecorrientePaneles
global FDCorrienteCarga
global DATCorrienteCarga
global phasecorrienteCarga
global FPCGE
global cosphiCGE
global FPPaneles
global cosphiPaneles
global FPCarga
global cosphiCarga
global q
q = str(i)
N = len(list_fftVoltages)
T = 1 / samplings
list_fftVoltages -= np.mean(list_fftVoltages)
datosfft = list_fftVoltages * np.hamming(4096)#np.kaiser(N,100)
yf = np.fft.rfft(datosfft)
#yf=fft(list_fftVoltages)
#if (g == 1):
# print(f'Sampling corriente 1: {round(samplings,2)}')
xf = fftfreq(N, T)[:N//2]
if (samplings > 5100):
f = interpolate.interp1d(xf,yf[:N//2])
xnew = np.arange(0, 2575, 1)
ynew = f(xnew)
ejeyabsolut = 2.0/N * np.abs(ynew)
#ejeyabsolut = 2.0/N * np.abs(ynew)
# n = 0
# ax = fig.add_subplot(111)
# ax.plot(xnew,ynew)
# rangex = np.zeros(56)
# for h in range(0, 2600, 50):
# rangex[n]=h
# n = n+1
# ax.xaxis.set_ticks(rangex)
# ax.grid(True)
# plt.title("FFT Corriente Fase"+i+".",fontdict=font)
# ax.set_xlabel('Frecuencia (Hz)',fontdict=font)
# ax.set_ylabel('|dB|',fontdict=font)
# oldepoch = time.time()
# st = datetime.datetime.fromtimestamp(oldepoch).strftime('%Y-%m-%d-%H:%M:%S')
# plt.savefig("images/fft/current"+i+"/"+st+"Current"+i+".png")
# print(f'i : {i}')
p = int(i)
z=0
FD= []
#dccomponent = max(ynew[0:10])
complejo = []
real=[]
imag=[]
#dccomponent = max(ynew[0:10])
for i in range(45, 2575, 50):
a2 = max(ynew[i:i+10])
arra = max(ejeyabsolut[i:i+10])
complejo.append(a2)
#index_max = np.argmax(ejeyabsolut[i-10:i+20])
#print(f'a : {a}')
#a = ynew[i+index_max]
real1 = a2.real
real.append(real1)
imag1 = a2.imag
imag.append(imag1)
#radiani = np.arctan(real1/imag1)
#degrees = math.degrees(radians)
#print(f'index max2 : {i+index_max}')
#z=z+1
FD.append(arra)
#print(f'Armonico numero:{z} {i+index_max} + magnitud de {arra} + magnitud2 {abs(ynew[i+index_max])} + forma rectangular de {a} o {a*2/N} y radianes : {np.angle(a)}')
#print(f'Armonico corriente numero: {z} => {round(arra,3)} + {a2} + .. + {round(radiani,4)})')
FD2=[]
for i in range(0,len(FD)):
if(FD[i]>(FD[0]/10)):
FD2.append(FD[i])
#print(f'FD2: {FD2}')
#print(f'FD largo: {len(FD)}')
SumMagnitudEficaz = (np.sum([FD2[0:len(FD2)]]))
print(f'Irms total: {round(SumMagnitudEficaz,2)}')
Magnitud1 = FD[0]
print(f'Irms armonico 1: {round(Magnitud1,2)}')
#razon=Magnitud1/SumMagnitudEficaz
#armonico1corriente=valor1*razon
#MagnitudArmonicoFundamentalCorriente=round(thd_array[0],3)
#fp2=round((armonico1corriente*np.cos(phasevoltaje-phasen))/valor1,2)
#FaseArmonicoFundamentalCorriente=round(np.angle(complejo[0]),2)
#GradoArmonicoFundamentalCorriente=round(Grados,2)
if(q=="1"):
global sincvoltaje1
FDCorrienteCGE = Magnitud1/SumMagnitudEficaz
print(f'FD corriente CGE: {FDCorrienteCGE}')
DATCorrienteCGE = np.sqrt((SumMagnitudEficaz**2-Magnitud1**2)/(Magnitud1**2))
phasecorrienteCGE = np.arctan(real[0]/(imag[0]))
if (sincvoltaje1 == 1):
FPCGE=np.cos(phasevoltajeCGE-phasecorrienteCGE)*FDCorrienteCGE
cosphiCGE=np.cos(phasevoltajeCGE-phasecorrienteCGE)
#FP=np.cos(FaseArmonicoFundamentalVoltaje-FaseArmonicoFundamentalCorriente)
print(f'FP1 cge: {FPCGE}')
print(f'cos(phi) cge : {cosphiCGE}')
sincvoltaje1=0
#return FPCGE
#sincvoltaje1=0
if(q=="2"):
global sincvoltaje2
FDCorrientePaneles = Magnitud1/SumMagnitudEficaz
print(f'FDCorrientePaneles : {FDCorrientePaneles }')
DATCorrientePaneles = np.sqrt((SumMagnitudEficaz**2-Magnitud1**2)/(Magnitud1**2))
phasecorrientePaneles = np.arctan(real[0]/(imag[0]))
if (sincvoltaje2 == 1):
FPPaneles=np.cos(phasevoltajePaneles-phasecorrientePaneles)*FDCorrientePaneles
cosphiPaneles=np.cos(phasevoltajePaneles-phasecorrientePaneles)
#FP=np.cos(FaseArmonicoFundamentalVoltaje-FaseArmonicoFundamentalCorriente)
print(f'FP1 paneles: {FPPaneles}')
print(f'cos(phi) paneles : {cosphiPaneles}')
sincvoltaje2=0
#return FPCGE
#sincvoltaje2=0
if(q=="3"):
global sincvoltaje3
FDCorrienteCarga=Magnitud1/SumMagnitudEficaz
DATCorrienteCarga = np.sqrt((SumMagnitudEficaz**2-Magnitud1**2)/(Magnitud1**2))
phasecorrienteCarga = np.arctan(real[0]/(imag[0]))
if (sincvoltaje3 == 1):
FPCarga=np.cos(phasevoltajeCarga-phasecorrienteCarga)*FDCorrienteCarga
cosphiCarga=np.cos(phasevoltajeCarga-phasecorrienteCarga)
#FP=np.cos(FaseArmonicoFundamentalVoltaje-FaseArmonicoFundamentalCorriente)
print(f'FP carga : {FPCarga}')
print(f'cos(phi) carga : {cosphiCarga}')
sincvoltaje3=0
#return FPCGE
#sincvoltaje3=0
#print(f'sincvoltaje == {sincvoltaje}')
#print(f'FP2 : {np.cos(0-GradoArmonicoFundamentalCorriente)*FD}')
#MagnitudTotalArmonicosCorriente=round(sum,3)
#MagnitudTotalArmonicosRms=round(sumsqrt,3)
#thd_final = (raiz/thd_array[0])
#print(f'Distorsion armonica total de la corriente de carga : {round(dat,2)}')
#if(p==1):
# print(f'thd corriente 1: {round(thd_final,2)}')
# return round(sumsqrt,2)
a = datetime.datetime.now()
b = datetime.datetime.now()
c = datetime.datetime.now()
energyCGEFase1 = 0.0
energyPanelesFase1 = 0.0
energyCargaFase1 = 0.0
AparenteCGEFase1 = 0.0
ActivaCGEFase1 = 0.0
ReactivaCGEFase1 = 0.0
AparentePanelesFase1 = 0.0
ActivaPanelesFase1 = 0.0
ReactivaPanelesFase1 = 0.0
AparenteCargaFase1 = 0.0
ActivaCargaFase1 = 0.0
ReactivaCargaFase1 = 0.0
#def Potencias(vrms, irms, phi, i):
# i = str i
# global a
#global energyfase1
# Aparente = vrms*irms
# Activa = np.abs(vrms*irms*np.cos(phi))
#print(f'Activa fase 1: {round(Activa,2)}')
# Reactiva = vrms*irms*np.sin(phi)
# if(i == 1):
# b = datetime.datetime.now()
# delta=(((b - a).microseconds)/1000+((b - a).seconds)*1000)/10000000000
#print(f'ms: {delta}')
# energyfase1 += Activa*delta*2.8
#print(f'energy: {round(energyFase1,3)}')
# a = datetime.datetime.now()
#print(f'Aparente fase 1: {round(Aparente)}')
#print(f'Activa fase 1: {round(Activa,2)}')
#print(f'Reactiva fase 1: {round(Reactiva)}')
#return Aparente,Activa,Reactiva,energyfase1
def Potencias(i,irms,vrms):
i = str(i)
if(i=="1"):
global a
global energyCGEFase1
global ActivaCGEFase1
global AparenteCGEFase1
global ReactivaCGEFase1
AparenteCGEFase1 = vrms*irms
ActivaCGEFase1= np.abs(vrms*irms*cosphiCGE)
ReactivaCGEFase1 = vrms*irms*np.sin(phasevoltajeCGE-phasecorrienteCGE)
a2 = datetime.datetime.now()
delta=(((a2 - a).microseconds)/1000+((a2 - a).seconds)*1000)/10000000000
energyCGEFase1 += ActivaCGEFase1*delta*2.8
a = datetime.datetime.now()
if(i=="2"):
global b
global energyPanelesFase1
global AparentePanelesFase1
global ActivaPanelesFase1
global ReactivaPanelesFase1
AparentePanelesFase1 = vrms*irms
ActivaPanelesFase1= np.abs(vrms*irms*cosphiPaneles)
ReactivaPanelesFase1 = vrms*irms*np.sin(phasevoltajePaneles-phasecorrientePaneles)
b2 = datetime.datetime.now()
delta=(((b2 - b).microseconds)/1000+((b2 - b).seconds)*1000)/10000000000
energyPanelesFase1 += ActivaPanelesFase1*delta*2.8
b = datetime.datetime.now()
if(i=="3"):
global c
global energyCargaFase1
global AparenteCargaFase1
global ActivaCargaFase1
global ReactivaCargaFase1
AparenteCargaFase1 = vrms*irms
ActivaCargaFase1= np.abs(vrms*irms*cosphiCarga)
ReactivaCargaFase1 = vrms*irms*np.sin(phasevoltajeCarga-phasecorrienteCarga)
c2 = datetime.datetime.now()
delta=(((c2 - c).microseconds)/1000+((c2 - c).seconds)*1000)/10000000000
energyCargaFase1 += ActivaCargaFase1*delta*2.8
c = datetime.datetime.now()
vrms1=0.0
vrms2=0.0
vrms3=0.0
irms1=0.0
irms2=0.0
irms3=0.0
def received():
while True:
esp32_bytes = esp32.readline()
decoded_bytes = str(esp32_bytes[0:len(esp32_bytes)-2].decode("utf-8"))#utf-8
np_array = np.fromstring(decoded_bytes, dtype=float, sep=',')
#print(f'largo array inicial: {len(np_array)}')
if (len(np_array) == 8402):
if (np_array[0] == 11):
global vrms1
global irms1
samplings = np_array[-1]
list_FPVoltage3 = np_array[0:4200]
list_FPCurrent3 = np_array[4201:8400]
sos = signal.butter(10, 3000, 'low', fs=samplings, output='sos')
list_FPVoltage2 = signal.sosfilt(sos, list_FPVoltage3)
#list_FPVoltage2 = savgol_filter(list_FPVoltage2,len(list_FPVoltage2)-1,))
#sos = signal.butter(4, 50, 'low', fs=samplings, output='sos')
list_FPCurrent2 = signal.sosfilt(sos, list_FPCurrent3)
list_FPVoltage = list_FPVoltage2[104:4200]
list_FPCurrent = list_FPCurrent2 [103:4200]
#Valor dc de Voltaje
valoresmaximovoltajesinmedia=getMaxValues(list_FPVoltage, 20)
valoresminimovoltajesinmedia=getMinValues(list_FPVoltage, 20)
maximovoltaje = np.median(valoresmaximovoltajesinmedia)
minimovoltaje = np.median(valoresminimovoltajesinmedia)
mediadcvoltaje = (maximovoltaje+minimovoltaje)/2
# Valores maximo y minimos de voltaje sin componente continua
NoVoltageoffset=list_FPVoltage-mediadcvoltaje
maximovoltaje2sinmedia=getMaxValues(NoVoltageoffset, 20)
minimovoltaje2sinmedia=getMinValues(NoVoltageoffset, 20)
maximovoltaje2 = np.median(maximovoltaje2sinmedia)
minimovoltaje2 = np.median(minimovoltaje2sinmedia)
#print(f'maximo voltaje{maximovoltaje2}')
#print(f'maximo voltaje{minimovoltaje2}')
NoVoltageoffset2 = EscalaVoltaje(NoVoltageoffset)
#NoVoltageoffset2=NoVoltageoffset/1.90
#print(f'len 1: {len(list_FPVoltage)}')
# print(f'maximos{valoresmaximovoltajesinmedia}')
# print(f'minimos{valoresminimovoltajesinmedia}')
# print(f'samplings 0: {len(list_FPVoltage)}')
# print(f'samplings 1: {len(NoVoltageoffset)}')
#Valor dc de corriente
valoresmaxcorriente=getMaxValues(list_FPCurrent, 20)
valoresmincorriente=getMinValues(list_FPCurrent, 20)
maximocorriente = np.median(valoresmaxcorriente)
minimocorriente = np.median(valoresmincorriente)
mediadccorriente = (maximocorriente+minimocorriente)/2
# Valores maximo y minimos de corriente
NoCurrentoffset=list_FPCurrent-mediadccorriente
maximocorriente2sinmedia=getMaxValues(NoCurrentoffset, 20)
minimocorriente2sinmedia=getMinValues(NoCurrentoffset, 20)
maximocorriente2 = np.median(maximocorriente2sinmedia)
minimocorriente2 = np.median(minimocorriente2sinmedia)
#print(f'corriente max: {maximocorriente2 }')
#print(f'corriente min: {minimocorriente2 }')
NoCurrentoffset2 = EscalaCorriente(NoCurrentoffset)
#NoCurrentoffset2 = NoCurrentoffset/125 #210 con res
vrms1 = VoltajeRms(NoVoltageoffset2)
VoltageFFT(NoVoltageoffset2,samplings,1)
graphVoltage1(NoVoltageoffset2,maximovoltaje2,minimovoltaje2,samplings)
graphFFTV1(NoVoltageoffset2,samplings)
irms1 = CorrienteRms(NoCurrentoffset2)
CurrentFFT(NoCurrentoffset2,samplings,1)
graphCurrent1(NoCurrentoffset2,samplings)
graphFFTI1(NoCurrentoffset2,samplings)
#maximo=max(list_FPCurrent[1000:1700])
#minimo=min(list_FPCurrent[1000:1700])
#diferencia=maximo-minimo
#maximo2=max(list_FPCurrent)
#escalaI = valor1*np.sqrt(2) / maximo2
#listEscalaI=list_FPCurrent*escalaI
#samplings = np_array[-1]
graphVoltageCurrent(NoVoltageoffset,NoCurrentoffset,samplings)
Potencias(1,irms1,vrms1)
print(f'samplings 1: {samplings}')
#FP(list_FPVoltage, list_FPCurrent, i=1)
if (np_array[0] == 22):
global vrms2
global irms2
samplings = np_array[-1]
list_FPVoltage3 = np_array[0:4200]
list_FPCurrent3 = np_array[4201:8400]
sos = signal.butter(10, 3000, 'low', fs=samplings, output='sos')
list_FPVoltage2 = signal.sosfilt(sos, list_FPVoltage3)
#list_FPVoltage2 = savgol_filter(list_FPVoltage2,len(list_FPVoltage2)-1,))
#sos = signal.butter(4, 50, 'low', fs=samplings, output='sos')
list_FPCurrent2 = signal.sosfilt(sos, list_FPCurrent3)
list_FPVoltage = list_FPVoltage2[104:4200]
list_FPCurrent = list_FPCurrent2 [103:4200]
#Valor dc de Voltaje
valoresmaximovoltajesinmedia=getMaxValues(list_FPVoltage, 20)
valoresminimovoltajesinmedia=getMinValues(list_FPVoltage, 20)
maximovoltaje = np.median(valoresmaximovoltajesinmedia)
minimovoltaje = np.median(valoresminimovoltajesinmedia)
mediadcvoltaje = (maximovoltaje+minimovoltaje)/2
# Valores maximo y minimos de voltaje sin componente continua
NoVoltageoffset=list_FPVoltage-mediadcvoltaje
maximovoltaje2sinmedia=getMaxValues(NoVoltageoffset, 20)
minimovoltaje2sinmedia=getMinValues(NoVoltageoffset, 20)
maximovoltaje2 = np.median(maximovoltaje2sinmedia)
minimovoltaje2 = np.median(minimovoltaje2sinmedia)
#print(f'maximo voltaje{maximovoltaje2}')
#print(f'maximo voltaje{minimovoltaje2}')
NoVoltageoffset2 = EscalaVoltaje(NoVoltageoffset)
#NoVoltageoffset2=NoVoltageoffset/1.90
#print(f'len 1: {len(list_FPVoltage)}')
# print(f'maximos{valoresmaximovoltajesinmedia}')
# print(f'minimos{valoresminimovoltajesinmedia}')
# print(f'samplings 0: {len(list_FPVoltage)}')
# print(f'samplings 1: {len(NoVoltageoffset)}')
#Valor dc de corriente
valoresmaxcorriente=getMaxValues(list_FPCurrent, 20)
valoresmincorriente=getMinValues(list_FPCurrent, 20)
maximocorriente = np.median(valoresmaxcorriente)
minimocorriente = np.median(valoresmincorriente)
mediadccorriente = (maximocorriente+minimocorriente)/2
# Valores maximo y minimos de corriente
NoCurrentoffset=list_FPCurrent-mediadccorriente
maximocorriente2sinmedia=getMaxValues(NoCurrentoffset, 20)
minimocorriente2sinmedia=getMinValues(NoCurrentoffset, 20)
maximocorriente2 = np.median(maximocorriente2sinmedia)
minimocorriente2 = np.median(minimocorriente2sinmedia)
#print(f'corriente max: {maximocorriente2 }')
#print(f'corriente min: {minimocorriente2 }')
NoCurrentoffset2 = EscalaCorriente(NoCurrentoffset)
#NoCurrentoffset2 = NoCurrentoffset/125 #210 con res
vrms2=VoltajeRms(NoVoltageoffset2)
VoltageFFT(NoVoltageoffset2,samplings,2)
graphVoltage2(NoVoltageoffset2,maximovoltaje2,minimovoltaje2,samplings)
graphFFTV2(NoVoltageoffset2,samplings)
irms2 = CorrienteRms(NoCurrentoffset2)
CurrentFFT(NoCurrentoffset2,samplings,2)
graphCurrent2(NoCurrentoffset2,samplings)
graphFFTI2(NoCurrentoffset2,samplings)
#maximo=max(list_FPCurrent[1000:1700])
#minimo=min(list_FPCurrent[1000:1700])
#diferencia=maximo-minimo
#maximo2=max(list_FPCurrent)
#escalaI = valor1*np.sqrt(2) / maximo2
#listEscalaI=list_FPCurrent*escalaI
#samplings = np_array[-1]
graphVoltageCurrent(NoVoltageoffset,NoCurrentoffset,samplings)
Potencias(2,irms2,vrms2)
print(f'samplings 2: {samplings}')
#FP(list_FPVoltage, list_FPCurrent, i=1)
if (np_array[0] == 33):
global vrms3
global irms3
samplings = np_array[-1]
list_FPVoltage3 = np_array[0:4200]
list_FPCurrent3 = np_array[4201:8400]
sos = signal.butter(10, 3000, 'low', fs=samplings, output='sos')
list_FPVoltage2 = signal.sosfilt(sos, list_FPVoltage3)
#list_FPVoltage2 = savgol_filter(list_FPVoltage2,len(list_FPVoltage2)-1,))
#sos = signal.butter(4, 50, 'low', fs=samplings, output='sos')
list_FPCurrent2 = signal.sosfilt(sos, list_FPCurrent3)
list_FPVoltage = list_FPVoltage2[104:4200]
list_FPCurrent = list_FPCurrent2[103:4200]
#Valor dc de Voltaje
valoresmaximovoltajesinmedia=getMaxValues(list_FPVoltage, 20)
valoresminimovoltajesinmedia=getMinValues(list_FPVoltage, 20)
maximovoltaje = np.median(valoresmaximovoltajesinmedia)
minimovoltaje = np.median(valoresminimovoltajesinmedia)
mediadcvoltaje = (maximovoltaje+minimovoltaje)/2
# Valores maximo y minimos de voltaje sin componente continua
NoVoltageoffset=list_FPVoltage-mediadcvoltaje
maximovoltaje2sinmedia=getMaxValues(NoVoltageoffset, 20)
minimovoltaje2sinmedia=getMinValues(NoVoltageoffset, 20)
maximovoltaje2 = np.median(maximovoltaje2sinmedia)
minimovoltaje2 = np.median(minimovoltaje2sinmedia)
#print(f'maximo voltaje{maximovoltaje2}')
#print(f'maximo voltaje{minimovoltaje2}')
NoVoltageoffset2 = EscalaVoltaje(NoVoltageoffset)
#NoVoltageoffset2=NoVoltageoffset/1.90
#print(f'len 1: {len(list_FPVoltage)}')
# print(f'maximos{valoresmaximovoltajesinmedia}')
# print(f'minimos{valoresminimovoltajesinmedia}')
# print(f'samplings 0: {len(list_FPVoltage)}')
# print(f'samplings 1: {len(NoVoltageoffset)}')
#Valor dc de corriente
valoresmaxcorriente=getMaxValues(list_FPCurrent, 20)
valoresmincorriente=getMinValues(list_FPCurrent, 20)
maximocorriente = np.median(valoresmaxcorriente)
minimocorriente = np.median(valoresmincorriente)
mediadccorriente = (maximocorriente+minimocorriente)/2
# Valores maximo y minimos de corriente
NoCurrentoffset=list_FPCurrent-mediadccorriente
maximocorriente2sinmedia=getMaxValues(NoCurrentoffset, 20)
minimocorriente2sinmedia=getMinValues(NoCurrentoffset, 20)
maximocorriente2 = np.median(maximocorriente2sinmedia)
minimocorriente2 = np.median(minimocorriente2sinmedia)
#print(f'corriente max: {maximocorriente2 }')
#print(f'corriente min: {minimocorriente2 }')
NoCurrentoffset2 = EscalaCorriente(NoCurrentoffset)
#NoCurrentoffset2 = NoCurrentoffset/125 #210 con res
vrms3=VoltajeRms(NoVoltageoffset2)
VoltageFFT(NoVoltageoffset2,samplings,3)
graphVoltage3(NoVoltageoffset2,maximovoltaje2,minimovoltaje2,samplings)
graphFFTV3(NoVoltageoffset2,samplings)
irms3 = CorrienteRms(NoCurrentoffset2)
CurrentFFT(NoCurrentoffset2,samplings,3)
graphCurrent3(NoCurrentoffset2,samplings)
graphFFTI3(NoCurrentoffset2,samplings)
#maximo=max(list_FPCurrent[1000:1700])
#minimo=min(list_FPCurrent[1000:1700])
#diferencia=maximo-minimo
#maximo2=max(list_FPCurrent)
#escalaI = valor1*np.sqrt(2) / maximo2
#listEscalaI=list_FPCurrent*escalaI
#samplings = np_array[-1]
graphVoltageCurrent(NoVoltageoffset,NoCurrentoffset,samplings)
Potencias(3,irms3,vrms3)
print(f'samplings 3: {samplings}')
#FP(list_FPVoltage, list_FPCurrent, i=1)
if (len(np_array)>0 and len(np_array)<=2):
global tempESP32
getTEMP()
#temphum()
#distance()
tempESP32 = round(np_array[0],0)
#print(f'array: {np_array}')
"""
if (len(np_array)==5202):
if (np_array[0]==111):
samplings = np_array[-1]
print(f'Sampling voltage: {samplings}')
listEscalaV= (np_array[500:4596])#*0.36
#con media
#valormaximovoltajesinmedia=getMaxValues(list_fftVoltage, 10)
#maximo= np.median(valormaximovoltajesinmedia)
#print(f'maximo voltaje fft 1 : {maximo}')
#escalaV = valor*np.sqrt(2) / maximo
#listEscalaV=list_fftVoltage*escalaV
#listEscalaV=(99*list_fftVoltage+list_fftVoltage)/100
#maximo2=max(listEscalaV)
#print(f'maximo voltaje fft 2: {maximo}')
print(f'maximo voltaje: {max(listEscalaV)}')
VoltageFFT(listEscalaV,samplings)
graphVoltage(listEscalaV)
graphFFT(listEscalaV,samplings)
#print(f'fft done')
if (np_array[0]==222):
samplings = np_array[-1]
print(f'Sampling corriente: {samplings}')
listEscalaI = np_array[500:4596]#/395
#con media
#valormaximocorrientesinmedia=getMaxValues(list_fftVoltage, 10)
#maximo2= np.median(valormaximocorrientesinmedia)
#print(f'maximo corriente fft: {maximo2}')
#escalaI = valor1*np.sqrt(2) / maximo2
#listEscalaI=list_fftVoltage*escalaI
#maximo2=max(listEscalaI)
#listEscalaI=(99*list_fftVoltage+list_fftVoltage)/100
print(f'maximo corriente: {max(listEscalaI)}')
CurrentFFT(listEscalaI,samplings,1)
graphCurrent(listEscalaI)
graphFFTI(listEscalaI,samplings)
#print(f'max current 2: {max(list_fftVoltage)}')
#print(f'max current 2: {max(listEscalaI)}')
"""
#if (len(np_array)>2 and len(np_array)<10):
# global ApFase1
# global AcFase1
# global ReacFase1
# global energyFase1
#valor = np_array[0]
#valor1 = np_array[1]
#Potencias2(valor,valor1)
#print(f'time: {datetime.utcnow()}')
#print(f'vrms: {valor}')
#print(f'irms: {valor1}')
#if (phi1==None):
# break
#else:
# ApFase1,AcFase1,ReacFase1,energyFase1=Potencias(vrms=valor,irms=valor1,phi=phi1,i=1)
x = datetime.datetime.now()
@app.route('/index.html')
def index():
# For each pin, read the pin state and store it in the pins dictionary:
for pin in pins:
pins[pin]['state'] = GPIO.input(pin)
# Put the pin dictionary into the template data dictionary:
templateData = {
'pins' : pins
}
#Muestra de for para graficar en pag
#labels = x
#print(f'labels:')
#values = y
#print(labels)
#data = [
#("1-1", 2),
#("1-2", 0),
#("1-3", 6),
#("1-4", 8),
#("1-5", 14),
#("1-6", 6),
#("1-7", 2),
#]
#print(data)
#labels = [row[0] for row in data]
#values = [row[1] for row in data]
return render_template('index.html',**templateData,
puerta="abierta",
tempESP32=tempESP32,
CPU_temp=CPU_temp,
humedad=humedad,
temperatura=temperatura,
ip_address=ip_address,current_time=x.strftime("%c")
)
@app.route('/fase1.html')
def fase1():
return render_template('fase1.html',
vrms1=round(vrms1,2),
irms1=round(irms1,2),
AparenteCGEFase1=round(AparenteCGEFase1,2),
ActivaCGEFase1=round(ActivaCGEFase1,2),
ReactivaCGEFase1=round(ReactivaCGEFase1,2),
vrms2=round(vrms2,2),
irms2=round(irms2,2),
AparentePanelesFase1=round(AparentePanelesFase1,2),
ActivaPanelesFase1=round(ActivaPanelesFase1,2),
ReactivaPanelesFase1=round(ReactivaPanelesFase1,2),
vrms3=round(vrms3,2),
irms3=round(irms3,2),
AparenteCargaFase1=round(AparenteCargaFase1,2),
ActivaCargaFase1=round(ActivaCargaFase1,2),
ReactivaCargaFase1=round(ReactivaCargaFase1,2),
energyCGEFase1=round(energyCGEFase1,2),
energyPanelesFase1=round(energyPanelesFase1,2),
energyCargaFase1=round(energyCargaFase1,2),
DATVoltajeCGE=round(DATVoltajeCGE,2),
phasevoltajeCGE=round(phasevoltajeCGE,2),
FDvoltajeCGE=round(FDvoltajeCGE,2),
DATVoltajePaneles=round(DATVoltajePaneles,2),
phasevoltajePaneles=round(phasevoltajePaneles,2),
FDvoltajePaneles=round(FDvoltajePaneles,2),
DATVoltajeCarga=round(DATVoltajeCarga,2),
phasevoltajeCarga=round(phasevoltajeCarga,2),
FDvoltajeCarga=round(FDvoltajeCarga,2),
FDCorrienteCGE=round(FDCorrienteCGE,2),
DATCorrienteCGE =round(DATCorrienteCGE,2),
phasecorrienteCGE=round(phasecorrienteCGE,2),
FDCorrientePaneles=round(FDCorrientePaneles,2),
DATCorrientePaneles=round(DATCorrientePaneles,2),
phasecorrientePaneles=round(phasecorrientePaneles,2),
FDCorrienteCarga=round(FDCorrienteCarga,2),
DATCorrienteCarga=round(DATCorrienteCarga,2),
phasecorrienteCarga=round(phasecorrienteCarga,2),
FPCGE=round(FPCGE,2),
cosphiCGE=round(cosphiCGE,2),
FPPaneles=round(FPPaneles,2),
cosphiPaneles=round(cosphiPaneles,2),
FPCarga=round(FPCarga,2),
cosphiCarga=round(cosphiCarga,2),
labelsvoltaje1=labelsvoltaje1,
labelsvoltaje2=labelsvoltaje2,
labelsvoltaje3=labelsvoltaje3,
valuesvoltaje1=valuesvoltaje1,
valuesvoltaje2=valuesvoltaje2,
valuesvoltaje3=valuesvoltaje3,
ejeyV11=ejeyV11,
ejeyV12=ejeyV12,
ejeyV21=ejeyV21,
ejeyV22=ejeyV22,
ejeyV31=ejeyV31,
ejeyV32=ejeyV32,
labelscurrent1=labelscurrent1,
valuescurrent1=valuescurrent1,
ejeycurrent11=ejeycurrent11,
ejeycurrent12=ejeycurrent12,
labelscurrent2=labelscurrent2,
valuescurrent2=valuescurrent2,
ejeycurrent21=ejeycurrent21,
ejeycurrent22=ejeycurrent22,
labelscurrent3=labelscurrent3,
valuescurrent3=valuescurrent3,
ejeycurrent31=ejeycurrent31,
ejeycurrent32=ejeycurrent32,
labelsfftv1=labelsfftv1,
valuesfftv1=valuesfftv1,
largoejeyv1=largoejeyv1,
labelsfftv2=labelsfftv2,
valuesfftv2=valuesfftv2,
largoejeyv2=largoejeyv2,
labelsfftv3=labelsfftv3,
valuesfftv3=valuesfftv3,
largoejeyv3=largoejeyv3,
labelsffti1=labelsffti1,
valuesffti1=valuesffti1,
largoejeyi1=largoejeyi1,
labelsffti2=labelsffti2,
valuesffti2=valuesffti2,
largoejeyi2=largoejeyi2,
labelsffti3=labelsffti3,
valuesffti3=valuesffti3,
largoejeyi3=largoejeyi3,
tempESP32=tempESP32,
CPU_temp=CPU_temp,
humedad=humedad,
temperatura=temperatura,
ip_address=ip_address,
#maxcorriente=maxcorriente,
#mincorriente=mincorriente,
labelsfp=labelsfp,
valuesvoltage=valuesvoltage,
valuescurrent=valuescurrent,
maxvoltaje=maxvoltaje,
minvoltaje=minvoltaje)
@app.route('/<changePin>/<action>')
def action(changePin, action):
# Convert the pin from the URL into an integer:
changePin = int(changePin)
# Get the device name for the pin being changed:
deviceName = pins[changePin]['name']
# If the action part of the URL is "on," execute the code indented below:
if action == "on":
# Set the pin high:
GPIO.output(changePin, GPIO.HIGH)
# Save the status message to be passed into the template:
message = "Turned " + deviceName + " on."
if action == "off":
GPIO.output(changePin, GPIO.LOW)
message = "Turned " + deviceName + " off."
# For each pin, read the pin state and store it in the pins dictionary:
for pin in pins:
pins[pin]['state'] = GPIO.input(pin)
# Along with the pin dictionary, put the message into the template data dictionary:
templateData = {
'pins' : pins
}
return render_template('index.html', **templateData, puerta=puerta,
tempESP32=tempESP32,
CPU_temp=CPU_temp,
humedad=humedad,
temperatura=temperatura,
ip_address=ip_address)
if __name__ == '__main__':
t = threading.Thread(target=received)
t.daemon = True
t.start()
app.run(debug=False)
|
f0b50514c3fcef4b2ca81dc6b2163ef67a86654b
|
[
"Python",
"Text"
] | 3 |
Text
|
nachovera93/heroku-prueba
|
a3d35171092f1699acd8d3e58424a242faea1089
|
47c9caca3de12448f3448b709cae57ab5d265fc7
|
refs/heads/master
|
<repo_name>feicccccccc/k-arm-bandit-test<file_sep>/greedy_near_greedy.py
'''
Demostrate the greedy and near greedy method
'''
import numpy as np
import matplotlib.pyplot as plt
from bandit import *
# create 10 bandit for the game following
# mean of the true action value : 0
# variance of true action value : 1
mean_all_action = 0
var_all_aciion = 1
var_single_game = 1
num_bandits = 10
bandits = []
for i in range(0,num_bandits):
bandits.append(Bandit(mean=np.random.normal(mean_all_action,var_all_aciion), variance=var_single_game))
# create the game
greedy_game = Game(bandits)
output = [[] for _ in range(num_bandits)]
output_mean = []
output_variance = []
num_step = 1000
num_game = 2000
for i in range(0,num_bandits):
output_mean.append(greedy_game.bandits[i].mean)
output_variance.append(greedy_game.bandits[i].variance)
print(" Arm {} mean = {}, variance = {}".format(i,output_mean[i],output_variance[i]))
output_std = np.sqrt(output_variance)
# show the 10 arm bandit
'''
fig, ax = plt.subplots()
ax.bar(np.arange(num_bandits), output_mean, yerr=output_std, align='center', alpha=0, ecolor='black', capsize=10)
plt.savefig('bar_plot_with_error_bars.png')
plt.show()
'''
def multiple_game_greedy_action():
greedy_history = []
greedy_game = []
greedy_correctness = []
near_greedy_history = []
near_greedy_game = []
near_greedy_correctness = []
near_greedy2_history = []
near_greedy2_game = []
near_greedy2_correctness = []
for i in range(0,num_game):
bandits = []
for _ in range(0, num_bandits):
bandits.append(Bandit(mean=np.random.normal(mean_all_action, var_all_aciion), variance=var_single_game))
greedy_game.append(Game(bandits))
for i in range(0, num_game):
bandits = []
for _ in range(0, num_bandits):
bandits.append(Bandit(mean=np.random.normal(mean_all_action, var_all_aciion), variance=var_single_game))
near_greedy_game.append(Game(bandits))
for i in range(0, num_game):
bandits = []
for _ in range(0, num_bandits):
bandits.append(Bandit(mean=np.random.normal(mean_all_action, var_all_aciion), variance=var_single_game))
near_greedy2_game.append(Game(bandits))
all_game_mean_1 = 0
all_game_mean_2 = 0
all_game_mean_3 = 0
all_game_corr_1 = 0
all_game_corr_2 = 0
all_game_corr_3 = 0
for i in range(num_step):
for j in range(num_game):
#print("game : {} , step : {}".format(j,i))
greedy_game[j].sample_once(near_greedy=False)
all_game_mean_1 = all_game_mean_1 + greedy_game[j].get_cur_mean()
all_game_corr_1 = all_game_corr_1 + greedy_game[j].correct_count
#print("cur_mean : {}".format(greedy_game[j].get_cur_mean()))
#print(all_game_mean_1)
print("greedy step {}".format(i))
greedy_history.append(all_game_mean_1 / num_game)
greedy_correctness.append(all_game_corr_1 / num_game)
all_game_mean_1 = 0
all_game_corr_1 = 0
for i in range(num_step):
for j in range(num_game):
#print("game : {} , step : {}".format(j,i))
near_greedy_game[j].sample_once(near_greedy=True,prop=0.01)
all_game_mean_2 = all_game_mean_2 + near_greedy_game[j].get_cur_mean()
all_game_corr_2 = all_game_corr_2 + near_greedy_game[j].correct_count
#print("cur_mean : {}".format(greedy_game[j].get_cur_mean()))
#print(all_game_mean_1)
print("near greedy 1 step {}".format(i))
near_greedy_history.append(all_game_mean_2 / num_game)
near_greedy_correctness.append(all_game_corr_2 / num_game)
all_game_mean_2 = 0
all_game_corr_2 = 0
for i in range(num_step):
for j in range(num_game):
#print("game : {} , step : {}".format(j,i))
near_greedy2_game[j].sample_once(near_greedy=True,prop=0.1)
all_game_mean_3 = all_game_mean_3 + near_greedy2_game[j].get_cur_mean()
all_game_corr_3 = all_game_corr_3 + near_greedy2_game[j].correct_count
#print("cur_mean : {}".format(greedy_game[j].get_cur_mean()))
#print(all_game_mean_1)
print("near greedy 2 step {}".format(i))
near_greedy2_history.append(all_game_mean_3 / num_game)
near_greedy2_correctness.append(all_game_corr_3 / num_game)
all_game_mean_3 = 0
all_game_corr_3 = 0
plt.plot(greedy_correctness)
plt.plot(near_greedy_correctness)
plt.plot(near_greedy2_correctness)
plt.savefig('allstep_percentage.png')
plt.show()
def one_game_greedy_action():
history = []
for i in range(num_step):
greedy_game.sample_once(near_greedy=False)
history.append(greedy_game.get_cur_mean())
print(greedy_game.mean)
print(greedy_game.count)
print(greedy_game.get_total_reward() / num_step)
plt.plot(history)
plt.show()
#one_game_greedy_action()
multiple_game_greedy_action()
<file_sep>/bandit.py
'''
An exercise base on RL book by Sutton
'''
import numpy as np
class Bandit:
def __init__(self, mean=0, variance=1):
self.mean = mean
self.variance = variance
def normal_sample(self):
return np.random.normal(self.mean, self.variance)
class Game:
def __init__(self, bandits=[]):
self.bandits = []
self.results = [[] for _ in range(len(bandits))]
self.mean = [0 for _ in range(len(bandits))]
self.count = [0 for _ in range(len(bandits))]
self.correct_count = 0
for bandit in bandits:
self.bandits.append(bandit)
self.optimal_action = 0
max_reward = -10
for i, bandit in enumerate(self.bandits):
#print("{} {}".format(i, bandit))
if bandit.mean > max_reward:
max_reward = bandit.mean
self.optimal_action = i
def get_reward(self):
return (self.sample_action(), self.bandits[self.sample_action()].normal_sample())
def sample_action(self):
action_candidate = np.argwhere(self.mean == np.amax(self.mean))
action_candidate = np.random.choice(action_candidate.flatten())
return action_candidate
def sample_once(self,near_greedy = True, prop = 0.5):
if near_greedy:
sample = np.random.uniform(0, 1)
if sample < prop:
action = np.random.randint(10)
else:
action = self.sample_action()
else:
action = self.sample_action()
if action == self.optimal_action:
self.correct_count = self.correct_count + 1
reward = self.bandits[action].normal_sample()
self.results[action].append(reward)
self.mean[action] = np.mean(self.results[action])
self.count[action] = self.count[action] + 1
def get_total_reward(self):
total_reward = 0
for i in range(len(self.bandits)):
total_reward = total_reward + self.count[i] * self.mean[i]
return total_reward
def get_cur_mean(self):
total_reward = self.get_total_reward()
return total_reward / sum(self.count)
|
a0f8e4e781433439f0f3ce2e3cf6443bcf493ff2
|
[
"Python"
] | 2 |
Python
|
feicccccccc/k-arm-bandit-test
|
a3be0c78305961e278be069c0bcd718819a2f1fd
|
39c89348d8eff67af6f651a2c7a34663b0f5b32e
|
refs/heads/master
|
<file_sep>//de skarpe parenterser i variablen viser at det er et array
let retter = [];
let aktuelKategori = "Menu";
document.addEventListener("DOMContentLoaded", hentJson);
//funktion som henter Json filen
async function hentJson() {
let jsonData = await fetch("menu.json");
retter = await jsonData.json();
visRetter(retter, "Menu");
//find tekst på klikket knap
document.querySelector("nav").addEventListener("click", () => {
// sæt variabel til indhold på knappen i små bogstaver
let kategori = event.target.textContent.toLowerCase();
console.log(kategori);
// hvis kategori er forskellig fra alle, skal kat være retter filreret efter ret.kategori
if (kategori != "alle") {
let kat = retter.filter(ret => ret.kategori == kategori);
visRetter(kat, kategori);
} else {
visRetter(retter, kategori);
}
})
}
function visRetter(retter, overskrift) {
console.log("vis retter");
let temp = document.querySelector("[data-rettemplate]");
let dest = document.querySelector("[data-liste]");
dest.innerHTML = "";
document.querySelector("[data-overskrift]").textContent = overskrift;
document.querySelector("#popup").style.pointerEvents = "none"; // slå mus fra
//loop som kloner template
retter.forEach(ret => {
let klon = temp.cloneNode(true).content;
klon.querySelector("[data-navn]").textContent = ret.navn;
klon.querySelector("[data-billede]").src = "imgs/small/" + ret.billede + "-sm.jpg";
klon.querySelector("[data-billede]").alt = "Billede af " + ret.navn;
klon.querySelector("[data-kortbeskrivelse]").textContent = ret.kortbeskrivelse;
klon.querySelector("[data-pris]").textContent = ret.pris + ",- kr";
klon.querySelector("[data-ret]").addEventListener("click", () => {
visModal(ret)
});
dest.appendChild(klon);
})
//fade in på article
document.querySelectorAll("article").forEach(a => {
a.getBoundingClientRect(); // kun hvis det ikke virker uden
a.style.transition = "all 1s";
//ændre opacity fra 0 til 1
a.style.opacity = "1";
})
}
function visModal(ret) {
document.querySelector("#popup").style.opacity = "1";
document.querySelector("#popup").style.pointerEvents = "auto"; // slå mus til
document.querySelector("[data-titel]").textContent = ret.navn;
document.querySelector("[data-singleImg]").src = "imgs/medium/" + ret.billede + "-md.jpg";
document.querySelector("[data-singleImg]").alt = "Billede af " + ret.navn;
document.querySelector("[data-beskrivelse]").textContent = ret.langbeskrivelse;
document.querySelector("[data-pris]").textContent = ret.pris + ",- kr";
document.querySelector("[data-button]").addEventListener("click", closeModal);
}
function closeModal() {
console.log("luk modal funktion");
document.querySelector("#popup").style.pointerEvents = "none"; // slå mus fra
document.querySelector("#popup").style.opacity = "0";
}
//burgermenu
function toggleMenu() {
document.querySelector(".burger").classList.toggle("change");
document.querySelector("nav").classList.toggle("show");
}
document.querySelector(".burger").addEventListener("click", toggleMenu);
document.querySelector("nav").addEventListener("click", toggleMenu);
//sortering radioknapper
document.querySelector(".radio_alpha").addEventListener("change", radioAlpha);
function radioAlpha() {
retter.sort((a, b) => a.navn.localeCompare(b.navn));
visRetter(retter, aktuelKategori);
}
document.querySelector(".radio_pris_op").addEventListener("change", radioPrisOp);
function radioPrisOp() {
retter.sort((a, b) => a.pris - b.pris);
visRetter(retter, aktuelKategori);
}
document.querySelector(".radio_pris_ned").addEventListener("change", radioPrisNed);
function radioPrisNed() {
retter.sort((a, b) => b.pris - a.pris);
visRetter(retter, aktuelKategori);
}
|
7967109a928cea65484b4a95c5192aab6acd617e
|
[
"JavaScript"
] | 1 |
JavaScript
|
LaiseBang/Bistro_Babushka_school_assignment
|
1397c6f7a777c6c844dd1326d1daf132d1f98b9e
|
471cf13b3c7ab9c5dc135de673dd105d2a767dc4
|
refs/heads/main
|
<repo_name>InhalePhoenix/Teminal-spammer<file_sep>/README.md
# Teminal-spammer
It's exactly what it says, it's a terminal spammer.
<file_sep>/spam.py
#!/usr/bin/python
while(True):
print("Get spammed faggot")
|
10444244fd49f9421192275ad046999e9a53743d
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
InhalePhoenix/Teminal-spammer
|
8e260311d1eccf1fb0848811b3f16a6731e073a1
|
370fe14aa4fa9aec4430687a4b75bde1f1e9208e
|
refs/heads/master
|
<file_sep>export class AccountingDept {
constructor(public id: number, public employees: number) {
}
get getPeople () {
return this.employees;
}
set setPeople (num: number) {
this.employees = num;
}
}<file_sep>import { AccountingDept } from './accounting.js';
const ReconAccounting = new AccountingDept(1, 55);
const displayDiv = document.querySelector("#displayValue");
const employeeInput = document.querySelector('input');
employeeInput.addEventListener('change', updateValue);
function updateValue () {
ReconAccounting.setPeople = parseInt(employeeInput.value);
displayDiv.innerHTML = `${ReconAccounting.getPeople}`;
}
|
3d949770138b2801436d440905ac3fbc71ce79a6
|
[
"TypeScript"
] | 2 |
TypeScript
|
Saul3d/Typescript
|
342c4627331f92a4ecdd6d733a80b00d9c036a79
|
188ebba5689a40d53889ad5743855754b7311bef
|
refs/heads/master
|
<file_sep>// @(#)root
#include <cstdlib>
#include <TFile.h>
#include "SiPM.h"
void breakVolt() {
//------------------------------------Retrieve data from CSV files------------------------------------//
string fileName = "/home/jeremie1001/Documents/School/Uni/Course/4th_Year/PHYS4007/SiPM/Data/dataset1/Vbr.csv";
vector< vector<double> > data = getData(fileName, ',', 3);
//----------------------------------------------------------------------------------------------------//
//------------------------Create Voltage v. Current plot for breaking voltage-------------------------//
unsigned int const size = data.size();
Double_t x[size];
Double_t y[size];
for(int i = 0; i < data.size(); i++) {
x[i] = data[i][0];
y[i] = data[i][1];
}
//----------------------------------------------------------------------------------------------------//
//---------------------------Fit linear function to Voltage v. Current plot---------------------------//
TGraph* gr;
gr = new TGraph(data.size(),x,y);
gr->Fit("pol1", "Q");
TF1 *f = gr->GetFunction("pol1");
double b = f->GetParameter(0);
double m = f->GetParameter(1);
double sigb = f->GetParError(0);
double sigm = f->GetParError(1);
//----------------------------------------------------------------------------------------------------//
//---------------------------------Analyse data and output to console---------------------------------//
double Vbr = -b/m;
double Vp = Vbr + 3;
double sig_Vbr = pow((pow((sigb/m),2) + pow((b*sigm/m/m),2)),0.5);
double sig_Vp = sig_Vbr;
cout<<"V_br = "<<Vbr<<" +/- "<<sig_Vbr<<" V"<<endl;
cout<<"V_p = "<<Vp<<" +/- "<<sig_Vp<<" V"<<endl;
//----------------------------------------------------------------------------------------------------//
//-------------------------------Draw plots to canvas and save to files-------------------------------//
TCanvas *c1 = new TCanvas();
f->SetLineWidth(1);
gr->SetLineWidth(0);
gr->SetMarkerStyle(20);
gr->SetMarkerSize(0.5);
gr->SetTitle("Breaking Voltage Plot");
gr->GetXaxis()->SetTitle("Voltage (V)");
gr->GetYaxis()->SetTitle("Current (mA)");
gr->Draw("AP");
c1->SaveAs("/home/jeremie1001/Documents/School/Uni/Course/4th_Year/PHYS4007/SiPM/Report/Figures/breakVolt.png");
//----------------------------------------------------------------------------------------------------//
}
<file_sep>#ifndef sipm_h
#define sipm_h
#include <iostream>
#include <math.h>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
//---------------------------------Initial declaaration of functions----------------------------------//
vector< vector<double> > getData(string file, char delim, int start);
double EE(int exponentPassed);
Double_t poissonf(Double_t*x,Double_t*par);
//----------------------------------------------------------------------------------------------------//
//--------------------------------------Data retireval function---------------------------------------//
vector< vector<double> > getData(string file, char delim, int start) {
//-------------------------------Push function parameters to variables--------------------------------//
string fileName = file;
char delimiter = delim;
int startLine = start;
//----------------------------------------------------------------------------------------------------//
//------------------------------Open stream of file with given filename-------------------------------//
ifstream ifs(fileName.c_str());
//----------------------------------------------------------------------------------------------------//
//--------------------------------------Variable initialization---------------------------------------//
vector< vector<double> > dataSet; //Vector for full dataset, each element is a vector of elements seperated by given delimiter
vector<double> row; //Each row of dataset, elements are all values that were seperated by given delimiter
string lineString; //String that each row is pushed to before being seperated bby given delimiter
string elementString; //String that each element of a given line is pushed to before being added to row vector
int lineCount = 0; //Integer to keep track of position in file, used to skip header rows if necessary
while( getline(ifs, lineString) ) {
//Increase lineCount variable
lineCount ++;
//Clear row vector for new row
row.clear();
//Add current line to lineString variable
stringstream ss(lineString);
//Split lineString into elements one by one, convert to double and add each to row vector
while(getline(ss, elementString, delimiter)){
row.push_back( strtod(elementString.c_str(), NULL) );
}
//Add row vector to dataSet vector, skip header rows if necessary
if (lineCount >= startLine) {
dataSet.push_back(row);
}
}
return dataSet;
//----------------------------------------------------------------------------------------------------//
}
Double_t poissonf(Double_t*x,Double_t*par) {
return par[0]*TMath::Poisson(x[0],par[1]);
}
//----------------------------------------------------------------------------------------------------//
//-----------------Scientific notation function, for simplifying nomenclature in code-----------------//
double EE(int exponentPassed) {
int exponent = exponentPassed;
return pow(10,exponent);
}
//----------------------------------------------------------------------------------------------------//
#endif
<file_sep>// @(#)root
#include <cstdlib>
#include <TFile.h>
#include "SiPM.h"
void gainFit32() {
//------------------------------------Retrieve data from CSV files------------------------------------//
string fileName = "/home/jeremie1001/Documents/School/Uni/Course/4th_Year/PHYS4007/SiPM/Data/dataset1/100att_gain32.csv";
vector< vector<double> > data = getData(fileName, ',', 0);
//----------------------------------------------------------------------------------------------------//
//--------------------------Create Channel v. Counts plot for gaussian peaks---------------------------//
unsigned int const size = data.size();
Double_t x[size];
Double_t y[size];
for(int i = 0; i < data.size(); i++) {
x[i] = data[i][0];
y[i] = data[i][1];
}
TGraph* channelCountsTGraph;
channelCountsTGraph = new TGraph(data.size(),x,y);
//----------------------------------------------------------------------------------------------------//
//----Add gauss fit to each peak w/ ranges defined in limits array & push params to results array-----//
int gaussLimits[11][2] = {{22,68},{76,123},{124,178},{180,230},{238,284},{295,339},{346,394},{402,451},{456,508},{514,564},{567,621}};
int gaussFitNum = sizeof(gaussLimits)/sizeof(gaussLimits[0]);
double gaussResults[11][3][2];
for(int i = 0; i < gaussFitNum; i++) {
TF1 *g1 = new TF1("m1","gaus",x[gaussLimits[i][0]],x[gaussLimits[i][1]]);
channelCountsTGraph->Fit("m1","QR+");
for (int j = 0; j < 3; j++) {
gaussResults[i][j][0] = g1->GetParameter(j);
gaussResults[i][j][1] = g1->GetParError(j);
string paramName = "";
if (j == 0) {
paramName = "Peak";
} else if (j == 1) {
paramName = "Mean";
} else if (j == 2) {
paramName = "Sigma";
}
}
g1->SetLineWidth(1);
}
//----------------------------------------------------------------------------------------------------//
//------------------Get gain for each set of adjacent peaks and plot against channel------------------//
double conversion = 1.027*EE(-15);
double electron = 1.602*EE(-19);
double sumResolution = 0;
double sumDiff = 0;
for (size_t i = 0; i < gaussFitNum-1; i++) {
sumDiff += (gaussResults[i+1][1][0]-gaussResults[i][1][0]);
sumResolution += (gaussResults[i+1][1][0]-gaussResults[i][1][0])/pow(TMath::Abs(pow((gaussResults[i+1][2][0]),2)-pow((gaussResults[i][2][0]),2)),0.5);
}
double avgResolution = sumResolution/(gaussFitNum-1);
double avgMeanDiff = sumDiff/(gaussFitNum-1);
double gain = conversion*avgMeanDiff/electron;
cout<<"Resolution = "<<avgResolution<<endl;
cout<<"Gain = "<<gain<<endl;
unsigned int const sizeGainLinear = gaussFitNum-3;
Double_t xGainLinear[sizeGainLinear];
Double_t yGainLinear[sizeGainLinear];
Double_t exGainLinear[sizeGainLinear];
Double_t eyGainLinear[sizeGainLinear];
for(int i = 0; i < sizeGainLinear; i++) {
xGainLinear[i] = (gaussResults[i+1][1][0]+gaussResults[i][1][0])/2;
yGainLinear[i] = conversion*(gaussResults[i+1][1][0]-gaussResults[i][1][0])/electron;
eyGainLinear[i] = conversion/electron*pow((pow(gaussResults[i+1][1][1],2)+pow(gaussResults[i][1][1],2)),0.5);
}
TGraphErrors* gainLinearTGraph;
gainLinearTGraph = new TGraphErrors(sizeGainLinear,xGainLinear,yGainLinear,0,eyGainLinear);
//----------------------------------------------------------------------------------------------------//
//----------------------------Fit linear function to Gain v. Channel plot-----------------------------//
gainLinearTGraph->Fit("pol1", "Q");
TF1 *f = gainLinearTGraph->GetFunction("pol1");
double b = f->GetParameter(0);
double m = f->GetParameter(1);
double sigb = f->GetParError(0);
double sigm = f->GetParError(1);
cout<<"Correlation factor of gain v channel: "<<gainLinearTGraph->GetCorrelationFactor()<<endl;
//----------------------------------------------------------------------------------------------------//
//----------------------------------------Gaussian peaks plot-----------------------------------------//
unsigned int const sizePoisson = gaussFitNum;
TH1D *gainPoisson;
gainPoisson = new TH1D("h1", "Histogram for joint datasets", sizePoisson, 0, sizePoisson);
TF1 *g = new TF1("g","gaus",2000,10000);
for(int i = 0; i < sizePoisson; i++) {
g->SetParameters(gaussResults[i][0][0],gaussResults[i][1][0],gaussResults[i][2][0]);
gainPoisson->SetBinContent(i+1,g->Integral(x[gaussLimits[i][0]],x[gaussLimits[i][1]]));
}
gainPoisson->Scale(1/(gainPoisson->Integral()));
TF1 *funcPoisson = new TF1("poisson",[](double*x,double*p){return TMath::Poisson(x[0],p[0]);},0,20,1);
TF1 *g2 = new TF1("g2","gaus",0,25);
gainPoisson->Fit("g2");
//----------------------------------------------------------------------------------------------------//
//-------------------------------Draw plots to canvas and save to files-------------------------------//
TCanvas *c1 = new TCanvas();
gErrorIgnoreLevel = kWarning;
channelCountsTGraph->SetLineWidth(0);
channelCountsTGraph->SetMarkerStyle(20);
channelCountsTGraph->SetMarkerSize(0.5);
channelCountsTGraph->SetTitle("Gain Plot");
channelCountsTGraph->GetXaxis()->SetTitle("Channel");
channelCountsTGraph->GetYaxis()->SetTitle("Counts");
channelCountsTGraph->Draw("AP");
c1->SaveAs("/home/jeremie1001/Documents/School/Uni/Course/4th_Year/PHYS4007/SiPM/Report/Figures/gainFit32.png");
gainLinearTGraph->SetMarkerStyle(20);
gainLinearTGraph->SetMarkerSize(0.5);
gainLinearTGraph->SetTitle("Gain Plot");
gainLinearTGraph->GetXaxis()->SetTitle("Channel");
gainLinearTGraph->GetYaxis()->SetTitle("Gain");
gainLinearTGraph->Draw("AP");
c1->SaveAs("/home/jeremie1001/Documents/School/Uni/Course/4th_Year/PHYS4007/SiPM/Report/Figures/gainLinear32.png");
gainPoisson->SetMarkerStyle(20);
gainPoisson->SetMarkerSize(1);
gainPoisson->SetTitle("Poisson Plot");
gainPoisson->GetXaxis()->SetTitle("Channel");
gainPoisson->GetYaxis()->SetTitle("N [Peak Number]");
gainPoisson->Draw();
c1->SaveAs("/home/jeremie1001/Documents/School/Uni/Course/4th_Year/PHYS4007/SiPM/Report/Figures/gainPoisson32.png");
//----------------------------------------------------------------------------------------------------//
}
<file_sep>## SiPM Charaterization lab report
<file_sep>// @(#)root
#include <cstdlib>
#include <TFile.h>
#include "SiPM.h"
void crystal() {
//------------------------------------------Data Processing-------------------------------------------//
string base = "/home/jeremie1001/Documents/School/Uni/Course/4th_Year/PHYS4007/SiPM/Data/";
string file[6] = {
"crystal/bkgd_crystal_histo.csv",
"crystal/cs_137_crystal_histo.csv",
"crystal/na_22_crystal_histo.csv"
};
TCanvas *c1 = new TCanvas();
string fileName = base+file[1];
vector< vector<double> > dataBgd = getData(base+file[0], ',', 0);
vector< vector<double> > dataCs = getData(base+file[1], ',', 0);
vector< vector<double> > dataNa = getData(base+file[2], ',', 0);
//----------------------------------------------------------------------------------------------------//
//---------------------------------------------Background---------------------------------------------//
unsigned int const sizeBgd = dataBgd.size();
Double_t xBgd[sizeBgd];
Double_t yBgd[sizeBgd];
for(int i = 0; i < dataBgd.size(); i++) {
xBgd[i] = dataBgd[i][0];
yBgd[i] = dataBgd[i][1];
}
TGraph* graphBgd;
graphBgd = new TGraph(dataBgd.size(),xBgd,yBgd);
//----------------------------------------------------------------------------------------------------//
//-----------------------------------------------Cesium-----------------------------------------------//
unsigned int const sizeCs = dataCs.size();
Double_t xCs[sizeCs];
Double_t yCs[sizeCs];
for(int i = 0; i < dataCs.size(); i++) {
xCs[i] = dataCs[i][0];
yCs[i] = dataCs[i][1];
}
TGraph* graphCs;
graphCs = new TGraph(dataCs.size(),xCs,yCs);
TF1 *cesiumFit = new TF1("cesiumFit","gaus",7700,12000);
graphCs->Fit("cesiumFit", "QR+");
//----------------------------------------------------------------------------------------------------//
//-----------------------------------------------Sodium-----------------------------------------------//
unsigned int const sizeNa = dataNa.size();
Double_t xNa[sizeNa];
Double_t yNa[sizeNa];
for(int i = 0; i < dataNa.size(); i++) {
xNa[i] = dataNa[i][0];
yNa[i] = dataNa[i][1];
}
TGraph* graphNa;
graphNa = new TGraph(dataNa.size(),xNa,yNa);
TF1 *sodiumFit1 = new TF1("sodiumFit1","gaus",5800,9000);
graphNa->Fit("sodiumFit1", "QR+");
TF1 *sodiumFit2 = new TF1("sodiumFit2","gaus",15000,24000);
graphNa->Fit("sodiumFit2", "QR+");
//----------------------------------------------------------------------------------------------------//
//---------------------------------------------Linear Fit---------------------------------------------//
unsigned int const sizeCalibration = 2;
double yCalibration[sizeCalibration] = {sodiumFit1->GetParameter(1), sodiumFit2->GetParameter(1)};
double yCalibrationErrors[sizeCalibration] = {sodiumFit1->GetParameter(2), sodiumFit2->GetParameter(2)};
double xCalibration[sizeCalibration] = {0.511, 1.27};
TGraphErrors *graphCalibration = new TGraphErrors(sizeCalibration, xCalibration, yCalibration, 0, yCalibrationErrors);
TF1 *calibrationFit = new TF1("calibrationFit","pol1",0,2);
graphCalibration->Fit("calibrationFit", "Q");
double calibrationResults[2][2] = {
{calibrationFit->GetParameter(0), calibrationFit->GetParError(0)},
{calibrationFit->GetParameter(1), calibrationFit->GetParError(1)}
};
//----------------------------------------------------------------------------------------------------//
//----------------------------------------------Analysis----------------------------------------------//
double cesiumChannel[2] = {cesiumFit->GetParameter(1), cesiumFit->GetParameter(2)};
double cesiumEnergy = (cesiumChannel[0]-calibrationResults[0][0])/calibrationResults[1][0];
double cesiumEnergyError = pow(pow((cesiumChannel[1]/calibrationResults[1][0]),2) + pow((calibrationResults[0][1]/calibrationResults[1][0]),2) + pow((calibrationResults[1][1]*(cesiumChannel[0]-calibrationResults[0][0])/pow(calibrationResults[1][0],2)),2),0.5);
cout<<"Cesium Energy: "<<cesiumEnergy<<" +/- "<<cesiumEnergyError<<endl;
//----------------------------------------------------------------------------------------------------//
//----------------------------------------------Drawing-----------------------------------------------//
gErrorIgnoreLevel = kWarning;
graphBgd->SetLineWidth(0);
graphBgd->SetMarkerStyle(20);
graphBgd->SetMarkerSize(0.5);
graphBgd->SetTitle("Background Spectrum");
graphBgd->GetXaxis()->SetTitle("Channel");
graphBgd->GetYaxis()->SetTitle("Counts");
graphBgd->Draw("AP");
c1->SaveAs("/home/jeremie1001/Documents/School/Uni/Course/4th_Year/PHYS4007/SiPM/Report/Figures/crystalBgdSpectrum.png");
graphCs->SetLineWidth(0);
graphCs->SetMarkerStyle(20);
graphCs->SetMarkerSize(0.5);
graphCs->SetTitle("Cs-137 Spectrum");
graphCs->GetXaxis()->SetTitle("Channel");
graphCs->GetYaxis()->SetTitle("Counts");
graphCs->Draw("AP");
c1->SaveAs("/home/jeremie1001/Documents/School/Uni/Course/4th_Year/PHYS4007/SiPM/Report/Figures/crystalCesiumSpectrum.png");
graphNa->SetLineWidth(0);
graphNa->SetMarkerStyle(20);
graphNa->SetMarkerSize(0.5);
graphNa->SetTitle("Na-22 Spectrum");
graphNa->GetXaxis()->SetTitle("Channel");
graphNa->GetYaxis()->SetTitle("Counts");
graphNa->Draw("AP");
c1->SaveAs("/home/jeremie1001/Documents/School/Uni/Course/4th_Year/PHYS4007/SiPM/Report/Figures/crystalSodiumSpectrum.png");
graphCalibration->SetMarkerStyle(20);
graphCalibration->SetMarkerSize(0.5);
graphCalibration->SetTitle("Calibration");
graphCalibration->GetXaxis()->SetTitle("Energy (MeV)");
graphCalibration->GetYaxis()->SetTitle("Channel");
graphCalibration->Draw("AP");
c1->SaveAs("/home/jeremie1001/Documents/School/Uni/Course/4th_Year/PHYS4007/SiPM/Report/Figures/crytalCalibrationFit.png");
//----------------------------------------------------------------------------------------------------//
}
|
648d23ed13b31caa1325b65b0fe8e9b83ba665dd
|
[
"Markdown",
"C++"
] | 5 |
C++
|
Jeremie1001/SiPM
|
9c72986b675878680fafbcde777f69ef7c363144
|
f10175eabf0da0307e23ebd08e934f8c4ef58c39
|
refs/heads/master
|
<repo_name>ahmedslove3/adevaNote<file_sep>/README.md
# Adeva Frontend Task
## Getting Started
- Run `yarn && yarn start` to install all dependencies and start the application.
- Go to [home](http://localhost:8081) to get started.
- Run `Yarn jest` to run the tests.
### NOTE: there is a bug at DraftJS (used to create a wyswig for note editing) which causes nots note to presist due to convertion error at the lib.
### I worked alot on solving it but it took me two days and I still didn't find a solution so I decided to submit the task.
<file_sep>/src/views/Notes/SideBar.js
import React, { useState } from 'react';
// @material-ui/core components
import { makeStyles } from "@material-ui/core/styles";
import InputAdornment from "@material-ui/core/InputAdornment";
import Button from "components/CustomButtons/Button.js";
import Card from "components/Card/Card.js";
import CardBody from "components/Card/CardBody.js";
import CardFooter from "components/Card/CardFooter.js";
import CustomInput from "components/CustomInput/CustomInput.js";
import Clear from "@material-ui/icons/Clear";
// @material-ui/icons
import Search from "@material-ui/icons/Search";
import Add from "@material-ui/icons/Add";
import styles from "assets/jss/material-kit-react/views/loginPage.js";
import NoteSearchContainer from "services/noteSearch.js"
import { Subscribe } from 'unstated';
const useStyles = makeStyles(styles);
const SideBar = (props) => {
const classes = useStyles();
const [searchValue, setSearch] = useState('');
const handleDelete = (e, note) => {
e.stopPropagation();
props.noteContainer.deleteNote(note.id);
}
return (
<Card style={style.sideBar.card} >
<CardBody>
<CustomInput labelText="Search" id="search"
formControlProps={{
fullWidth: true,
}}
labelProps={{ style: style.searchLabel }}
inputProps={{
value: searchValue,
onChange: (e) => {
setSearch(e.target.value);
props.noteContainer.search(e.target.value);
},
style: style.searchInput,
type: "text",
endAdornment: (
<InputAdornment position="end">
<Search className={classes.searchIcon} />
</InputAdornment>
)
}}
/>
{
props.noteContainer.state.notes.map(
(note, i) => {
return (
<div key={i} style={style.sideBar.notes} onClick={() => props.noteContainer.selectNote(note.id)} >
<CardBody className=".note">
<h4>{note.title}</h4>
<Button onClick={(e) => handleDelete(e, note)} justIcon round style={style.deleteButton}>
<Clear />
</Button>
</CardBody>
</div>
);
}
)
}
<Button onClick={() => props.noteContainer.addNote({ id: newId, title: "Note title", body: null, textBody: null, editing: true })} justIcon round style={style.addButton}>
<Add style={style.searchIcon} className={classes.searchIcon} />
</Button>
</CardBody>
</Card>
);
}
const style = {
gridContainer: {
height: "100%",
},
addButton: {
backgroundColor: "#00acc1",
position: "absolute",
right: "20px",
bottom: "20px",
},
deleteButton: {
float: "right",
minWidth: "10px",
width: "10px",
height: "10px",
position: "absolute",
top: "0",
right: "0"
},
searchInput: {
height: "50px",
},
searchLabel: {
marginTop: "15px",
},
gridItem: {
height: "100%",
},
cardFooter: {
position: "relative",
}
,
sideBar: {
card: {
margin: '0',
height: "100%",
backgroundColor: "#212121"
},
notes: {
margin: "0",
width: "100%",
color: "white",
position: "relative"
}
},
}
export default SideBar;<file_sep>/src/services/noteSearch.js
import { Container } from 'unstated';
import _ from 'Lodash';
import StorageProvider from 'services/storageProvider'
class NoteSearchContainer extends Container {
// add multiple empty notes
// close and open with empty notes
NOTES_KEY = "notes";
selectedNote = "";// represent the current selected note
savedNotes = [];
initFlage = false;
editorInialState = null;
constructor() {
super();
console.log("constructor");
this.savedNotes = StorageProvider.read(this.NOTES_KEY);
this.state = {
notes: this.savedNotes || []
};
}
init(note) {
if (this.initFlage) return;
this.initFlage = true;
if (!this.savedNotes.length) {
return this.addNote(note);
} else {
return this.selectNote(0);
}
}
search(value) {
console.log("search");
if (!value) {
this.setState({ notes: this.savedNotes });
return;
}
const result = _.filter(this.savedNotes, (o) => {
return (-1 < o.title.search(value) || -1 < o.textBody.search(value));
});
return this.setState({ notes: result });
}
addNote(note) {
console.log("addNote");
// if there was a note being edited save it an switch to the new one
let currentNotes = this.state.notes;
let newId = 0;
// if we our array is not empty overide the new id value
if (currentNotes.length > 0) {
newId = currentNotes[currentNotes.length - 1].id + 1;
}
note.id = newId;
let newNotes = [...currentNotes, note];
// select the new note after making it
return this.setState({ notes: newNotes },
() => {
this.selectNote(newId);
this.presistNotes();
}
);
}
selectNote(id) {
console.log("selectNote", id);
const notes = _.map(this.state.notes, (o) => {
if (o.id === id) {
o.editing = true;
this.selectedNote = o;
} else {
o.editing = false;
}
return o;
});
return this.setState({ notes: notes })
}
deleteNote(id) {
console.log("deleteNote");
const notes = _.filter(this.state.notes, (o) => {
return o.id !== id
});
console.log("befor setState", notes);
// select the new note after making it
return this.setState({ notes: notes },
() => {
console.log("current state", this.state);
this.selectNote(notes[0].id);
this.presistNotes();
}
);
}
editNote(state, textState) {
console.log("editNote");
const notes = _.map(this.state.notes, (o) => {
if (o.editing) {
o.body = state;
o.textBody = textState
}
return o;
});
return this.setState({ notes: notes },
() => {
this.presistNotes();
});
}
editTitle(title) {
console.log("editTitel");
const notes = _.map(this.state.notes, (o) => {
if (o.editing) {
o.title = title;
}
return o;
});
return this.setState({ notes: notes },
() => {
this.presistNotes();
})
}
presistNotes() {
console.log("presist");
this.savedNotes = [...this.state.notes];
console.log(this.state.notes);
StorageProvider.save(this.NOTES_KEY, this.savedNotes);
}
}
export default NoteSearchContainer;<file_sep>/__tests__/NoteContainerTest.js
import React from 'react';
import renderer from 'react-test-renderer';
import SideBar from "views/Notes/SideBar.js";
import { shallow, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import NoteSearchContainer from 'services/noteSearch.js';
import { Provider } from 'unstated';
const container = new NoteSearchContainer();
test("inial NoteContainer state", async () => {
await container.init({
id: 0,
body: null,
editing: true,
textBody: "This is a note one",
title: "note 1"
});
console.log(container);
// find 1 notes by defaults
expect(container.state.notes).toMatchObject([
{
id: 0,
body: null,
editing: true,
textBody: "This is a note one",
title: "note 1"
}]
);
});
test("adding anothr note", async () => {
// add another note
await container.addNote({
body: null,
editing: true,
textBody: "This is a note two",
title: "note 2"
})
// find 2 notes
expect(container.state.notes).toMatchObject([
{
id: 0,
body: null,
editing: false,
textBody: "This is a note one",
title: "note 1"
},
{
id: 1,
body: null,
editing: true,
textBody: "This is a note two",
title: "note 2"
},
]
);
});
test("selecting the first note again", async () => {
await container.selectNote(0);
// the current selected note
expect(container.selectedNote).toMatchObject(
{
id: 0,
body: null,
editing: true,
textBody: "This is a note one",
title: "note 1"
}
);
// state shape
expect(container.state.notes).toMatchObject([
{
id: 0,
body: null,
editing: true,
textBody: "This is a note one",
title: "note 1"
},
{
id: 1,
body: null,
editing: false,
textBody: "This is a note two",
title: "note 2"
},
]
);
});
test("editing the selected note", async () => {
await container.editNote("normal body edited", "Text body edited");
await container.editTitle("a new title");
// new state shap
expect(container.state.notes).toMatchObject([
{
id: 0,
body: "normal body edited",
editing: true,
textBody: "Text body edited",
title: "a new title"
},
{
id: 1,
body: null,
editing: false,
textBody: "This is a note two",
title: "note 2"
},
]
);
});
test("searching for a note", async () => {
// add other notes for search testing
await container.addNote({
body: null,
textBody: "This is a note specific string",
title: "note 2"
});
await container.addNote({
body: null,
textBody: "This is a note",
title: "specific title"
});
await container.search("specific string") // search for the above one
expect(container.state.notes).toMatchObject([
{
id: 2,
body: null,
editing: false,
textBody: "This is a note specific string",
title: "note 2"
}]
);
await container.search("specific title") // search for the lower one
expect(container.state.notes).toMatchObject([
{
id: 3,
body: null,
editing: true,
textBody: "This is a note",
title: "specific title"
}]
);
await container.search("") // nothing returns all the notes
expect(container.state.notes).toMatchObject([
{
id: 0,
body: "normal body edited",
editing: false,
textBody: "Text body edited",
title: "a new title"
},
{
id: 1,
body: null,
editing: false,
textBody: "This is a note two",
title: "note 2"
},
{
id: 2,
body: null,
editing: false,
textBody: "This is a note specific string",
title: "note 2"
},
{
id: 3,
body: null,
editing: true,
textBody: "This is a note",
title: "specific title"
}
]
);
});
test("deleteing a note", async () => {
await container.deleteNote(2);//delete the third one
expect(container.state.notes).toMatchObject([
{
id: 0,
body: "normal body edited",
editing: true,
textBody: "Text body edited",
title: "a new title"
},
{
id: 1,
body: null,
editing: false,
textBody: "This is a note two",
title: "note 2"
},
{
id: 3,
body: null,
editing: false,
textBody: "This is a note",
title: "specific title"
}]
);
});
<file_sep>/__mocks__/fileMock.js
module.export = "A file";<file_sep>/src/services/storageProvider.js
// reads data from localstorage
function read(key) {
return JSON.parse(window.localStorage.getItem(key)) || []
}
//saves data to localstoragef
function save(key, value) {
return window.localStorage.setItem(key, JSON.stringify(value))
}
// export default saveData;
export default { read, save };
|
673b15812803cc0909e8a44c58264c2e095ee9d1
|
[
"Markdown",
"JavaScript"
] | 6 |
Markdown
|
ahmedslove3/adevaNote
|
2707226b17b8de284fe1e8cdbccf925989f7c9f2
|
802e56e8980d2bdd1e9bafc17dc3db7f6026c93a
|
refs/heads/master
|
<repo_name>gitever/xjson<file_sep>/README.md
# xjson
2016-5-20 17:37:35
流传递、md5、base64 添加。
<file_sep>/src/main/java/com/x/xjson/HttpAccessor.java
/**
*
* File Name: HttpAccessor.java
* Package Name: com.x.xijson
* Date: 2016年5月20日 上午10:34:10
*/
package com.x.xjson;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentProducer;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* @author x
*
*/
public class HttpAccessor {
private CloseableHttpClient httpClient;
private HttpGet httpGet;
final static int BUFFER_SIZE = 4096;
public HttpAccessor(){
httpClient = HttpClients.createDefault();
}
public String getResponseByPost(String url, final String param, final String charset){
ContentProducer cp = new ContentProducer() {
public void writeTo(OutputStream arg0) throws IOException {
arg0.write(param.getBytes(charset));
arg0.flush();
arg0.close();
}
};
String result = "";
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new EntityTemplate(cp));
try {
HttpResponse response = httpclient.execute(httpPost);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
InputStream inputStream = resEntity.getContent();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, charset));
String readLine =null;
while((readLine = br.readLine()) !=null){
result = result + readLine;
}
inputStream.close();
br.close();
System.out.println("========="+result);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public String getResponseByGet(String url, String encode){
String result = "";
httpGet = new HttpGet(url);
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
HttpEntity resEntity = response.getEntity();
if(resEntity != null){
result = EntityUtils.toString(resEntity, encode);
}
EntityUtils.consume(resEntity);
response.close();
}catch (Exception e){
e.printStackTrace();
}
return result;
}
public String InputStreamTOString(InputStream in) throws Exception{
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[BUFFER_SIZE];
int count = -1;
while((count = in.read(data,0,BUFFER_SIZE)) != -1)
outStream.write(data, 0, count);
data = null;
return new String(outStream.toByteArray(),"UTF-8");
}
}
<file_sep>/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.x</groupId>
<artifactId>xijson</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>xijson</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<!-- http://mvnrepository.com/artifact/org.fusesource/sigar -->
<dependency>
<groupId>org.fusesource</groupId>
<artifactId>sigar</artifactId>
<version>1.6.4</version>
</dependency>
<!-- http://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
<!-- http://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
<!-- <dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
</dependency> -->
<!-- http://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
<!-- http://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-xml -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.6.3</version>
</dependency>
<!-- http://mvnrepository.com/artifact/dom4j/dom4j -->
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
</dependencies>
</project>
<file_sep>/src/main/java/com/x/xjson/JsonUtil.java
/**
*
* File Name: JsonUtil.java
* Package Name: com.x.xjson
* Date: 2016年5月25日 上午9:51:39
*/
package com.x.xjson;
import java.io.File;
import java.io.IOException;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
/**
* @author x
* Xstream
* jackson
*
*/
public class JsonUtil {
private static ObjectMapper mapper;
private static XmlMapper xml;
private JsonUtil(){ }
public static synchronized ObjectMapper getInstance() {
if(mapper == null){
mapper = new ObjectMapper();
}
return mapper;
}
public static synchronized XmlMapper getXmlMapper(){
if (xml == null) {
xml = new XmlMapper();
}
return xml;
}
/**
* 对象转json
* @param obj
* @return
* @throws Exception
*/
public static String beanToJson(Object obj){
try {
ObjectMapper objectMapper = getInstance();
String json = objectMapper.writeValueAsString(obj);
return json;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 对象转json,排除空属性
* @param obj
* @return
* @throws Exception
*/
public static String beanToJson_NOEMPTY(Object obj){
try {
ObjectMapper objectMapper = getInstance();
objectMapper.setSerializationInclusion(Include.NON_EMPTY); // 配置mapper忽略空属性
String json = objectMapper.writeValueAsString(obj);
return json;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 对象转json,并格式化
* 生产中不建议使用,加大传输量
* @param obj
* @return
* @throws Exception
*/
public static String beanToJson_FORMAT(Object obj){
try {
ObjectMapper objectMapper = getInstance();
mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // FORMAT
String json = objectMapper.writeValueAsString(obj);
return json;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* json转对象
* @param json
* @param cls
* @return
* @throws Exception
*/
public static Object jsonToObject(String json, Class<?> cls){
try {
ObjectMapper objectMapper = getInstance();
return objectMapper.readValue(json, cls);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将对象转json,写入path路径
* @param obj
* @param path
* @throws IOException
* @throws JsonMappingException
* @throws JsonGenerationException
*/
public static void objToJsonPath(Object obj, String path){
try {
ObjectMapper mapper = getInstance();
// 格式化
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
// 配置mapper忽略空属性
mapper.setSerializationInclusion(Include.NON_EMPTY);
mapper.writeValue(new File(path), obj);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 将对象转为xml
* @param obj
* @return
*/
public static String objToXml(Object obj){
try {
XmlMapper xml = getXmlMapper();
return xml.writeValueAsString(obj);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将xml转为对象
* @param xmlValue
* @param cls
* @return
*/
public static <T> T xmlToObj(String xmlValue, Class<T> cls){
XmlMapper xml = getXmlMapper();
try {
return xml.readValue(xmlValue, cls);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 将对象转xml,写入path路径
* xml处理时需要jackson-dataformat-xml、stax2-api
* @param obj
* @param path
*/
public static void objToXmlPath(Object obj, String path){
try {
XmlMapper xml = getXmlMapper();
xml.writeValue(new File(path), obj);
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>/src/main/java/com/x/xjson/Main.java
/**
*
* File Name: f.java
* Package Name: com.x.xjson
* Date: 2016年5月23日 下午2:10:27
*/
package com.x.xjson;
import java.awt.Toolkit;
import javax.swing.JOptionPane;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.wb.swt.SWTResourceManager;
/**
* @author x
*
*/
public class Main {
protected Shell shell;
private Text txtPara;
private Text txtJson;
private Text txtMDencode;
private Text txtMDdecode;
private Text txtBASEencode;
private Text txtBASEdecode;
private static String UTF8 = "utf-8";
private Text text;
/**
* Launch the application.
* @param args
*/
public static void main(String[] args) {
try {
Main window = new Main();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
* @wbp.parser.entryPoint
*/
/**
*
*/
protected void createContents() {
shell = new Shell();
shell.setSize(800, 650);
shell.setText("SWT");
// 得到屏幕的宽度和高度
int screenHeight = Toolkit.getDefaultToolkit().getScreenSize().height;
int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
// 得到Shell窗口的宽度和高度
int shellHeight = shell.getBounds().height;
int shellWidth = shell.getBounds().width;
// 如果窗口大小超过屏幕大小,让窗口与屏幕等大
if (shellHeight > screenHeight)
shellHeight = screenHeight;
if (shellWidth > screenWidth)
shellWidth = screenWidth;
// 让窗口在屏幕中间显示
shell.setLocation(( (screenWidth - shellWidth) / 2 ),((screenHeight - shellHeight) / 2 ) );
Label lblUrl = new Label(shell, SWT.NONE);
lblUrl.setBounds(10, 10, 33, 17);
lblUrl.setText("URL:");
Label lblPara = new Label(shell, SWT.NONE);
lblPara.setBounds(10, 33, 33, 17);
lblPara.setText("Data:");
final Combo cmbURL = new Combo(shell, SWT.NONE);
cmbURL.setBounds(49, 10, 499, 25);
String propUrl = PropUtil.getValue("url");
if (propUrl != null && !"".equals(propUrl)) {
String[] urls = propUrl.split(",");
int number = urls.length; // 总长度
// 显示前20条
if (number > 20) {
int num = 0;
String [] newUrls = new String[20];
for (int i = number-20; i < number; i++) {
newUrls[num] = urls[i];
num++;
}
cmbURL.setItems(newUrls);
}else
cmbURL.setItems(urls);
}
cmbURL.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent arg0) {
// dll 索引
int index = cmbURL.getSelectionIndex();
String propPara = PropUtil.getValue("param"+index);
txtPara.setText("");
if (propPara!= null) {
txtPara.setText(Base64Util.decode(propPara));
}
}
public void widgetDefaultSelected(SelectionEvent arg0) {
}
});
Combo cmbCT = new Combo(shell, SWT.READ_ONLY);
cmbCT.setFont(SWTResourceManager.getFont("微软雅黑", 8, SWT.NORMAL));
cmbCT.setItems(new String[]{"application/x-www-form-urlencoded","multipart/form-data","application/json","text/xml","",""});
cmbCT.setBounds(647, 33, 127, 24);
cmbCT.select(0);
Combo cmbAccept = new Combo(shell, SWT.READ_ONLY);
cmbAccept.setFont(SWTResourceManager.getFont("微软雅黑", 8, SWT.NORMAL));
cmbAccept.setItems(new String[]{"application/x-www-form-urlencoded","text/html","text/xml","application/x-javascript","application/json"});
cmbAccept.setBounds(647, 64, 127, 25);
cmbAccept.select(0);
final Combo cmbType = new Combo(shell, SWT.READ_ONLY);
cmbType.setFont(SWTResourceManager.getFont("微软雅黑", 8, SWT.NORMAL));
cmbType.setItems(new String[] {"GET", "POST"});
cmbType.setBounds(647, 95, 127, 25);
cmbType.select(1);
Label lblNewLabel = new Label(shell, SWT.NONE);
lblNewLabel.setAlignment(SWT.RIGHT);
lblNewLabel.setBounds(561, 36, 73, 17);
lblNewLabel.setText("ContentType");
Label lblNewLabel_1 = new Label(shell, SWT.NONE);
lblNewLabel_1.setAlignment(SWT.RIGHT);
lblNewLabel_1.setBounds(593, 67, 41, 22);
lblNewLabel_1.setText("Accept");
Label lblNewLabel_2 = new Label(shell, SWT.NONE);
lblNewLabel_2.setAlignment(SWT.RIGHT);
lblNewLabel_2.setBounds(598, 98, 36, 17);
lblNewLabel_2.setText("Type");
Button btnNewButton = new Button(shell, SWT.CENTER);
btnNewButton.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String url = cmbURL.getText();
String para = txtPara.getText();
String respJson = null;
if ("".equals(url)) {
JOptionPane.showMessageDialog(null, "请求啥呢");
return;
}
if (cmbType.getSelectionIndex() == 0) { // get
respJson = new HttpAccessor().getResponseByGet(url, UTF8);
}else{ // post
respJson = new HttpAccessor().getResponseByPost(url, para, UTF8);
}
txtJson.setText(respJson);
String fotmatStr = FormatJSON.format(txtJson.getText());
txtJson.setText(fotmatStr);
int index = cmbURL.getItems().length;
PropUtil.updateProperties("url", url + ",");
PropUtil.updateProperties("param"+ (index <= 0 ? 0 : index), Base64Util.encode(para));
cmbURL.add(url, index);
}
});
btnNewButton.setBounds(694, 5, 80, 27);
btnNewButton.setText("go");
txtPara = new Text(shell, SWT.BORDER | SWT.WRAP);
txtPara.setBounds(49, 36, 499, 96);
txtPara.addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent arg0) {
}
public void keyPressed(KeyEvent e) {
if (e.stateMask == SWT.CTRL && e.keyCode == 'a') {
txtPara.selectAll();
}
}
});
Button btnMd = new Button(shell, SWT.CHECK);
btnMd.setBounds(562, 10, 49, 17);
btnMd.setText("MD5");
Button btnBase = new Button(shell, SWT.CHECK);
btnBase.setBounds(617, 10, 65, 17);
btnBase.setText("BASE64");
TabFolder tabFolder = new TabFolder(shell, SWT.NONE);
tabFolder.setBounds(10, 135, 764, 467);
TabItem tbtmJson = new TabItem(tabFolder, SWT.NONE);
tbtmJson.setText("json");
Composite composite = new Composite(tabFolder, SWT.NONE);
tbtmJson.setControl(composite);
txtJson = new Text(composite, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
txtJson.setBounds(10, 40, 736, 387);
txtJson.setFont(SWTResourceManager.getFont("Consolas", 11, SWT.NORMAL));
Button btnJson = new Button(composite, SWT.NONE);
btnJson.setBounds(10, 10, 80, 19);
btnJson.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
String fotmatStr = FormatJSON.format(txtJson.getText());
txtJson.setText(fotmatStr);
}
});
btnJson.setText("format");
Button button = new Button(composite, SWT.NONE);
button.setBounds(96, 10, 80, 19);
button.setText("/");
Button btnn = new Button(composite, SWT.NONE);
btnn.setBounds(182, 10, 80, 19);
btnn.setText("/n");
final Button ckBase = new Button(composite, SWT.CHECK);
ckBase.setBounds(348, 11, 65, 17);
ckBase.setText("BASE64");
ckBase.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent e) {
if(ckBase.getSelection()){
if (!"".equals(txtJson.getText())) {
txtJson.setText(Base64Util.encode(txtJson.getText()));
}
}else{
if (!"".equals(txtJson.getText())) {
txtJson.setText(Base64Util.decode(txtJson.getText()));
}
}
}
public void widgetDefaultSelected(SelectionEvent arg0) {
}
});
txtJson.addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent arg0) {
}
public void keyPressed(KeyEvent e) {
if (e.stateMask == SWT.CTRL && e.keyCode == 'a') {
txtJson.selectAll();
}
}
});
TabItem tbtmNewItem = new TabItem(tabFolder, SWT.NONE);
tbtmNewItem.setText("xml");
Composite composite_1 = new Composite(tabFolder, SWT.NONE);
tbtmNewItem.setControl(composite_1);
Button btnXml = new Button(composite_1, SWT.NONE);
btnXml.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (!"".equals(text.getText())) {
try {
String xml = XmlUtil.formatXML(text.getText());
text.setText(xml);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
});
btnXml.setText("format");
btnXml.setBounds(10, 10, 80, 19);
text = new Text(composite_1, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
text.setFont(SWTResourceManager.getFont("Consolas", 11, SWT.NORMAL));
text.setBounds(10, 35, 736, 387);
text.addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent arg0) {
}
public void keyPressed(KeyEvent e) {
if (e.stateMask == SWT.CTRL && e.keyCode == 'a') {
txtMDencode.selectAll();
}
}
});
TabItem tbtmView = new TabItem(tabFolder, SWT.NONE);
tbtmView.setText("view");
Composite composite_v = new Composite(tabFolder, SWT.NONE);
tbtmView.setControl(composite_v);
Tree tree = new Tree(composite_v, SWT.BORDER);
tree.setBounds(10, 10, 736, 417);
TabItem tbtmMd = new TabItem(tabFolder, SWT.NONE);
tbtmMd.setText("MD5");
Composite composite_2 = new Composite(tabFolder, SWT.NONE);
tbtmMd.setControl(composite_2);
Label lblNewLabel_3 = new Label(composite_2, SWT.NONE);
lblNewLabel_3.setBounds(10, 10, 36, 17);
lblNewLabel_3.setText("原文:");
txtMDencode = new Text(composite_2, SWT.BORDER | SWT.WRAP);
txtMDencode.setFont(SWTResourceManager.getFont("微软雅黑", 11, SWT.NORMAL));
txtMDencode.setBounds(46, 7, 684, 240);
txtMDencode.addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent arg0) {
}
public void keyPressed(KeyEvent e) {
if (e.stateMask == SWT.CTRL && e.keyCode == 'a') {
txtMDencode.selectAll();
}
}
});
Label label = new Label(composite_2, SWT.NONE);
label.setBounds(10, 308, 36, 17);
label.setText("密文:");
txtMDdecode = new Text(composite_2, SWT.BORDER);
txtMDdecode.setBounds(46, 286, 684, 51);
txtMDdecode.setFont(SWTResourceManager.getFont("微软雅黑", 23, SWT.NORMAL));
Button btnMDencode = new Button(composite_2, SWT.NONE);
btnMDencode.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (!"".equals(txtMDencode.getText())) {
String encode = MD5Util.getMD5(txtMDencode.getText());
txtMDdecode.setText(encode);
}
}
});
btnMDencode.setToolTipText("没有密文库");
btnMDencode.setBounds(46, 253, 80, 27);
btnMDencode.setText("加密");
Button btnMDencode16 = new Button(composite_2, SWT.NONE);
btnMDencode16.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (!"".equals(txtMDencode.getText())) {
String encode = MD5Util.getMD5(txtMDencode.getText()+"123456");
txtMDdecode.setText(encode);
}
}
});
btnMDencode16.setToolTipText("没有密文库");
btnMDencode16.setText("加密(123456)");
btnMDencode16.setBounds(147, 253, 80, 27);
TabItem tbtmBase = new TabItem(tabFolder, SWT.NONE);
tbtmBase.setText("BASE64");
Composite composite_3 = new Composite(tabFolder, SWT.NONE);
tbtmBase.setControl(composite_3);
Label label_1 = new Label(composite_3, SWT.NONE);
label_1.setBounds(10, 10, 36, 17);
label_1.setText("原文:");
Label label_2 = new Label(composite_3, SWT.NONE);
label_2.setBounds(10, 218, 36, 17);
label_2.setText("密文:");
txtBASEencode = new Text(composite_3, SWT.BORDER | SWT.WRAP);
txtBASEencode.setBounds(52, 10, 694, 166);
txtBASEencode.addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent arg0) {
}
public void keyPressed(KeyEvent e) {
if (e.stateMask == SWT.CTRL && e.keyCode == 'a') {
txtBASEencode.selectAll();
}
}
});
txtBASEdecode = new Text(composite_3, SWT.BORDER | SWT.WRAP);
txtBASEdecode.setBounds(52, 215, 694, 212);
txtBASEdecode.addKeyListener(new KeyListener() {
public void keyReleased(KeyEvent arg0) {
}
public void keyPressed(KeyEvent e) {
if (e.stateMask == SWT.CTRL && e.keyCode == 'a') {
txtBASEdecode.selectAll();
}
}
});
Button btnBencode = new Button(composite_3, SWT.NONE);
btnBencode.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (!"".equals(txtBASEencode.getText())) {
String decode = Base64Util.encode(txtBASEencode.getText());
txtBASEdecode.setText(decode);
}
}
});
btnBencode.setBounds(52, 182, 80, 27);
btnBencode.setText("加密");
Button btnBdecode = new Button(composite_3, SWT.NONE);
btnBdecode.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
if (!"".equals(txtBASEdecode.getText())) {
String encode = Base64Util.decode(txtBASEdecode.getText());
txtBASEencode.setText(encode);
}
}
});
btnBdecode.setBounds(138, 182, 80, 27);
btnBdecode.setText("解密");
TabItem tbtmAes = new TabItem(tabFolder, SWT.NONE);
tbtmAes.setText("AES");
Button btnClear = new Button(shell, SWT.NONE);
btnClear.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
cmbURL.setText("");
txtPara.setText("");
}
});
btnClear.setBounds(554, 61, 33, 71);
btnClear.setText("清空");
}
}
<file_sep>/src/main/java/com/x/xjson/Base64Util.java
/**
*
* File Name: Base64Util.java
* Package Name: com.x.xijson
* Date: 2016年5月20日 上午10:29:17
*/
package com.x.xjson;
import java.io.UnsupportedEncodingException;
/**
* @author x
*
*/
public class Base64Util {
public static String decode(String s) {
if (s == null) return null;
try {
@SuppressWarnings("restriction")
byte[] b = new sun.misc.BASE64Decoder().decodeBuffer(s);
return new String(b, "UTF-8");
} catch (Exception e) {
return null;
}
}
// 编码
@SuppressWarnings("restriction")
public static String encode(String s){
if (s == null) return null;
try {
//return new sun.misc.BASE64Encoder().encode(s.getBytes("UTF-8"));
s = new sun.misc.BASE64Encoder().encode(s.getBytes("UTF-8"));
return s.replaceAll("[\\s*\t\n\r]", "");
} catch (UnsupportedEncodingException e) {
return null;
}
}
public static void main(String[] args) {
String s = "{\"FUNC\":\"GetOrRefreshVisionList\",\"SERV_CENTER_ID\":\"F2\",\"VISIONROOMINFOID\":\"a683320f-9905-4714-9767-ab6a5137e113\"}";
s = encode(s);
System.out.println(s);
}
}
|
c8ee8b0e7087e0287aeb46a3774eae9a9090f559
|
[
"Markdown",
"Java",
"Maven POM"
] | 6 |
Markdown
|
gitever/xjson
|
b4096cd584e0351cfce4505c9bfc94376bd882b1
|
244ce82eec06fd9c9f25030d039d2525cc9e679c
|
refs/heads/master
|
<repo_name>hdamber/tictactoe<file_sep>/app.js
let cells = document.querySelectorAll('.cell');
let shape = 'X'
cellCount = 0
// 8 winning combos
let wins = [
[cells[0], cells[1], cells[2]],
[cells[3], cells[4], cells[5]],
[cells[6], cells[7], cells[8]],
[cells[0], cells[3], cells[6]],
[cells[1], cells[4], cells[7]],
[cells[2], cells[5], cells[8]],
[cells[0], cells[4], cells[8]],
[cells[2], cells[4], cells[6]],
]
// switches through the 'X's and 'O's and runs and checks them to loop
for (i = 0; i < cells.length; i++) {
cells[i].addEventListener('click', cellClicked)
}
function cellClicked(cell) {
if (cell.target.textContent == '') {
cell.target.textContent = shape
checkWin();
if (shape == 'X') {
shape = 'O'
let snd = new Audio("Lightsaber Turn On-SoundBible.com-1637663395.mp3");
snd.play();
}
else { shape = 'X'
let snd = new Audio("Lightsaber Clash-SoundBible.com-203518049.mp3");
snd.play();
}
};
};
function checkWin() {
cellCount++
for (i = 0; i < wins.length; i++) {
let shapeCount = 0;
for (j = 0; j < wins[i].length; j++) {
if (wins[i][j].innerHTML == shape) {
shapeCount++
};
if (shapeCount == 3) {
alert(shape + '...may the force be with you.')
reset();
return;
}
if (cellCount == 9 && shapeCount == 3) {
alert(shape + '...may the force be with you.')
reset();
return;
}
else if (shapeCount != 3 && cellCount == 9) {
alert('Give yourself to the Dark Side.')
reset();
return;
}
};
}
}
function reset() {
for (i = 0; i < cells.length; i++) {
cells[i].innerHTML = ''
shape = 'O'
cellCount = 0
}
}
// var snd = new Audio("name");
// snd.play();
|
823f41b73263a3aa8bdf9bf86b094bee53f7a1d0
|
[
"JavaScript"
] | 1 |
JavaScript
|
hdamber/tictactoe
|
8284abff73fc8ca9cfdd955ca360e1cd062d6f35
|
7002dce4715d56f45cd0149cde7d4176faa8da25
|
refs/heads/master
|
<file_sep>function average(collection) { return _.sum(collection) / collection.length; }
function PullRequest(data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
self.createdAt = new Date(self.created_at());
self.isOpen = self.closed_at() == null;
self.closedAt = self.isOpen ? null : new Date(self.closed_at());
self.age = (self.isOpen ? new Date() : self.closedAt) - self.createdAt;
self.isOpenAtDate = function (when) {
return self.createdAt <= when && (self.isOpen || self.closedAt > when);
};
}
var msInADay = 1000 * 60 * 60 * 24,
msInAWeek = msInADay * 7,
msInAYear = msInADay * 365.25;
function SearchResults() {
var self = this;
self.totalPRCount = ko.observable(0);
self.pullRequests =
ko.mapping.fromJS([],
{
key: function(data) { return ko.utils.unwrapObservable(data.id); },
create: function(options) { return new PullRequest(options.data); }
});
self.openPullRequests = ko.pureComputed(function () {
return self.pullRequests().filter(function (pr) { return pr.isOpen; });
});
self.closedPullRequests = ko.pureComputed(function () {
return self.pullRequests().filter(function (pr) { return !pr.isOpen; });
});
self.openPRsAtDate = function(when) {
return self.pullRequests().filter(function (pr) { return pr.isOpenAtDate(when); });
};
self.pullRequestAges = function (open) {
return (open ? self.openPullRequests() : self.closedPullRequests()).map(function (pr) { return pr.age; });
};
self.averagePRAge = function (open) {
return ko.pureComputed(function () { return average(self.pullRequestAges(open)); });
};
self.minPRAge = function (open) {
return ko.pureComputed(function () { return _.min(self.pullRequestAges(open)); });
};
self.maxPRAge = function (open) {
return ko.pureComputed(function () { return _.max(self.pullRequestAges(open)); });
};
self.agesOfPRsOpenAt = function (when) {
return self.openPRsAtDate(when).map(function (pr) { return when - pr.createdAt; });
};
self.prCountByAgeInWeeks = function (open, limit) {
var map = new Array();
self.pullRequestAges(open)
.forEach(function (age) {
var weeks = Math.floor(age / msInAWeek);
map[weeks] = (map[weeks] ? map[weeks] : 0) + 1;
});
var cumulative = [];
_.range(limit).reduce(function (c, i) {
var count = c + (map[i] ? map[i] : 0);
cumulative.push(count);
return count;
}, 0);
return cumulative;
// Non-cumulative version
//return _.range(limit).map(function (weeks) { return map[weeks] ? map[weeks] : 0; });
};
function createHistory(f, limit) {
var dates = [];
var openPRCountHistory = [];
var when = new Date();
for (var week = 0; week < limit; ++week) {
dates.push(new Date(when).toLocaleDateString());
openPRCountHistory.push(f(when));
when -= msInAWeek;
}
return { labels: dates.reverse(), data: openPRCountHistory.reverse() };
};
self.openPRCountHistory = function (limit) {
return createHistory(function (when) { return self.openPRsAtDate(when).length; }, limit);
};
self.sumOfPRAgesHistory = function (limit) {
return createHistory(function (when) { return _.sum(self.agesOfPRsOpenAt(when)) / msInAYear; }, limit);
};
self.sumOfPRAges = ko.pureComputed(function () { return _.sum(self.agesOfPRsOpenAt(new Date())); });
self.jamiesDisapproval = ko.pureComputed(function() { return Math.round(9 - Math.log(self.sumOfPRAges() / 263000000)); });
self.errorMessage = ko.observable();
self.activeRequests = ko.observable(0);
self.loading = ko.pureComputed(function () { self.activeRequests() == 0; });
self.uninitialised = ko.pureComputed(function () { return self.pullRequests().length == 0; });
self.update =
function () {
var pullRequests = [];
// Function to load a page of results
function getPage(uri) {
self.activeRequests(self.activeRequests() + 1);
$.getJSON(uri, function (data, textStatus, jqXHR) {
self.totalPRCount(data.total_count);
// Get the pull requests
pullRequests = pullRequests.concat(data.items);
// Get the link to the next page of results
var nextLinkSuffix = "; rel=\"next\"";
var nextLinks = jqXHR.getResponseHeader("Link").split(",").filter(function (link) { return link.endsWith(nextLinkSuffix); });
if (nextLinks.length > 0) {
var nextLink = nextLinks[0];
nextLink = nextLink.substring(1, nextLink.length - nextLinkSuffix.length - 1);
getPage(nextLink);
return; // Don't update until read all pages
}
if (pullRequests.length != self.totalPRCount())
self.errorMessage("Couldn't get all the pull requests");
ko.mapping.fromJS(pullRequests, {}, self.pullRequests);
})
.fail(function (jqXHR, textStatus, errorThrown) {
if (jqXHR.getResponseHeader("X-RateLimit-Remaining") <= 0) {
var rateLimitReset = new Date(parseInt(jqXHR.getResponseHeader("X-RateLimit-Reset")) * 1000);
console.log("Rate limit exceeded, retrying at " + rateLimitReset.toLocaleTimeString());
setTimeout(function() { getPage(uri); }, rateLimitReset - new Date());
}
})
.always(function () { self.activeRequests(self.activeRequests() - 1); });
}
// Load the first page
getPage("https://api.github.com/search/issues?q=user%3Adiffblue+type%3Apr&per_page=100");
};
}
|
bf87edfe7ff3b28f67e1676112565f7fde98fc61
|
[
"JavaScript"
] | 1 |
JavaScript
|
rjmunro/github-dashboard
|
4dbb6df791084f61205d909d46021ee5109cc224
|
84f267020c907dd676c8a06b107f3d162a146e79
|
refs/heads/master
|
<file_sep># proyecto_algebra
ejercicio
<file_sep>
package main;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner leer = new Scanner(System.in);
double crdA=0.0;
double crdB=0.0;
double crdC =0.0;
double crdD =0.0;
double area=0.0;
double perimetro_equilatero=0.0;
double perimetro_isoceles=0.0;
double perimetro_escaleno=0.0;
double perimetro_cuadrado=0.0;
double perimetro_rectangulo=0.0;
double perimetro_rombo=0.0;
double baserectangulo=0.0;
double alturarectangulo=0.0;
double arearectangulo=0.0;
double area_rombo=0.0;
double radio=0.0;
double pi=3.1416;
double areacirculo=0.0;
double basecuadrado=0.0;
double alturacuadrado=0.0;
double areacuadrado=0.0;
double area_trapecio =0.0;
double perimetro_trapecio=0.0;
double alturatr =4.0;
double n =0.0;
double area_romboide = 0.0;
double perimetro_romboide = 0.0;
double altura_romboide = 0.0;
double area_trapezoide_1= 0.0;
double area_trapezoide_2= 0.0;
double D1= 0.0;
double perimetro_trapezoide= 0.0;
double angulo = 0.0;
double s = 0.0;
int opc;
int opcion;
int contador = -1;
int contador_equilatero = 0;
int contador_isoceles = 0;
int contador_escaleno = 0;
int contador_cuadrado = 0;
int contador_rectangulo = 0;
int contador_rombo = 0;
int contador_romboide = 0;
int contador_trapecio = 0;
int contador_trapezoide = 0;
System.out.println("----------------------------------------");
System.out.println("Sofwere de Algebra");
System.out.println("----------------------------------------");
while(true){
System.out.println(" ");
System.out.println("cuantos puntos desea ingresar?");
System.out.println("1.- 3 Puntos.");
System.out.println("2.- 4 Puntos.");
System.out.println("3.-Salir.");
System.out.println("----------------------------------------");
System.out.print("ingrese su opcion: ");
opc = leer.nextInt();
System.out.println("----------------------------------------");
contador = contador +1;
if(opc != 1 && opc != 2 && opc != 3){
System.out.println("profe, no se ponga tierno. es solo numeros. XD");
continue;
}
if(opc == 1){
System.out.println(" ");
System.out.println("---------------------------------------------");
System.out.print("Ingrese las coordenadas de la base: ");
crdA = leer.nextDouble();
System.out.println(" ");
System.out.println("---------------------------------------------");
System.out.print("Ingrese las cordenadas de la altura: ");
crdB = leer.nextDouble();
System.out.println(" ");
System.out.println("---------------------------------------------");
System.out.print("Ingrese las cordenadas de un lado x1: ");
crdC = leer.nextDouble();
area =(crdA * crdB)/2;
perimetro_equilatero = crdA *3;
if(crdA == crdC && crdA == crdB){
contador_equilatero = contador_equilatero +1;
System.out.println("-------------------------------------------------");
System.out.println("la figura ingresada es un Triangulo equilatero");
System.out.println("-------------------------------------------------");
System.out.println("");
System.out.println(" *");
System.out.println(" ***");
System.out.println(" *****");
System.out.println(" *******");
System.out.println(" *********");
System.out.println(" ***********");
System.out.println("");
System.out.println("------------------------------------------------");
System.out.println("el area del triangulo equilatero es: "+area);
System.out.println("------------------------------------------------");
System.out.println("el perimetro del triangulo equilatero es: "+perimetro_equilatero);
}else{
perimetro_isoceles = 2 * crdA + crdB;
if(crdA == crdB){
contador_isoceles = contador_isoceles +1;
System.out.println("-------------------------------------------------");
System.out.println("la figura ingresada es un Triangulo isoceles");
System.out.println("-------------------------------------------------");
System.out.println("");
System.out.println(" *");
System.out.println(" ******");
System.out.println(" ***********");
System.out.println(" **************");
System.out.println(" **************");
System.out.println(" *************");
System.out.println(" ************");
System.out.println(" ***********");
System.out.println(" **********");
System.out.println(" *********");
System.out.println(" ********");
System.out.println(" *******");
System.out.println(" ******");
System.out.println(" *****");
System.out.println(" ****");
System.out.println(" ***");
System.out.println(" **");
System.out.println(" *");
System.out.println("");
System.out.println("-------------------------------------------------");
System.out.println("el area del triangulo isoceles es: "+area);
System.out.println("-------------------------------------------------");
System.out.println("el perimetro del triangulo isoceles es: "+perimetro_isoceles);
}else{
if(crdA == crdC){
contador_isoceles = contador_isoceles +1;
System.out.println("-------------------------------------------------");
System.out.println("la figura ingresada es un Triangulo isoceles");
System.out.println("-------------------------------------------------");
System.out.println("");
System.out.println(" *");
System.out.println(" ******");
System.out.println(" ***********");
System.out.println(" **************");
System.out.println(" **************");
System.out.println(" *************");
System.out.println(" ************");
System.out.println(" ***********");
System.out.println(" **********");
System.out.println(" *********");
System.out.println(" ********");
System.out.println(" *******");
System.out.println(" ******");
System.out.println(" *****");
System.out.println(" ****");
System.out.println(" ***");
System.out.println(" **");
System.out.println(" *");
System.out.println(" ");
System.out.println("-------------------------------------------------");
System.out.println("el area del triangulo isoceles es: "+area);
System.out.println("-------------------------------------------------");
System.out.println("el perimetro del triangulo isoceles es: "+perimetro_isoceles);
}else{
perimetro_escaleno =crdA + crdB + crdC;
if(crdA != crdB && crdA != crdC){
contador_escaleno = contador_escaleno +1;
System.out.println("-------------------------------------------------");
System.out.println("la figura ingresada es un Triangulo Escaleno");
System.out.println("-------------------------------------------------");
System.out.println("");
System.out.println(" ");
System.out.println(" *");
System.out.println(" **");
System.out.println(" *****");
System.out.println(" ********");
System.out.println(" ***********");
System.out.println(" **************");
System.out.println(" ******************");
System.out.println(" *********************");
System.out.println(" ************************");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println("-------------------------------------------------");
System.out.println("el area del triangulo isoceles es: "+area);
System.out.println("-------------------------------------------------");
System.out.println("el perimetro del triangulo isoceles es: "+perimetro_escaleno);
}
}
}
}
}else {
if(opc == 2){
System.out.println(" ");
System.out.println("-----------------------------------------");
System.out.print("Ingrese las cordenadas de la base(A) : ");
crdA = leer.nextDouble();
System.out.println(" ");
System.out.println("-----------------------------------------");
System.out.print("Ingrese las cordenadas de la parte superior(B) : ");
crdB = leer.nextDouble();
System.out.println(" ");
System.out.println("-----------------------------------------");
System.out.print("Ingrese las cordenadas de parte isquierda(C) : ");
crdC = leer.nextDouble();
System.out.println(" ");
System.out.println("-----------------------------------------");
System.out.print("Ingrese las cordenadas de lado derecho(D) : ");
crdD = leer.nextDouble();
if(crdA == crdB && crdA != crdC && crdA != crdD && crdC != crdD)
if(crdA == crdC && crdB != crdD){
System.out.println(" ");
System.out.println("---------------------------------------");
System.out.println("profe, no existe esa figura.");
System.out.println("---------------------------------------");
continue;
}
perimetro_cuadrado = crdA + crdB + crdC + crdD;
if(crdA == crdB && crdA == crdC && crdA == crdD){
System.out.println(" ");
System.out.println("------------------------------------------------------");
System.out.println("las cordenadas ingresadas pueden ser de dos figuras.");
System.out.println("------------------------------------------------------");
System.out.println("1.-Cuadrado");
System.out.println("2.-Rombo");
System.out.println("--------------------");
System.out.print("que opcion desea:");
opcion = leer.nextInt();
if(opcion != 1 && opcion != 2){
System.out.println("profe. es 1 y 2");
continue;
}
if(crdA == crdB && crdA != crdC && crdA == crdD){
System.out.println("figura no existe");
continue;
}
if(opcion == 1){
areacuadrado =(crdA * crdC);
contador_cuadrado = contador_cuadrado +1;
System.out.println("---------------------------------------");
System.out.println("la figura ingresada es un cuadrado.");
System.out.println("---------------------------------------");
System.out.println(" ");
System.out.println(" * * * * * * * * * *");
System.out.println(" * * * * * * * * * *");
System.out.println(" * * * * * * * * * *");
System.out.println(" * * * * * * * * * *");
System.out.println(" * * * * * * * * * *");
System.out.println(" * * * * * * * * * *");
System.out.println(" * * * * * * * * * *");
System.out.println(" * * * * * * * * * *");
System.out.println(" * * * * * * * * * *");
System.out.println(" * * * * * * * * * *");
System.out.println(" ");
System.out.println("-------------------------------------------------");
System.out.println("el area del cuadrado es: "+areacuadrado);
System.out.println("-------------------------------------------------");
System.out.println("el perimetro del cuadrado es: "+perimetro_cuadrado);
}else{
area_rombo = crdA * crdC /2;
perimetro_rombo = crdA *4;
if(opcion == 2){
contador_rombo = contador_rombo +1;
System.out.println("---------------------------------------");
System.out.println("la figura ingresada es un Rombo.");
System.out.println("---------------------------------------");
System.out.println(" ");
System.out.println(" *");
System.out.println(" * * *");
System.out.println(" * * * * *");
System.out.println(" * * * * * * *");
System.out.println(" * * * * * * * * *");
System.out.println(" * * * * * * *");
System.out.println(" * * * * *");
System.out.println(" * * *");
System.out.println(" *");
System.out.println(" ");
System.out.println(" ");
System.out.println("-------------------------------------------------");
System.out.println("el area del rombo es: "+area_rombo);
System.out.println("-------------------------------------------------");
System.out.println("el perimetro del rombo es: "+perimetro_rombo);
}
}
}else{
perimetro_rectangulo = crdA + crdA + crdC + crdC;
arearectangulo = crdA * crdB;
if(crdA == crdB && crdC ==crdD){
System.out.println(" ");
System.out.println("------------------------------------------------------");
System.out.println("las cordenadas ingresadas pueden ser de dos figuras.");
System.out.println("------------------------------------------------------");
System.out.println("1.-Rectangulo");
System.out.println("2.-Romboide");
System.out.println("--------------------");
System.out.print("que opcion desea:");
opcion = leer.nextInt();
if(opcion == 1){
arearectangulo = crdA * crdB;
contador_rectangulo = contador_rectangulo +1;
System.out.println("---------------------------------------");
System.out.println("la figura ingresada es un Rectangulo.");
System.out.println("---------------------------------------");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" * * * * * * * * * * * * * *");
System.out.println(" * * * * * * * * * * * * * *");
System.out.println(" * * * * * * * * * * * * * *");
System.out.println(" * * * * * * * * * * * * * *");
System.out.println(" * * * * * * * * * * * * * *");
System.out.println(" * * * * * * * * * * * * * *");
System.out.println(" * * * * * * * * * * * * * *");
System.out.println(" ");
System.out.println("-------------------------------------------------");
System.out.println("el area del rectangulo es: "+arearectangulo);
System.out.println("-------------------------------------------------");
System.out.println("el perimetro del rectangulo es: "+perimetro_rectangulo);
}else{
if(opcion == 2){
area_romboide = crdA * crdB;
perimetro_romboide = crdA * 2 + crdC * 2;
altura_romboide = area_romboide / crdA;
contador_romboide = contador_romboide +1;
System.out.println("---------------------------------------");
System.out.println("la figura ingresada es un Romboide.");
System.out.println("---------------------------------------");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" * * * * * * * * * * * * * *");
System.out.println(" * | *");
System.out.println(" * | *");
System.out.println(" * | *");
System.out.println(" * | *");
System.out.println(" * h: | "+altura_romboide+" *");
System.out.println(" * * * * * * * * * * * * * *");
System.out.println(" ");
System.out.println("-------------------------------------------------");
System.out.println("el area del romboide es: "+area_romboide);
System.out.println("-------------------------------------------------");
System.out.println("el perimetro del romboide es: "+perimetro_romboide);
}
}
}else{
n= crdA - crdB/2;
alturatr = crdC *crdC -n * n;
System.out.println((double)Math.round(alturatr * 3));
area_trapecio = crdA + crdB * alturatr/2;
perimetro_trapecio= crdA + crdB + crdC*2;
if(crdC == crdD && crdA != crdB){
contador_trapecio = contador_trapecio +1;
System.out.println("-------------------------------------------------");
System.out.println("la figura ingresada es un Trapecio");
System.out.println("-------------------------------------------------");
System.out.println("");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" *******************");
System.out.println(" * | * ");
System.out.println(" *h: |"+alturatr+" *" );
System.out.println(" * | * ");
System.out.println(" ************************************ ");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println("-------------------------------------------------");
System.out.println("el area del trapecio es: "+area_trapecio );
System.out.println("-------------------------------------------------");
System.out.println("el perimetro del trapecio es: "+perimetro_trapecio);
}else{
if(crdA != crdB && crdA != crdC && crdA != crdD){
contador_trapezoide = contador_trapezoide +1;
System.out.println(" ");
System.out.println("-----------------------------------------------------------");
System.out.println("esta figua es un trapezoide pero para calcular su area");
System.out.println("debe ingresar un ángulo de 1 hasta 9");
System.out.println("-----------------------------------------------------------");
System.out.print("que opcion desea:");
angulo = leer.nextInt();
s = crdD + crdB + D1;
area_trapezoide_1 = 1/2 * crdA * crdC * angulo;
area_trapezoide_2 = s * s + crdD * crdD * s * s - crdB * crdB * s * s *D1 * D1;
D1 = crdA * crdA + crdC + crdC -2 * crdA * crdC * angulo ;
perimetro_trapezoide = crdA + crdB + crdC + crdD ;
System.out.println("-------------------------------------------------");
System.out.println("la figura ingresada es un Trapezoide");
System.out.println("-------------------------------------------------");
System.out.println("");
System.out.println(" C ");
System.out.println(" * ");
System.out.println(" * * ");
System.out.println(" D * * ");
System.out.println(" * D1 * D1:"+D1+" ");
System.out.println(" * * *");
System.out.println(" * * *");
System.out.println(" * * *" );
System.out.println(" * "+angulo+" *");
System.out.println(" **************************** ");
System.out.println(" A B ");
System.out.println(" ");
System.out.println(" ");
System.out.println("-------------------------------------------------");
System.out.println("el area 1 del trapezoide ABD es: "+area_trapezoide_1);
System.out.println("-------------------------------------------------");
System.out.println("el area 2 del trapezoide BCD es: "+area_trapezoide_2);
System.out.println("-------------------------------------------------");
System.out.println("el perimetro del trapezoide es: "+perimetro_trapezoide);
}
}
}
}
/***Rombo obj= new Rombo();
obj.rom();**/
}else {
if(opc == 3){
System.out.println("Gracias por probar el desafio (PERO ESQUE PROFEE.");
System.out.println(" ");
System.out.println("-------------------------------------------------");
System.out.println(" cantidad de triangulos equilateros : "+contador_equilatero);
System.out.println("-------------------------------------------------");
System.out.println(" cantidad de triangulos izoceles : "+contador_isoceles);
System.out.println("-------------------------------------------------");
System.out.println(" cantidad de triangulos escalenos : "+contador_escaleno);
System.out.println("-------------------------------------------------");
System.out.println(" cantidad de cuadrados : "+contador_cuadrado);
System.out.println("-------------------------------------------------");
System.out.println("cantidad de rectangulos : "+contador_rectangulo);
System.out.println("-------------------------------------------------");
System.out.println("cantidad de rombos : "+contador_rombo);
System.out.println("-------------------------------------------------");
System.out.println("cantidad de romboides "+contador_romboide);
System.out.println("-------------------------------------------------");
System.out.println("cantidad de trapecios "+contador_trapecio);
System.out.println("-------------------------------------------------");
System.out.println("cantidad de trapezoides "+contador_trapezoide);
System.out.println("-------------------------------------------------");
System.out.println(" ");
System.out.println(" ");
System.out.println("Cantidad de figuras ingresadas : "+ contador);
System.out.println("-------------------------------------------------");
break;
}
}
}
}
}
}
<file_sep>
package main;
/**
*
* @author Alvaro
*/
public class Cuadrado {
}
<file_sep>
package main;
/**
*
* @author Alvaro
*/
public class Trapezoide {
}
<file_sep>
package main;
/**
*
* @author Alvaro
*/
public class Romboide {
}
|
8afe6d0e78ee2695946469544b52b317f2bcfb22
|
[
"Markdown",
"Java"
] | 5 |
Markdown
|
ajvidal98/proyecto_algebra
|
d6a8fd504007157765cfc43909b96dfbff28266e
|
187b091865f0fb5823199598b3a0e4431375b7d2
|
refs/heads/master
|
<repo_name>skyshiro/dac_conv<file_sep>/main.c
#include <msp430.h>
//Latch port allows user to change the pin used to latch CS
void DAC_cipher(int amplitude, int latch_port);
void DAC_setup();
#define SAMPLE_MAX 50
#define DAC_CONST 4095/SAMPLE_MAX
int sample_count;
int offset = 1150; //934
int amplitude = 1150;
int m;
int DAC_flag;
int main(void)
{
int period = 10000; // in us
WDTCTL = WDTPW + WDTHOLD; // Stop WDT
WDTCTL = WDTPW + WDTHOLD; // Stop watchdog timer
P2DIR |= BIT2; // SMCLK set out to pins
P2SEL |= BIT2;
P7DIR |= BIT4+BIT7; // MCLK set out to pins
P7SEL |= BIT7;
_BIS_SR(GIE);
DAC_setup();
TA0CCTL0 = CCIE; // CCR0 interrupt enabled
TA0CTL = TASSEL_2 + MC_1 + TAIE; // SMCLK, up mode, 1 MHz timer clk,
//Timer resoultion = T_period/(MAX_samples*T_clk)
//For 1 us clock and T_period in us = period/SAMPLE_MAX
TA0CCR0 = period/SAMPLE_MAX;
sample_count = 0;
DAC_flag = 0;
while(1)
{
//DAC_flag is used to determine time to change value of DAC
if(DAC_flag)
{
DAC_cipher(DAC_CONST*sample_count, BIT0);
sample_count++;
if(sample_count == SAMPLE_MAX)
{
sample_count = 0;
}
DAC_flag = 0;
}
}
}
// Timer A0 interrupt service routine
// DAC_flag is raised in ISR to change DAC value
#pragma vector=TIMER0_A0_VECTOR
__interrupt void Timer_A (void)
{
//int timerVal = TAR;
TA0CTL &= ~TAIFG;
DAC_flag = 1;
}
void DAC_setup()
{
P2DIR |= BIT0; // Will use P2.0 to activate /CE on the DAC
P3SEL = BIT0 + BIT2; // + BIT4; // SDI on P3.0 and SCLK on P3.2
UCB0CTL0 |= UCCKPL + UCMSB + UCMST + /* UCMODE_2 */ + UCSYNC;
UCB0CTL1 |= UCSSEL_2; // UCB0 will use SMCLK as the basis for
//Divides UCB0 clk, I think @ 4 MHz CPU clk it should be fine
//UCB0BR0 |= 0x10; // (low divider byte)
//UCB0BR1 |= 0x00; // (high divider byte)
UCB0CTL1 &= ~UCSWRST; // **Initialize USCI state machine**
}
void DAC_cipher(int amplitude, int latch_port)
{
int DAC_code;
DAC_code = (0x3000)|(amplitude & 0xFFF); //Gain to 1 and DAC on
P2OUT &= ~latch_port; //Lower CS pin low
//send first 8 bits of code
UCB0TXBUF = (DAC_code >> 8);
//wait for code to be sent
while(!(UCTXIFG & UCB0IFG));
//send last 8 bits of code
UCB0TXBUF = (char)(DAC_code & 0xFF);
//wait for code to be sent
while(!(UCTXIFG & UCB0IFG));
//wait until latch
_delay_cycles(1);
//raise CS pin
P2OUT |= latch_port;
return;
}
|
d01d2a650263c96120647c8bf70ea5b803944359
|
[
"C"
] | 1 |
C
|
skyshiro/dac_conv
|
b2298ba781e87645ebd0d9332c30015b0e9df945
|
42f64bceade485ed76676bcc60109192716f5e6c
|
refs/heads/master
|
<file_sep>import cv2 as cv
import numpy as np
cap = cv.VideoCapture(0)
if cap.isOpened():
ret, frame = cap.read()
else:
ret = False
ret, frame1 = cap.read()
ret, frame2 = cap.read()
while ret:
d = cv.absdiff(frame1, frame2)
grey = cv.cvtColor(d, cv.COLOR_BGR2GRAY)
blur = cv.GaussianBlur(grey, (5, 5), 0)
ret, th = cv.threshold( blur, 20, 255, cv.THRESH_BINARY)
dilated = cv.dilate(th, np.ones((3, 3), np.uint8), iterations=1 )
eroded = cv.erode(dilated, np.ones((3, 3), np.uint8), iterations=1 )
img, c, h = cv.findContours(eroded, cv.RETR_TREE, cv.CHAIN_APPROX_NONE)
cv.drawContours(frame1, c, -1, (0, 255, 0), 2)
cv.imshow("Output", frame1)
if cv.waitKey(1) == 27:
break
frame1 = frame2
ret, frame2 = cap.read()
cv.destroyAllWindows()
cap.release()
|
df513dde8ecc842b4823c460c7af18b768adfd97
|
[
"Python"
] | 1 |
Python
|
vivekarora2000/Intruder-Alert-System
|
d474a94c92a86dfba5d405fcf6e7226a94d8b6a6
|
55649e02f3e02634627a1a61ce6a6e2abce7ccfc
|
refs/heads/master
|
<file_sep>nwchem-tce-triples-kernels
==========================
NWChem TCE CCSD(T) loop-driven kernels for performance optimization experiments
<file_sep>#include <math.h>
#ifdef _OPENMP
#include <omp.h>
#else
#include "fake-omp.h"
#endif
#include "safemalloc.h"
#include "ccsd_t_kernels.h"
double dger_gflops(int m, int n);
double dgemm_gflops(int m, int n, int k);
void rand_array(long long n, double * a)
{
#pragma omp parallel for schedule(static)
for (long long i=0; i<n; i++)
a[i] = 1.0 - 2*(double)rand()/(double)RAND_MAX;
return;
}
void zero_array(long long n, double * a)
{
#pragma omp parallel for schedule(static)
for (long long i=0; i<n; i++)
a[i] = 0.0;
return;
}
void copy_array(long long n, double * a, double * b)
{
#pragma omp parallel for schedule(static)
for (long long i=0; i<n; i++)
b[i] = a[i];
return;
}
double norm_array(long long n, const double * a)
{
double norm = 0.0;
for (long long i=0; i<n; i++)
norm += a[i]*a[i];
return norm;
}
double diff_array(long long n, const double * a, const double * b)
{
double diff = 0.0;
for (long long i=0; i<n; i++)
diff += fabs(a[i]-b[i]);
return diff;
}
int main(int argc, char * argv[])
{
int tilesize = ((argc>1) ? atoi(argv[1]) : 16);
printf("testing NWChem CCSD(T) kernels on %d threads with tilesize %d \n", omp_get_max_threads(), tilesize);
long long tile2 = tilesize*tilesize;
long long tile4 = tile2*tile2;
long long tile6 = tile4*tile2;
long long tile7 = tile6*tilesize;
double eff_peak = -9999.9;
/* approximate achievable peak by
* T3(ijk,abc) = T1(i,j)*V(k,abc) */
eff_peak = dger_gflops(tilesize*tilesize,
tilesize*tilesize*tilesize*tilesize);
printf("DGER gigaflop/s of your processor is %lf \n", eff_peak);
/* approximate achievable peak by
* T3(ijk,abc) = T2(ijk,l)*V(l,abc) */
eff_peak = dgemm_gflops(tilesize*tilesize*tilesize,
tilesize*tilesize*tilesize,
tilesize);
printf("DGEMM gigaflop/s of your processor is %lf \n", eff_peak);
fflush(stdout);
double tt0, tt1, ttt0, ttt1, dt;
/* reference */
double * t1 = safemalloc( tile2*sizeof(double) );
double * t2 = safemalloc( tile4*sizeof(double) );
double * v2 = safemalloc( tile4*sizeof(double) );
double * t3r = safemalloc( tile6*sizeof(double) );
double * t3o = safemalloc( tile6*sizeof(double) );
double * t3c = safemalloc( tile6*sizeof(double) );
tt0 = omp_get_wtime();
rand_array(tile2, t1);
rand_array(tile4, t2);
rand_array(tile4, v2);
tt1 = omp_get_wtime();
printf("randomized initialization took %lf seconds \n", tt1-tt0);
printf("\nSTARTING FORTRAN REFERENCE KERNELS \n");
fflush(stdout);
for (int i=0; i<2; i++)
{
long long totalflops = 0;
zero_array(tile6, t3r);
ttt0 = omp_get_wtime();
#ifdef DO_S1
tt0 = omp_get_wtime();
ref_sd_t_s1_1_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_1_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
ref_sd_t_s1_2_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_2_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
ref_sd_t_s1_3_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_3_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
ref_sd_t_s1_4_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_4_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
ref_sd_t_s1_5_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_5_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
ref_sd_t_s1_6_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_6_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
ref_sd_t_s1_7_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_7_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
ref_sd_t_s1_8_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_8_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
ref_sd_t_s1_9_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_9_", dt, (2e-9*tile6)/dt );
totalflops = 2*9*tile6;
#endif
#ifdef DO_D1
tt0 = omp_get_wtime();
ref_sd_t_d1_1_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_1_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
ref_sd_t_d1_2_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_2_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
ref_sd_t_d1_3_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_3_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
ref_sd_t_d1_4_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_4_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
ref_sd_t_d1_5_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_5_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
ref_sd_t_d1_6_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_6_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
ref_sd_t_d1_7_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_7_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
ref_sd_t_d1_8_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_8_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
ref_sd_t_d1_9_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_9_", dt, (2e-9*tile7)/dt );
totalflops = 2*9*tile7;
#endif
#ifdef DO_D2
tt0 = omp_get_wtime();
ref_sd_t_d2_1_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_1_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
ref_sd_t_d2_2_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_2_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
ref_sd_t_d2_3_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_3_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
ref_sd_t_d2_4_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_4_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
ref_sd_t_d2_5_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_5_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
ref_sd_t_d2_6_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_6_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
ref_sd_t_d2_7_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_7_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
ref_sd_t_d2_8_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_8_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
ref_sd_t_d2_9_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3r, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_9_", dt, (2e-9*tile7)/dt );
totalflops = 2*9*tile7;
#endif
ttt1 = omp_get_wtime();
dt = ttt1-ttt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "total", dt, (1e-9*totalflops)/dt );
fflush(stdout);
}
printf("\nSTARTING FORTRAN OPENMP KERNELS \n");
fflush(stdout);
for (int i=0; i<2; i++)
{
long long totalflops = 0;
zero_array(tile6, t3o);
ttt0 = omp_get_wtime();
#ifdef DO_S1
tt0 = omp_get_wtime();
omp_sd_t_s1_1_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_1_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
omp_sd_t_s1_2_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_2_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
omp_sd_t_s1_3_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_3_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
omp_sd_t_s1_4_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_4_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
omp_sd_t_s1_5_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_5_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
omp_sd_t_s1_6_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_6_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
omp_sd_t_s1_7_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_7_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
omp_sd_t_s1_8_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_8_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
omp_sd_t_s1_9_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_9_", dt, (2e-9*tile6)/dt );
totalflops = 2*9*tile6;
#endif
#ifdef DO_D1
tt0 = omp_get_wtime();
omp_sd_t_d1_1_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_1_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
omp_sd_t_d1_2_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_2_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
omp_sd_t_d1_3_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_3_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
omp_sd_t_d1_4_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_4_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
omp_sd_t_d1_5_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_5_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
omp_sd_t_d1_6_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_6_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
omp_sd_t_d1_7_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_7_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
omp_sd_t_d1_8_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_8_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
omp_sd_t_d1_9_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_9_", dt, (2e-9*tile7)/dt );
totalflops = 2*9*tile7;
#endif
#ifdef DO_D2
tt0 = omp_get_wtime();
omp_sd_t_d2_1_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_1_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
omp_sd_t_d2_2_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_2_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
omp_sd_t_d2_3_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_3_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
omp_sd_t_d2_4_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_4_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
omp_sd_t_d2_5_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_5_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
omp_sd_t_d2_6_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_6_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
omp_sd_t_d2_7_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_7_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
omp_sd_t_d2_8_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_8_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
omp_sd_t_d2_9_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3o, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_9_", dt, (2e-9*tile7)/dt );
totalflops = 2*9*tile7;
#endif
ttt1 = omp_get_wtime();
dt = ttt1-ttt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "total", dt, (1e-9*totalflops)/dt );
fflush(stdout);
}
#if DO_C_KERNELS
printf("\nSTARTING C99 KERNELS \n");
fflush(stdout);
for (int i=0; i<2; i++)
{
long long totalflops = 0;
zero_array(tile6, t3c);
ttt0 = omp_get_wtime();
#ifdef DO_S1
tt0 = omp_get_wtime();
f2c_sd_t_s1_1_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_1_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_s1_2_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_2_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_s1_3_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_3_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_s1_4_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_4_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_s1_5_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_5_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_s1_6_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_6_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_s1_7_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_7_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_s1_8_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_8_", dt, (2e-9*tile6)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_s1_9_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t1, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_s1_9_", dt, (2e-9*tile6)/dt );
totalflops = 2*9*tile6;
#endif
#ifdef DO_D1
tt0 = omp_get_wtime();
f2c_sd_t_d1_1_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_1_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_d1_2_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_2_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_d1_3_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_3_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_d1_4_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_4_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_d1_5_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_5_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_d1_6_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_6_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_d1_7_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_7_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_d1_8_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_8_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_d1_9_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d1_9_", dt, (2e-9*tile7)/dt );
totalflops = 2*9*tile7;
#endif
#ifdef DO_D2
tt0 = omp_get_wtime();
f2c_sd_t_d2_1_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_1_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_d2_2_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_2_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_d2_3_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_3_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_d2_4_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_4_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_d2_5_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_5_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_d2_6_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_6_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_d2_7_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_7_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_d2_8_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_8_", dt, (2e-9*tile7)/dt );
tt0 = omp_get_wtime();
f2c_sd_t_d2_9_(&tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, &tilesize, t3c, t2, v2);
tt1 = omp_get_wtime();
dt = tt1-tt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "sd_t_d2_9_", dt, (2e-9*tile7)/dt );
totalflops = 2*9*tile7;
#endif
ttt1 = omp_get_wtime();
dt = ttt1-ttt0;
printf("%d: %s time = %lf seconds gigaflop/s = %lf \n", i, "total", dt, (1e-9*totalflops)/dt );
fflush(stdout);
}
#endif // DO_C_KERNELS
printf("\n");
double e1 = diff_array(tile2, t1, t1);
double e2 = diff_array(tile4, t2, t2);
double e3 = diff_array(tile4, v2, v2);
double e4 = diff_array(tile6, t3r, t3o);
#if DO_C_KERNELS
double e5 = diff_array(tile6, t3r, t3c);
#else
double e5 = 0.0;
#endif // DO_C_KERNELS
printf("differences: t1 = %lf, t2 = %lf, v2 = %lf, t3o = %30.15lf, t3c = %30.15lf \n", e1, e2, e3, e4, e5);
if ( fabs(e4)>1.e-7 || fabs(e5)>1.e-7) {
printf("ERROR!!!\n");
exit(1);
}
double n1 = norm_array(tile2, t1);
double n2 = norm_array(tile4, t2);
double n3 = norm_array(tile4, v2);
double n4r = norm_array(tile6, t3r);
double n4o = norm_array(tile6, t3o);
double n4c = norm_array(tile6, t3c);
printf("norm: t1 = %lf, t2 = %lf, v2 = %lf, t3 = %lf, %lf, %lf \n", n1, n2, n3, n4r, n4o, n4c);
free(t3c);
free(t3o);
free(t3r);
free(v2);
free(t2);
free(t1);
printf("ALL DONE \n");
fflush(stdout);
return 0;
}
<file_sep>#include <assert.h>
#include <sys/time.h>
static int omp_get_max_threads(void)
{
return 1;
}
static double omp_get_wtime(void)
{
struct timeval tp;
int rc = gettimeofday(&tp, NULL);
assert(rc==0);
double t = tp.tv_sec + tp.tv_usec * 1.e-6;
return t;
}
<file_sep>#include "ccsd_t_kernels_ref.h"
#include "ccsd_t_kernels_omp.h"
#include "ccsd_t_kernels_f2c.h"
<file_sep>#include <math.h>
#ifdef _OPENMP
#include <omp.h>
#else
#include "fake-omp.h"
#endif
#include "safemalloc.h"
void dgemm_(char* , char* ,int* , int* , int* , double* , double* , int* , double* , int* , double* , double* , int* );
void dger_(int* m, int* n, double* alpha, double* x, int* incx, double* y, int* incy, double* a, int* lda);
/* number of test repititions */
const int nr = 10;
double dgemm_gflops(int m, int n, int k)
{
#ifdef DEBUG
printf("testing DGEMM on %d threads with (m,n,k) = (%d,%d,%d) \n", omp_get_max_threads(), m, n, k);
fflush(stdout);
#endif
int rowc = m;
int rowa = m;
int cola = k;
int rowb = k;
int colb = n;
int colc = n;
long mn = m*n;
long mk = m*k;
long kn = k*n;
double * a = safemalloc( mk*sizeof(double) );
double * b = safemalloc( kn*sizeof(double) );
double * c = safemalloc( mn*sizeof(double) );
#pragma omp parallel
{
double denom = 2.0/(double)RAND_MAX;
#pragma omp for
for (long i=0; i<mk; i++)
a[i] = 1.0 - denom*(double)rand();
#pragma omp for
for (long i=0; i<kn; i++)
b[i] = 1.0 - denom*(double)rand();
#pragma omp for
for (long i=0; i<mn; i++)
c[i] = 1.0 - denom*(double)rand();
}
char notrans = 'n';
double alpha = 1.0;
double beta = 1.0;
double tt0 = omp_get_wtime();
for (int r = 0; r<nr; r++)
dgemm_(¬rans, ¬rans, &rowa, &colb, &cola,
&alpha, a, &rowa, b, &rowb,
&beta, c, &rowc);
double tt1 = omp_get_wtime();
unsigned long long mnk = m*n*k;
double dt = (tt1-tt0)/nr;
double result = (2.e-9*mnk/dt);
#ifdef DEBUG
printf("DGEMM(%c,%c,m=%d,n=%d,k=%d,alpha=%lf,beta=%lf) took %lf seconds, GF/s = %lf \n",
notrans, notrans, m, n, k, alpha, beta, dt, result);
fflush(stdout);
#endif
free(c);
free(b);
free(a);
return result;
}
double dger_gflops(int m, int n)
{
#ifdef DEBUG
printf("testing DGER on %d threads with (m,n) = (%d,%d) \n", omp_get_max_threads(), m, n);
fflush(stdout);
#endif
long mn = m*n;
double * x = safemalloc( m*sizeof(double) );
double * y = safemalloc( n*sizeof(double) );
double * a = safemalloc( mn*sizeof(double) );
#pragma omp parallel
{
double denom = 2.0/(double)RAND_MAX;
#pragma omp for
for (long i=0; i<m; i++)
x[i] = 1.0 - denom*(double)rand();
#pragma omp for
for (long i=0; i<n; i++)
y[i] = 1.0 - denom*(double)rand();
#pragma omp for
for (long i=0; i<mn; i++)
a[i] = 1.0 - denom*(double)rand();
}
int inc = 1;
double alpha = 1.0;
double tt0 = omp_get_wtime();
for (int r = 0; r<nr; r++)
dger_(&m, &n, &alpha, x, &inc, y, &inc, a, &m);
double tt1 = omp_get_wtime();
double dt = (tt1-tt0)/nr;
double result = (2.e-9*mn/dt);
#ifdef DEBUG
printf("DGER(m=%d,n=%d,alpha=%lf) took %lf seconds, GF/s = %lf \n",
m, n, alpha, dt, result);
fflush(stdout);
#endif
free(a);
free(y);
free(x);
return result;
}
<file_sep>ACTIVE = -DDO_S1 -DDO_D1 -DDO_D2 -DDO_C_KERNELS
ifeq ($(TARGET),MAC-CLANG)
CC = clang
FC = gfortran
OPT = -O3 -march=native -mno-avx
CFLAGS = $(OPT) -std=c99 $(ACTIVE)
FFLAGS = $(OPT)
CFLAGS += -DFORTRAN_INTEGER_SIZE=4
LD = clang -L/usr/local/Cellar/gfortran/4.8.2/gfortran/lib
LDFLAGS = $(CFLAGS)
LIBS = -framework Accelerate
endif
ifeq ($(TARGET),MAC)
CC = gcc
FC = gfortran
OPT = -O3 -fopenmp -march=native -mno-avx
CFLAGS = $(OPT) -std=c99 $(ACTIVE)
FFLAGS = $(OPT)
CFLAGS += -DFORTRAN_INTEGER_SIZE=4
LD = clang -L/usr/local/Cellar/gfortran/4.8.2/gfortran/lib
LDFLAGS = $(CFLAGS)
LIBS = -framework Accelerate
endif
ifeq ($(TARGET),INTEL)
# INTEL WORKSTATION (protos.mcs.anl.gov)
CC = icc
FC = ifort
OPT = -O3 -openmp -fno-alias -mavx -multiple-processes=8
ASM = -S -fsource-asm -fcode-asm
REPORT = -guide -parallel
REPORT = -vec-report2 -opt-report2
#TARGET_FLAGS = -mmic
CFLAGS = $(OPT) -std=c99 $(TARGET_FLAGS) $(ACTIVE) $(REPORT)
FFLAGS = $(OPT) $(TARGET_FLAGS) $(REPORT) $(GUIDE)
CFLAGS += -DFORTRAN_INTEGER_SIZE=4
LD = $(CC)
LDFLAGS = $(CFLAGS)
LIBS = -mkl=parallel
endif
TESTS := test_ccsd_t.x
OBJECTS := ccsd_t_kernels_omp.o ccsd_t_kernels_ref.o ccsd_t_kernels_f2c.o blas_flops.o
HEADERS := ccsd_t_kernels_omp.h ccsd_t_kernels_ref.h ccsd_t_kernels_f2c.h safemalloc.h
all: $(TESTS)
%.x: %.o $(OBJECTS)
$(LD) $(LDFLAGS) $< $(OBJECTS) $(LIBS) -o $@
%.o: %.c $(HEADERS)
$(CC) $(CFLAGS) -c $< -o $@
%.o: %.f
$(FC) $(FFLAGS) -c $< -o $@
%.o: %.F
$(FC) $(FFLAGS) -c $< -o $@
%.s: %.c $(HEADERS)
$(CC) $(CFLAGS) $(ASM) -c $< -o $@
%.s: %.f
$(FC) $(FFLAGS) $(ASM) -c $< -o $@
clean:
$(RM) $(RMFLAGS) *.o
realclean: clean
$(RM) $(RMFLAGS) $(TESTS)
<file_sep>#ifndef SAFEMALLOC_H
#define SAFEMALLOC_H
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>
int posix_memalign(void **memptr, size_t alignment, size_t size);
#define ALIGNMENT 64
//void * safemalloc(size_t n);
static void * safemalloc(size_t n)
{
int rc = -1;
void * ptr = NULL;
rc = posix_memalign( &ptr, ALIGNMENT, n);
if ( ptr==NULL || rc!=0 )
{
fprintf( stderr , "%ld bytes could not be allocated \n" , (long)n );
exit(1);
}
return ptr;
}
#endif // SAFEMALLOC_H
|
e9415993ac07dc01eb4e51063116b542a54ec7a7
|
[
"Markdown",
"C",
"Makefile"
] | 7 |
Markdown
|
axelyamel/nwchem-tce-triples-kernels
|
9b172bb882d25e6ebf105d96f16656d0afef6460
|
257c46ce8395ae0ba4d85c8556c55c90f063a6eb
|
refs/heads/master
|
<repo_name>viperauter/vim<file_sep>/upgradClang.sh
#!/bin/sh
wget http://llvm.org/releases/3.8.0/llvm-3.8.0.src.tar.xz
wget http://llvm.org/releases/3.8.0/cfe-3.8.0.src.tar.xz
wget http://llvm.org/releases/3.8.0/compiler-rt-3.8.0.src.tar.xz
tar xf llvm-3.8.0.src.tar.xz
mv llvm-3.8.0.src llvm
cp compiler-rt-3.8.0.src.tar.xz ./llvm/projects
cp cfe-3.8.0.src.tar.xz ./llvm/tools
cd ./llvm/tools
tar xf cfe-3.8.0.src.tar.xz
mv cfe-3.8.0.src clang
cd ../projects
tar xf compiler-rt-3.8.0.src.tar.xz
mv compiler-rt-3.8.0.src compiler-rt
cd ../../
mkdir build
cd build
../llvm/configure --enable-optimized --enable-targets=host-only CC=gcc CXX=g++
make -j8
make install
clang --version
cp ./build/Release+Asserts/lib/libclang.so ~/.vim/bundle/YouCompleteMe/third_party/ycmd/libclang.so.3.8
<file_sep>/autoconfig.sh
#!/bin/sh
cdir=`pwd`
#检查是否有git环境
command -v git >/dev/null 2>&1 || { echo "require git but it's not installed. Aborting." >&2; exit 1; }
command -v ctags >/dev/null 2>&1 || { echo "require ctags but it's not installed. Aborting." >&2; exit 1; }
#编译需要的vim源码git地址,git上面的7.4.xxx版本不能用
#git url(wget):https://github.com/vim/vim/archive/v7.4.144.tar.gz
#ver=7.4.143
#vimver=v$ver.tar.gz
#sourceurl=https://github.com/vim/vim/archive/$vimver
#if [ ! -f $vimver ];then
# echo "download the vim source"
# #wget https://github.com/vim/vim/archive/v7.4.144.tar.gz
# wget $sourceurl -O $vimver
#fi
#
#tar -xzvf $vimver
#mv "vim-$ver" vim74
#编译需要的vim源码git地址ftp://ftp.vim.org/pub/vim/unix/vim-7.4.tar.bz2
if [ ! -f vim-7.4.tar.bz2 ];then
echo "download the vim source"
wget ftp://ftp.vim.org/pub/vim/unix/vim-7.4.tar.bz2
fi
tar -xjvf vim-7.4.tar.bz2
#编译需要的vimgdb地址
#git url(wget):https://codeload.github.com/larrupingpig/vimgdb-for-vim7.4/zip/master
if [ ! -f vimgdb-for-vim7.4-master.zip ];then
echo "download the vimgdm source"
wget https://codeload.github.com/larrupingpig/vimgdb-for-vim7.4/zip/master -O vimgdb-for-vim7.4-master.zip
fi
unzip vimgdb-for-vim7.4-master.zip
#打补丁
patch -p0 < vimgdb-for-vim7.4-master/vim74.patch
echo y|sudo apt-get install python-dev
echo y|sudo apt-get install libxt-dev
cd $cdir/vim74/src
sed -i "s/BINDIR = \/opt\/bin/BINDIR = \/usr\/bin/" Makefile
sed -i "s/MANDIR = \/opt\/share\/man/MANDIR = \/usr\/share\/man\/man1/" Makefile
sed -i "s/DATADIR = \/opt\/share/DATADIR = \/usr\/share\/vim/" Makefile
echo y|sudo apt-get install libncurses5-dev
./configure --enable-gdb --prefix=/usr/local/vim74 --enable-multibyte --enable-fontset --enable-xim --enable-gui=auto --enable-pythoninterp=yes --enable-rubyinterp=dynamic --enable-rubyinterp --enable-perlinterp --enable-cscope --enable-sniff --with-x --with-features=huge --enable-luainterp=dynami --with-python-config-dir=/usr/lib/python2.7/config --with-feature=big
if [ $? -eq 0 ];then
echo "make vim source"
make CFLAGS="-O2 -D_FORTIFY_SOURCE=1"
else
echo "config the vim option error"
fi
make install
cp -rf $cdir/vimgdb-for-vim7.4-master/vimgdb_runtime/* ~/.vim
echo "vim compile success"
cd /usr/share/vim/vim/vim74/doc/
echo ":helptags ."|vim
#安装bundle
if [ ! -f ~/.vim/bundle/vundle/autoload/vundle.vim ];then
echo "download bundle\n"
git clone https://github.com/gmarik/vundle.git ~/.vim/bundle/vundle;
fi
cd $cdir
#生成vim默认配置加载文件.vimrc
vimconfname=.vimrc
vimloadbundle=.vimrc.bundles.local
if [ -f $vimconfname ];then
rm -rf ./$vimconfname
fi
touch $vimconfname
echo "if &compatible" >> $vimconfname
echo " set nocompatible" >> $vimconfname
echo "end" >> $vimconfname
echo "filetype off" >> $vimconfname
"echo "set rtp+=~/.vim/bundle/vundle/" >> $vimconfname
"echo "call vundle#rc()" >> $vimconfname
"echo "\" Let Vundle manage Vundle" >> $vimconfname
"echo "Bundle 'gmarik/vundle'" >> $vimconfname
echo "if filereadable(expand(\"~/.vimrc.bundles.local\"))" >> $vimconfname
echo ' source ~/.vimrc.bundles.local' >> $vimconfname
echo "endif" >> $vimconfname
echo "filetype on" >> $vimconfname
echo "set previewheight=10" >>$vimconfname
echo "run macros/gdb_mappings.vim" >>$vimconfname
echo "set asm=0" >>$vimconfname
echo "set gdbprg=gdb" >>$vimconfname
echo "set splitbelow" >>$vimconfname
echo "set splitright" >>$vimconfname
if [ -f ~/$vimconfname ];then
mv ~/.vimrc ~/$".vimrc.$(date +"%Y%m%d%I%M%S").bak"
fi
cp ./$vimconfname ~/
#vim的配置文件,使用git中use_vim_as_ide项目配置[https://github.com/yangyangwithgnu/use_vim_as_ide]
#https://codeload.github.com/yangyangwithgnu/use_vim_as_ide/zip/master
if [ ! -f use_vim_as_ide-master.zip ];then
echo "download the vim config file\n"
wget https://codeload.github.com/yangyangwithgnu/use_vim_as_ide/zip/master -O use_vim_as_ide-master.zip
fi
unzip use_vim_as_ide-master.zip
cd $cdir/use_vim_as_ide-master/
sed -i "s/^colorscheme solarized/\"colorscheme solarized/" .vimrc
sed -i "s/set background=dark/set background=light/" .vimrc
sed -i "s/^\"colorscheme phd/colorscheme phd/" .vimrc
cp .vimrc ~/$vimloadbundle
cp README.md ./../
#启动vim安装插件
vim +PluginInstall +qall
#重新配置ycm,从git上下载ubuntu-fix版本
rm -rf ~/.vim/bundle/YouCompleteMe
cd ~/.vim/bundle/
git clone https://git.oschina.net/viperauter/ubuntu-fix.git
mv ubuntu-fix YouCompleteMe
cd ~/.vim/bundle/YouCompleteMe/
command -v cmake>/dev/null 2>&1 || { echo y|apt-get install cmake }
git submodule update --init --recursive
./install.py --clang-completer
echo "auto config vim env success"
#打开README
vim README.md
<file_sep>/upgradgcc.sh
#!/bin/sh
add-apt-repository ppa:ubuntu-toolchain-r/test
apt-get update
apt-get install gcc-4.9 g++-4.9
updatedb && ldconfig
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.6 46
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.9 49
update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.6 46
update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-4.9 49
gcc --version
|
63dfa6baadf33bbd030ca7451757596a605ba303
|
[
"Shell"
] | 3 |
Shell
|
viperauter/vim
|
763ed2932e571ae8527d57c8d8da03fc415953d9
|
c20d027515b9e1ddb21ea6b4a4953c6b2e980501
|
refs/heads/master
|
<repo_name>nicollevalladares/XO-FrontEnd<file_sep>/config/server.js
const serve = {
mainServe: 'http://localhost:3333'
}
export default serve;
|
ff2b961fcc420ad5a1c2b1ed641af4d91fd9d272
|
[
"JavaScript"
] | 1 |
JavaScript
|
nicollevalladares/XO-FrontEnd
|
72c28303bff3be71f967bf20aa1186955d407731
|
51f9a259bf28f8517eb7e7168f690c620b89e13c
|
refs/heads/master
|
<file_sep>#!/bin/bash
wp i18n make-pot ./stripe-payments/ --exclude="includes/plugin-update-checker,/includes/stripe"<file_sep># stripe-payments
Stripe Payments Plugin for WordPress
<file_sep>#!/bin/bash
#regenerate .pot file
sh ./genpot.sh
#minify and combine css
cat ./stripe-payments/public/views/templates/default/pure.css ./stripe-payments/public/views/templates/default/pp-style.css | cleancss -o ./stripe-payments/public/views/templates/default/pp-combined.min.css --s0
cat ./stripe-payments/public/views/templates/default/pp-inline-head.css | cleancss -o ./stripe-payments/public/views/templates/default/pp-inline-head.min.css --s0
#minify and combine js
cat ./stripe-payments/public/assets/js/add-ons/tax-variations.js ./stripe-payments/public/assets/js/md5.min.js ./stripe-payments/public/assets/js/pp-handler.js | uglifyjs - -c -m -o ./stripe-payments/public/assets/js/pp-handler.min.js
stable=$(grep "Stable tag:" ./stripe-payments/readme.txt)
version=$(echo $stable | sed 's/Stable tag://' | xargs)
rm -f ./stripe-payments_$version.zip
zip -r -q -J -X ./stripe-payments_$version.zip ./stripe-payments/ -x *_debug_log.txt
|
03a8ea3449e156a59cb73ac1fd1f4f8308d4b67c
|
[
"Markdown",
"Shell"
] | 3 |
Shell
|
Arsenal21/stripe-payments
|
f9d64a93e3a1f25d61848ccaaf54f4943c334813
|
a218036c987a2026f3d3008aa9ab2c63e9f7783c
|
refs/heads/master
|
<repo_name>Liangzg/GEX_1.X<file_sep>/Assets/Editor/SceneManagerEditor/Strategy/PreDirectionStrategy.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// 描述:逐目录策略
/// <para>创建时间:2016-06-24</para>
/// </summary>
public class PreDirectionStrategy : IStrategy {
public void BeginProcess(BuildConfig buildConfig)
{
string absolutionPath = Path.Combine(Application.dataPath, buildConfig.InputDir);
string[] findFile = buildConfig.FileSuffixs.Split('|');
//查找打包输入路径下的根目录列表
string[] dirArr = Directory.GetDirectories(absolutionPath, "*", SearchOption.TopDirectoryOnly);
foreach (string subDir in dirArr)
{
DirectoryInfo di = new DirectoryInfo(subDir);
//将文件夹的名字做为Bundle名称
AssetBundleUtil.MulInOneBundle(di.Name , buildConfig.AssetType , subDir , findFile , buildConfig.OptionSerach);
}
}
public void EndProcess(BuildConfig buildConfig)
{
Debugger.Log("<<PreDirection>> End ! build config name is " + buildConfig.BundleName);
}
}
<file_sep>/Assets/GameScript/Lua/Engines/events.lua
--[[
Auth:LiangZG
like Unity Brocast Event System in lua.
]]
local EventLib = require "eventlib"
local Event = class("Event")
function Event:ctor()
self.events = {}
end
function Event:AddListener(event,handler)
if not event or type(event) ~= "string" then
error("event parameter in addlistener function has to be string, " .. type(event) .. " not right.")
end
if not handler or type(handler) ~= "function" then
error("handler parameter in addlistener function has to be function, " .. type(handler) .. " not right")
end
if not self.events[event] then
--create the Event with name
self.events[event] = EventLib:new(event)
end
--conn this handler
self.events[event]:connect(handler)
--print("add event : " .. event)
end
--广播事件
function Event:Brocast(event,...)
if not self.events[event] then
--error("brocast " .. event .. " has no event.")
return false
else
self.events[event]:fire(...)
end
return true
end
--删除指定指定
function Event:RemoveListener(event,handler)
if not self.events[event] then
--error("remove " .. event .. " has no event.")
return
else
self.events[event]:disconnect(handler)
end
end
--清空事件列表
function Event:Clear()
for k , v in pairs(self.events) do
v:DisconnectAll()
end
end
return Event<file_sep>/Assets/Libs/LuaDataBind/Foundation/Setter/Setter.cs
using UnityEngine;
namespace LuaDataBind
{
public abstract class Setter : MonoBehaviour , IBinding
{
public string path;
/// <summary>
/// Type of data binding.
/// </summary>
public DataBindingType Type;
[HideInInspector]
public DataProvider Provider;
public string Path { get { return path; } }
public DataBindingType BindingType {
get { return Type; }
}
public LuaContext Context { get; set; }
protected virtual void Awake()
{
if (Provider == null)
Provider = this.GetComponent<DataProvider>();
}
protected virtual void Start()
{
LuaContext parentContext = this.GetComponentInParent<LuaContext>();
parentContext.RegistBinder(this);
Context = parentContext;
}
protected virtual void OnDisable()
{
}
protected virtual void OnDestroy()
{
Context.UnregistBinder(this);
}
public virtual void OnObjectChanged(object value)
{
}
}
}<file_sep>/Assets/GameScript/Lua/Collections/Queue.lua
--[[
Author: LiangZG
Email : <EMAIL>
Desc : 队列
]]
local rawset = rawset
local Queue = class("Queue")
function Queue:ctor( capactity , growFactor)
self._capactity = capactity or 32
self._growFactor = (growFactor or 2) * 100
self._array = Array.new()
self._head = 1
self._tail = 1
self._size = 0
end
function Queue:enqueue( item )
if self._size == self._capactity then
local capactity = self._array:length() * self._growFactor / 100
if capactity < self._array:length() + 4 then
capactity = self._array:length() + 4
end
self:setCapactity(capactity)
end
self._array:insert(self._tail , item)
self._tail = self._tail + 1
self._size = self._size + 1
end
function Queue:dequeue( )
if self._size == 0 then return nil end
local item = self._array[self._head]
self._array[self._head] = false
self._head = self._head + 1
self._size = self._size - 1
return item
end
function Queue:peek( )
if self._size == 0 then return nil end
return self._array[self._head]
end
function Queue.isEmpty(queue)
return Array.isEmpty(queue._array)
end
function Queue:isFull()
return self._array:length() == self._capactity
end
function Queue:contains( obj )
return self._array:indexOf(obj) ~= -1
end
function Queue:clear( )
self._head = 1
self._tail = 1
self._size = 0
self._array:clear()
end
function Queue:setCapactity( capactity )
-- print("----------------size:" .. self._size .. " , capactity:" .. capactity)
-- print("src:" .. self._array:toString() .. ",Array:" .. print_lua_table(self._array))
local objArr = Array.new()
if self._head < self._tail then
Array.copy(self._array , self._head , objArr , 1 , self._size)
else
print("head:" .. self._head .. " length:" .. (self._capactity - self._head))
Array.copy(self._array , self._head , objArr , 1 , self._capactity - self._head)
Array.copy(self._array , 1 , objArr , self._capactity - self._head , self._tail)
end
self._capactity = capactity
self._array = objArr
self._size = self._size == capactity and 0 or self._size
self._head = 1
end
function Queue:size()
return self._size
end
function Queue:enumerator( )
local i = self._head - 1
return function ( )
i = i + 1
return self._array[i]
end
end
function Queue:getEnumerator( )
return Enumerator.new(self._head - 1, 1, function ( i )
return self._array[i]
end)
end
function Queue:toString( )
return self._array:toString()
end
return Queue<file_sep>/Assets/GameScript/Lua/Util/TaskRunner/init.lua
local TASKRUNNER_MODEL_NAME = ...
import ".ITask"
AysncTask = import ".AsyncTask"
TaskCollection = import ".TaskCollection"
SerialTaskCollection = import ".SerialTaskCollection"
ParallelTaskCollection = import ".ParallelTaskCollection"
SingleTask = import ".SingleTask"
TaskRunner = import ".TaskRunner"<file_sep>/Assets/Editor/Script/LuaScriptEditor.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
/// <summary>
/// 描述:Lua脚本创建编辑器
/// <para>创建时间:2016-08-09</para>
/// </summary>
public class LuaScriptEditor : EditorWindow
{
private List<string> templetes = new List<string>();
private Dictionary<string , string> nameAndPath = new Dictionary<string, string>();
private int selectTempleteIndex;
private string tableName = "";
private string selectDir = "";
[MenuItem("GameObject/Custom/CreateLua")]
[MenuItem("AssetTools/Lua %L" , false , 50)]
public static void CreateLuaScript()
{
LuaScriptEditor editor = EditorWindow.GetWindow<LuaScriptEditor>("Create Lua");
editor.Initizalier();
editor.Show();
}
public void Initizalier()
{
string[] files = Directory.GetFiles(Application.dataPath + "/Editor/Script", "*.txt", SearchOption.AllDirectories);
foreach (string file in files)
{
string fileName = Path.GetFileNameWithoutExtension(file);
fileName = fileName.Replace("Templete", "");
templetes.Add(fileName);
nameAndPath.Add(fileName , file);
}
string log = getCreateLog;
if (!string.IsNullOrEmpty(log))
{
string[] logInfos = log.Split(';');
selectTempleteIndex = Convert.ToInt32(logInfos[0]);
selectDir = logInfos[1];
}
}
public void OnGUI()
{
GUILayout.BeginVertical(GUILayout.MinHeight(100));
GUILayout.Space(5);
GUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Templete:" , GUILayout.MaxWidth(100));
selectTempleteIndex = EditorGUILayout.Popup(selectTempleteIndex, templetes.ToArray());
GUILayout.EndHorizontal();
GUILayout.Space(5);
GUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Table Name:", GUILayout.MaxWidth(100));
tableName = EditorGUILayout.TextField(tableName);
GUILayout.EndHorizontal();
GUILayout.Space(5);
EditorGUILayout.LabelField("Path", GUILayout.MaxWidth(100));
GUILayout.BeginHorizontal();
selectDir = selectDir.Replace(Application.dataPath, "");
GUILayout.TextField(string.IsNullOrEmpty(selectDir) ? "[Warn]No Path!!" : selectDir);
if (GUILayout.Button("..." , GUILayout.MaxWidth(30)))
{
selectDir = EditorUtility.OpenFolderPanel("Save Folder", Application.dataPath + "/GameScript", "");
selectDir = selectDir.Replace(Application.dataPath, "Assets");
}
GUILayout.EndHorizontal();
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.Space();
if (GUILayout.Button("Create" , GUILayout.Width(80)))
{
string fileText = File.ReadAllText(nameAndPath[templetes[selectTempleteIndex]]);
fileText = fileText.Replace("tableName", tableName);
string filePath = Path.Combine(selectDir, tableName);
if (!filePath.EndsWith(".lua")) filePath += ".lua";
filePath = filePath.Replace("\\", "/");
File.WriteAllText(filePath , fileText);
SaveLog(); //保存记录
AssetDatabase.ImportAsset(filePath);
Selection.activeObject = AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(filePath);
AssetDatabase.Refresh();
}
}
GUILayout.EndVertical();
}
private string key
{
get { return Application.dataPath + typeof (LuaScriptEditor); }
}
private string getCreateLog
{
get { return EditorPrefs.GetString(key); }
}
private void SaveLog()
{
EditorPrefs.SetString(key, selectTempleteIndex + ";" + selectDir);
}
}
<file_sep>/Assets/GameScript/Lua/AppConst.lua
--[[
Author: LiangZG
Email : <EMAIL>
]]
--[[
应用配置
]]
--AppConst = {}
--资源加载是否使用AssetBundle
AppConst.IsAssetBundle = false
--语言种类
AppConst.Language =
{
["CHINESE"] = "CN",
["ENGLISH"] = "EN"
}
--多语言的模块配置表
AppConst.LocalizationModule =
{
"LTCommon",
"LTUser",
}<file_sep>/Assets/GameScript/Lua/UI/BattlePanel.lua
-- @Author: <EMAIL>
-- @Last Modified time: 2017-01-01 00:00:00
-- @Desc: 战斗面板
BattlePanel = {}
local this = BattlePanel
local curUiId = 0
--- 由LuaBehaviour自动调用
function BattlePanel.Awake(gameObject)
this.widgets = {
{field="root", path ="", src=LuaCanvas},
{field="btn_skill",path="btn_skill",src=LuaButton, onClick = this._onClickSkill },
{field="btn_battle",path="btn_battle",src=LuaButton, onClick = this._onClickBattle },
}
LuaUIHelper.bind(this.gameObject , BattlePanel )
end
function BattlePanel.Show( func )
UIManager:Show("Prefab/GUI/BattlePanel", nil)
this.closeFunc = func
end
--- 由LuaBehaviour自动调用
function BattlePanel.OnInit(basePage)
this.basePage = basePage
this.basePage:SetPage(EPageType.Normal , EShowMode.HideOther , ECollider.Normal)
--每次显示自动修改UI中所有Panel的depth
--LuaUIHelper.addUIDepth(this.gameObject , BattlePanel)
this._registeEvents(this.event)
end
-- 注册界面事件监听
function BattlePanel._registeEvents(event)
end
function BattlePanel._onClickSkill()
SkillPanel.Show()
end
function BattlePanel._onClickBattle()
print("goto battle scene!")
end
--- 关闭界面
function BattlePanel._onClickClose( )
--panelMgr:ClosePanel("BattlePanel")
UIManager.Hide(this.basePage.assetPath)
if this.closeFunc ~= nil then
this.closeFunc()
this.closeFunc = nil
end
end
--- 由LuaBehaviour自动调用
function BattlePanel.OnClose()
--LuaUIHelper.removeUIDepth(this.gameObject) --还原全局深度
end
--- 由LuaBehaviour自动调用--
function BattlePanel.OnDestroy()
this.gameObject = nil
this.transform = nil
this.widgets = nil
end<file_sep>/Assets/GameScript/Lua/Util/EventManager.lua
--[[
Author: LiangZG
Email : <EMAIL>
]]
local Event = require "events"
--[[
Desc:全局事件管理器
]]
EventManager = {}
local this = EventManager
--事件池
local eventPool = {}
function EventManager.AddEvent(luaTableName)
local luatable = this._findTable(luaTableName)
if (not luatable) or luatable["event"] then
print("Cant find table or Event system is already !")
return
end
luatable.event = Event.new()
eventPool[luaTableName] = luatable.event
end
--查找对应的Table
function EventManager._findTable(tableName)
local func = loadstring("return " .. tableName)
return func()
end
--全局广播事件
function EventManager.SendEvent(eventName , ...)
local args = {...}
for k , v in pairs(eventPool) do
if v:Brocast(eventName , unpack(args)) then
return
end
end
end
--清理一份LuaTable内的事件
function EventManager.ClearEvent(luaTableName)
local luatable = this._findTable(luaTableName)
if luatable and luatable["event"] then
--print(" -------> clear event sytem : " .. luaTableName)
luatable.event:Clear()
end
end
<file_sep>/Assets/GameScript/Lua/GameState/UpdateState.lua
--[[
Author: LiangZG
Email : <EMAIL>
]]
local BaseState = require "Common.BaseState"
local LoginState = require "GameState.LoginState"
--[[
更新资源主状态,用于启动时的资源更新
]]
local UpdateState = class("UpdateState" , BaseState)
function UpdateState:OnEnter()
print("Update State ---> OnEnter")
end
function UpdateState:OnExit()
print("Update State <---- OnExit")
end
return UpdateState
<file_sep>/Assets/GameScript/Controller/Command/StartUpCommand.cs
using UnityEngine;
using System.Collections;
using LuaFramework;
public class StartUpCommand : ControllerCommand {
public override void Execute(IMessage message) {
// if (!Util.CheckEnvironment()) return;
GameObject gameMgr = GameObject.Find("GlobalGenerator");
if (gameMgr != null) {
AppView appView = gameMgr.AddComponent<AppView>();
}
//-----------------关联命令-----------------------
AppFacade.Instance.RegisterCommand(NotiConst.DISPATCH_MESSAGE, typeof(SocketCommand));
//-----------------初始化管理器-----------------------
AppFacade.Instance.AddManager<LuaManager>();
AppFacade.Instance.AddManager<PanelManager>();
AppFacade.Instance.AddManager<SoundManager>();
AppFacade.Instance.AddManager<TimerManager>();
AppFacade.Instance.AddManager<ResourceManager>();
AppFacade.Instance.AddManager<ThreadManager>();
AppFacade.Instance.AddManager<ObjectPoolManager>();
AppFacade.Instance.AddManager<GameManager>();
}
}<file_sep>/Assets/GameScript/UISystem/UIManager.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using GEX.Resource;
using RSG;
/// <summary>
/// 描述:UIPage管理器
/// <para>创建时间:2016-08-08</para>
/// </summary>
public class UIManager : ASingleton<UIManager>
{
//页面缓存列表
private Dictionary<string , UIPage> cachePagePool = new Dictionary<string, UIPage>();
private List<UIPage> pageList = new List<UIPage>();
protected EUIState curStateUI;
protected EUIState lastStateUI;
public EUIState CurStateUI
{
get { return curStateUI; }
}
private UIManager() { }
/// <summary>
/// Page GameObject Name 必须和LuaLogic的文件名一致,避免不必要的配置
/// </summary>
/// <param name="pagePath"></param>
/// <param name="param"></param>
public void Show(string pagePath, object param = null)
{
if (!cachePagePool.ContainsKey(pagePath))
{
new Promise<LoadOperation>((s, j) =>
{
LoadOperation loader = GResource.LoadAssetAsync(pagePath);
loader.OnFinish += s;
AppInter.StartCoroutine(loader);
}).Then((loader) =>
{
GameObject prefab = loader.GetAsset<GameObject>();
GameObject gObj = GameObject.Instantiate(prefab);
gObj.name = Path.GetFileNameWithoutExtension(pagePath);
LuaPageBehaviour pageBehaviour = gObj.AddComponent<LuaPageBehaviour>();
UIPage page = new UIPage(pageBehaviour , pagePath);
//缓存记录
cachePagePool.Add(pagePath, page);
showUIPage(page, param);
}).Catch((e) =>
{
Debug.LogError("加载Page异常! Path:" + pagePath);
Debug.LogException(e);
});
}
else
{
UIPage page = cachePagePool[pagePath];
showUIPage(page, param);
}
}
private void showUIPage(UIPage uiPage , object param)
{
//将新显示的Page添加到队尾
pageList.Remove(uiPage);
pageList.Add(uiPage);
//界面适配
adjustRoot(uiPage);
uiPage.OnShow(param);
checkPops(uiPage);
}
/// <summary>
/// 检测并弹出不合格的数据
/// </summary>
/// <param name="page"></param>
private void checkPops(UIPage page)
{
if (page.AttributePage.showMode != EShowMode.HideOther) return;
//如果返回列表不为空,说明界面被反复显示调用,则添加一个分隔标识
// 标识也可是使用Page的各页面配置,用于区分,因为异步情况下界面对象被释放无法使用
int count = page.BackQueue.Count;
if(count > 0 ) page.BackQueue.Add("_none_");
for (int i = pageList.Count - 2; i >= 0; i--)
{
UIPage uiPage = pageList[i];
if(uiPage.AttributePage.pageType == EPageType.Fixed || !uiPage.Active) continue;
uiPage.OnHide();
pageList.RemoveAt(i);
//记录上次显示的界面列表,用于返回操作
//如果页面不需要返回时显示,则不用添加到返回列表
if (uiPage.AttributePage.showMode != EShowMode.NoNeedBack)
{
page.BackQueue.Add(uiPage.AttributePage.assetPath);
}
}
//如果没有新的返回列表,则不需要分隔标识
if(count > 0 && count == page.BackQueue.Count - 1) page.BackQueue.RemoveAt(count);
}
/// <summary>
/// 适配根结点
/// </summary>
/// <param name="uiPage"></param>
private void adjustRoot(UIPage uiPage)
{
UIPageRoot pageRoot = UIPageRoot.Instance;
//设置界面的根结点
Transform parentTrans = pageRoot.GetRoot(uiPage.AttributePage.pageType);
RectTransform rectTrans = uiPage.gameObject.GetComponent<RectTransform>();
rectTrans.SetParent(parentTrans);
rectTrans.anchoredPosition = Vector2.zero;
rectTrans.transform.localScale = Vector3.one;
}
/// <summary>
/// 获得缓存PageUI
/// </summary>
/// <param name="pageName"></param>
/// <returns></returns>
public UIPage GetPageUI(string pageName)
{
if (!cachePagePool.ContainsKey(pageName)) return null;
return cachePagePool[pageName];
}
/// <summary>
/// 隐藏指定页面
/// </summary>
/// <param name="pageName">页面名</param>
public void Hide(string pageName)
{
UIPage page = GetPageUI(pageName);
if (page == null) return;
for (int i = 0; i < pageList.Count; i++)
{
if (pageList[i] != page) continue;
for (int j = pageList.Count - 1; j > i; j--)
{
UIPage tPage = pageList[j];
tPage.OnHide();
pageList.RemoveAt(j);
//记录上次显示的界面列表,用于返回操作
//如果页面不需要返回时显示,则不用添加到返回列表
if (tPage.AttributePage.showMode != EShowMode.NoNeedBack &&
tPage.AttributePage.showMode != EShowMode.HideOther)
page.BackQueue.Add(tPage.AttributePage.assetPath);
}
pageList.RemoveAt(i);
break;
}
page.OnHide();
}
/// <summary>
/// 自动返回上层界面
/// </summary>
public void AutoBackPage()
{
UIPage pageRoot = null;
for (int i = pageList.Count - 1; i >= 0; i--)
{
UIPage page = pageList[i];
//固定界面无法自动返回隐藏,需要强制
//PopUp模式,会随父层的Normal界面关闭
if(page.AttributePage.pageType == EPageType.Fixed || page.AttributePage.pageType == EPageType.PopUp) continue;
if (page.AttributePage.showMode != EShowMode.HideOther && page.AttributePage.showMode != EShowMode.None) continue;
pageRoot = page;
//隐藏当前的页面
Hide(page.AttributePage.assetPath);
break;
}
if (pageRoot == null) return;
//返回上层界面
List<string> backQueue = new List<string>();
//返回队列被使用后清空
string flag = "_none_";
for (int i = pageRoot.BackQueue.Count - 1; i >= 0; i--)
{
if (pageRoot.BackQueue[i] == flag)
{
pageRoot.BackQueue.RemoveAt(i);
break;
}
backQueue.Add(pageRoot.BackQueue[i]);
pageRoot.BackQueue.RemoveAt(i);
}
foreach (string pagePath in backQueue)
{
Show(pagePath , null);
}
}
/// <summary>
/// 设置UI状态
/// </summary>
/// <param name="state"></param>
public void SetStateUI(EUIState state)
{
Camera uiCam = UIPageRoot.Instance.uiCamera;
uiCam.cullingMask = 0;
curStateUI = state;
switch (state)
{
case EUIState.Normal:
CameraUtil.ShowLayerName(uiCam, "UI", "UIModel", "UIEffect", "TipsPenetrate", "GloableUI");
break;
case EUIState.Talk:
case EUIState.Plot:
CameraUtil.ShowLayerName(uiCam, "Plot", "GloableUI");
break;
}
}
}
<file_sep>/Assets/GameScript/UISystem/UIEnums.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
/// 描述:UI框架枚举集合
/// <para>创建时间:2016-08-08</para>
//页面主体类型
public enum EPageType
{
Fixed, //固定页面 , 比如固定的toolbar
Normal, //常规页面
PopUp, //模式窗口 , 最上层的页面,比如:消息盒,确认窗口
}
/// <summary>
/// 显示模式
/// </summary>
public enum EShowMode
{
None , HideOther ,
NeedBack, // 点击返回按钮关闭当前,不关闭其他界面(需要调整好层级关系)
NoNeedBack, // 关闭TopBar,关闭其他界面,不加入backSequence队列
}
/// <summary>
/// 碰撞遮挡
/// </summary>
public enum ECollider
{
None, // 显示该界面不包含碰撞背景
Normal, // 碰撞透明背景
WithBg, // 碰撞非透明背景
}
/// <summary>
/// UI渲染状态,不同状态对应不同的Layer
/// </summary>
public enum EUIState
{
Normal , //正常UI状态
Talk, //对话状态
Plot, //剧情动画
}<file_sep>/Assets/Editor/SceneManagerEditor/AssetBuildEditor.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using LuaFramework;
using UnityEditor;
using UnityEditor.SceneManagement;
/// <summary>
/// 描述:资源打包编辑器逻辑
/// <para>创建时间:2016-06-20</para>
/// </summary>
public class AssetBuildEditor : EditorWindow
{
public static AssetBuildEditor Instance;
private BuildConfig curBuildConfig = new BuildConfig();
private Vector2 confScrollPos;
private static string[] Strategys = new []
{
"Scene" , "Pre File" , "Pre Direction" , "AllInOne"
};
/// <summary>
/// 资源类型
/// </summary>
private static string[] AssetTypes = {"Scene" , "Model" , "Effect" , "UI" , "GameObject"};
private Dictionary<string , IStrategy> strategyDic = new Dictionary<string, IStrategy>();
private List<string> buildConfigs = new List<string>(new []{"None" });
private bool isAddNewConfig;
/// <summary>
/// Bundle引用的公共资源
/// </summary>
private Dictionary<string, List<string>> buildRefDic = new Dictionary<string, List<string>>();
public void Initialize()
{
Instance = this;
strategyDic[Strategys[0]] = new SceneStrategy();
strategyDic[Strategys[1]] = new PreFileStrategy();
strategyDic[Strategys[2]] = new PreDirectionStrategy();
strategyDic[Strategys[3]] = new AllInOneStrategy();
BuildConfigManager.Instance.ReadConfig();
BuildConfig[] configArr = BuildConfigManager.Instance.BuildConfigs;
if (configArr.Length > 0)
{
curBuildConfig = configArr[0];
foreach (BuildConfig bc in configArr)
buildConfigs.Add(bc.BundleName);
}
}
public static IStrategy GetStrategy(string strategy)
{
if(strategy == Strategys[0])
return new SceneStrategy();
if(strategy == Strategys[1])
return new PreFileStrategy();
if(strategy == Strategys[2])
return new PreDirectionStrategy();
if(strategy == Strategys[3])
return new AllInOneStrategy();
return null;
}
/// <summary>
/// 添加引用记录
/// </summary>
/// <param name="bundleName"></param>
/// <param name="depAssetPath"></param>
public void AddDependencie(string bundleName, string depAssetPath)
{
if(!buildRefDic.ContainsKey(bundleName))
buildRefDic[bundleName] = new List<string>();
if (buildRefDic[bundleName].Contains(depAssetPath)) return;
buildRefDic[bundleName].Add(depAssetPath);
}
/// <summary>
/// 分配Bundle
/// </summary>
/// <param name="bundleName">Bundle名称</param>
/// <param name="assetPath">资源的绝对路径</param>
/// <param name="buildConfigName">配置的名称</param>
public List<string> AssignBundle(string bundleName, string assetPath , string buildConfigName)
{
string relativeScenePath = assetPath.Replace(Application.dataPath, "Assets");
string[] depAssetArr = AssetDatabase.GetDependencies(relativeScenePath);
string rootPath = Path.GetDirectoryName(assetPath).Replace("\\", "/");
rootPath = rootPath.Replace(Application.dataPath, "Assets");
List<string> allBundleFiles = new List<string>();
foreach (string defAsset in depAssetArr)
{
string suffix = Path.GetExtension(defAsset);
if (BuildGlobal.FilterAsset.Contains(suffix)) continue;
if (defAsset.StartsWith(rootPath))
{
AssetBundleUtil.AssignBundle(defAsset, bundleName);
allBundleFiles.Add(defAsset);
}
else
{
//记录引用,避免公共集合打包时,把不必要的资源也打要进来
AddDependencie(buildConfigName, defAsset);
}
}
//分配自身的Bundle
AssetBundleUtil.AssignBundle(assetPath, bundleName);
allBundleFiles.Add(assetPath);
return allBundleFiles;
}
/// <summary>
/// 获得Bundle资源引用列表信息
/// </summary>
/// <param name="bundleName"></param>
/// <returns></returns>
public List<string> GetBundleRefList(string bundleName)
{
if (!buildRefDic.ContainsKey(bundleName)) return null;
return buildRefDic[bundleName];
}
void OnGUI()
{
//平台
GUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Build Target:", EditorStyles.boldLabel , GUILayout.MaxWidth(100));
EditorGUILayout.EnumPopup(EditorUserBuildSettings.activeBuildTarget);
GUILayout.EndHorizontal();
this.onSettingGUI();
this.onConfigListGUI();
if (GUILayout.Button("Build" , GUILayout.Height(30)))
{
BuildConfig[] configArr = BuildConfigManager.Instance.BuildConfigs;
IStrategy bcStrategy = null;
BuildConfig lastBuildConfig = null;
HashSet<string> bcLog = new HashSet<string>();
// 分配AssetBundle关联
foreach (BuildConfig buildConfig in configArr)
{
if (bcLog.Contains(buildConfig.BundleName)) continue;
lastBuildConfig = onPrebuild(buildConfig);
bcStrategy = GetStrategy(lastBuildConfig.BuildStrategy);
bcStrategy.BeginProcess(lastBuildConfig);
bcLog.Add(lastBuildConfig.BundleName);
}
this.buildAllBundle();
//打包完成后的处理,比如文件移动等
foreach (BuildConfig buildConfig in configArr)
{
bcStrategy = GetStrategy(buildConfig.BuildStrategy);
bcStrategy.EndProcess(buildConfig);
}
//保存
BuildConfigManager.Instance.SaveConfig();
//提示
EditorUtility.DisplayDialog("提示", "已打包完成!", "OK");
}
GUILayout.Space(5);
}
/// <summary>
/// 前置处理
/// </summary>
/// <param name="buildConfig"></param>
/// <returns></returns>
private BuildConfig onPrebuild(BuildConfig buildConfig)
{
if (buildConfig.PreBuild == "None") return buildConfig;
BuildConfig preBuild = BuildConfigManager.Instance.GetBuildConfig(buildConfig.PreBuild);
return onPrebuild(preBuild);
}
/// <summary>
/// 设置信息
/// </summary>
private void onSettingGUI()
{
EditorGUILayout.LabelField("Setting", EditorStyles.boldLabel);
if (curBuildConfig == null) return;
GUILayout.BeginHorizontal();
GUILayout.Label("AssetBundle Name" , GUILayout.Width(120));
curBuildConfig.BundleName = GUILayout.TextField(curBuildConfig.BundleName);
GUILayout.EndHorizontal();
EditorGUILayout.LabelField("Input Path" , EditorStyles.boldLabel);
GUILayout.BeginHorizontal();
curBuildConfig.InputDir = GUILayout.TextField(curBuildConfig.InputDir);
if (GUILayout.Button("...", GUILayout.Width(30)))
{
string selectDir = EditorUtility.OpenFolderPanel("Input Directory", Application.dataPath, "input");
curBuildConfig.InputDir = selectDir.Replace(Application.dataPath, "").Substring(1);
}
GUILayout.EndHorizontal();
//search file suffix
GUILayout.BeginHorizontal();
GUILayout.Label("Include file" , GUILayout.MaxWidth(120));
curBuildConfig.FileSuffixs = GUILayout.TextField(curBuildConfig.FileSuffixs);
GUILayout.EndHorizontal();
//Output Path
EditorGUILayout.LabelField("Output Path" , EditorStyles.boldLabel);
GUILayout.BeginHorizontal();
curBuildConfig.OutputDir = GUILayout.TextField(curBuildConfig.OutputDir);
if (GUILayout.Button("...", GUILayout.Width(30)))
{
string selectDir = EditorUtility.OpenFolderPanel("Output Directory", BuildGlobal.EXPORT_BUNDLE_ROOT , "output");
curBuildConfig.OutputDir = selectDir.Replace(BuildGlobal.EXPORT_BUNDLE_ROOT.Replace("\\" , "/"), "");
}
GUILayout.EndHorizontal();
// Asset Type
GUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Asset Type", GUILayout.MaxWidth(100));
int selectAssetTyp = 0;
if (!string.IsNullOrEmpty(curBuildConfig.AssetType))
{
for (int i = 0; i < AssetTypes.Length; i++)
{
if (curBuildConfig.AssetType == AssetTypes[i])
{
selectAssetTyp = i;
break;
}
}
}
selectAssetTyp = EditorGUILayout.Popup(selectAssetTyp, AssetTypes);
curBuildConfig.AssetType = AssetTypes[selectAssetTyp];
GUILayout.EndHorizontal();
//前置条件
GUILayout.BeginHorizontal();
EditorGUILayout.LabelField("Pre Build", GUILayout.MaxWidth(100));
int selectPrebuildIndex = buildConfigs.FindIndex((s) =>
{
return s == curBuildConfig.PreBuild;
});
selectPrebuildIndex = EditorGUILayout.Popup(selectPrebuildIndex < 0 ? 0 : selectPrebuildIndex, buildConfigs.ToArray());
curBuildConfig.PreBuild = buildConfigs[selectPrebuildIndex];
GUILayout.EndHorizontal();
//build strategy
EditorGUILayout.LabelField("Build Strategy" , EditorStyles.boldLabel);
int selectStratgyIndex = 0;
for (int i = 0; i < Strategys.Length; i++)
{
if (Strategys[i] == curBuildConfig.BuildStrategy)
{
selectStratgyIndex = i;
break;
}
}
GUILayout.BeginHorizontal();
selectStratgyIndex = EditorGUILayout.Popup(selectStratgyIndex, Strategys);
curBuildConfig.BuildStrategy = Strategys[selectStratgyIndex];
curBuildConfig.OptionSerach = (SearchOption)EditorGUILayout.EnumPopup(curBuildConfig.OptionSerach , GUILayout.MaxWidth(130));
GUILayout.EndHorizontal();
//save change
if (isAddNewConfig)
{
using (new EditorGUILayout.HorizontalScope())
{
GUILayout.FlexibleSpace();
GUI.backgroundColor = Color.green;
if (GUILayout.Button("Save Configs"))
{
BuildConfigManager.Instance.SaveConfig();
isAddNewConfig = false;
}
GUI.backgroundColor = Color.white;
GUILayout.FlexibleSpace();
}
}
}
/// <summary>
/// 配置列表
/// </summary>
private void onConfigListGUI()
{
GUILayout.Space(5);
BuildConfig[] configArr = BuildConfigManager.Instance.BuildConfigs;
using (new EditorGUILayout.HorizontalScope())
{
EditorGUILayout.LabelField("Configs", EditorStyles.boldLabel);
GUILayout.FlexibleSpace();
if (GUILayout.Button("Add"))
{
BuildConfigManager.Instance.AddBuildConfig("default" + configArr.Length);
isAddNewConfig = true;
}
}
GUILayout.Space(5);
confScrollPos = GUILayout.BeginScrollView(confScrollPos);
foreach (BuildConfig buildConfig in configArr)
{
GUILayout.BeginHorizontal();
GUILayout.Space(Screen.width * 0.1f);
if (curBuildConfig != null && curBuildConfig.BundleName == buildConfig.BundleName)
{
GUI.backgroundColor = Color.green;
}
if (GUILayout.Button(buildConfig.BundleName))
{
curBuildConfig = buildConfig;
}
GUI.backgroundColor = Color.white;
GUILayout.Space(Screen.width * 0.1f);
GUILayout.EndHorizontal();
}
GUILayout.EndScrollView();
GUILayout.Space(5);
}
/// <summary>
/// 打包所有的Bundle文件
/// </summary>
private void buildAllBundle()
{
if (AppConst.LuaBundleMode)
buildAllBundle(BuildAssetBundleOptions.UncompressedAssetBundle, EditorUserBuildSettings.activeBuildTarget);
else
{
//非Bundle模式,生成文件名同路径的映射
StringBuilder buf = new StringBuilder();
buf.AppendLine(genDevAssetForMap());
buf.AppendLine(AppPathUtils.AssetForMap);
buf.AppendLine(genAssetForBundleMap());
//写入映射关联文件
string mapPath = Path.Combine(AppPathUtils.PersistentDataRootPath, "dev" + AppPathUtils.AssetBundleMap);
File.WriteAllText(mapPath, buf.ToString());
AssetDatabase.Refresh();
}
}
private void buildAllBundle(BuildAssetBundleOptions options , BuildTarget target)
{
string path = BuildGlobal.EXPORT_BUNDLE_ROOT;
BuildPipeline.BuildAssetBundles(path, options, target);
//拷贝文件
CopyFileTo(AppPathUtils.PersistentDataRootPath);
EditorSceneManager.SaveOpenScenes();
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
/// <summary>
/// 拷贝文件到运行环境目录
/// </summary>
public static void CopyFileTo(string targetDir)
{
//对AssetBundleManifest文件改名,默认没有后缀
string manifestFile = BuildGlobal.EXPORT_BUNDLE_ROOT.Replace("\\" , "/");
manifestFile = manifestFile.Substring(0, manifestFile.Length - 1);
manifestFile = manifestFile.Substring(manifestFile.LastIndexOf("/") + 1);
manifestFile = BuildGlobal.EXPORT_BUNDLE_ROOT + manifestFile;
File.Copy(manifestFile, BuildGlobal.EXPORT_BUNDLE_ROOT + "bin_none" + AppPathUtils.BundleSuffix, true);
//再次移动所有的AssetBundle文件到目标目录
if (!Directory.Exists(targetDir)) Directory.CreateDirectory(targetDir);
string[] allFiles = Directory.GetFiles(BuildGlobal.EXPORT_BUNDLE_ROOT, "*"+AppPathUtils.BundleSuffix,
SearchOption.AllDirectories);
string mapPath = Path.Combine(targetDir , AppPathUtils.AssetBundleMap);
//读取原映射文件
Dictionary<string, string> mapDic = new Dictionary<string, string>();
if (File.Exists(mapPath))
{
string[] mapInfos = File.ReadAllText(mapPath).Trim().Split('\n');
foreach (string mapInfo in mapInfos)
{
if (mapInfo.IndexOf(':') >= 0) break;
string[] maps = mapInfo.Split(';');
mapDic[maps[0]] = maps[1];
}
}
StringBuilder fileMap = new StringBuilder();
foreach (string filePath in allFiles)
{
string fileName = Path.GetFileNameWithoutExtension(filePath);
string[] fileAndType = fileName.Split('_');
string fileType = "none";
if (fileAndType.Length > 1) fileType = fileAndType[fileAndType.Length - 1];
string relativePath = filePath.Replace(BuildGlobal.EXPORT_BUNDLE_ROOT, "");
relativePath = relativePath.Replace("_" + fileType, "");
string md5 = Util.md5file(filePath);
//删除旧的文件
bool isCopy = false;
if (mapDic.ContainsKey(filePath) && mapDic[filePath] != md5)
{
if(File.Exists(mapDic[filePath]))
File.Delete(mapDic[filePath]);
isCopy = true;
}
string targetPath = Path.Combine(targetDir, md5);
if(isCopy || !File.Exists(targetPath))
File.Copy(filePath , targetPath, true);
fileMap.AppendFormat("{0};{1};{2}\n" , fileType.ToLower(), relativePath, md5);
}
//添加资源映射
fileMap.AppendLine(AppPathUtils.AssetForMap);
fileMap.Append(genAssetForBundleMap());
//写入映射关联文件
File.WriteAllText(mapPath, fileMap.ToString());
}
/// <summary>
/// 生成资源同Bundle文件的映射,进行在加载资源时,识别包含此文件的Bundle名称
/// </summary>
private static string genAssetForBundleMap()
{
string[] bundleNames = AssetDatabase.GetAllAssetBundleNames();
StringBuilder buf = new StringBuilder();
foreach (string bundleName in bundleNames)
{
string[] assetPathArr = AssetDatabase.GetAssetPathsFromAssetBundle(bundleName);
string fileType = "none";
string[] fileAndType = bundleName.Replace(AppPathUtils.BundleSuffix, "").Split('_');
if (fileAndType.Length > 1) fileType = fileAndType[fileAndType.Length - 1];
foreach (string assetPath in assetPathArr)
{
string suffix = Path.GetExtension(assetPath);
if(!BuildGlobal.MapIndexFilter.Contains(suffix)) continue;
string fileName = Path.GetFileName(assetPath);
buf.AppendFormat("{0};{1};{2}\n", fileType.ToLower(), fileName, bundleName );
}
}
return buf.ToString();
}
/// <summary>
/// 生成开发期的映射数据,文件类型|AssetBundleName|Resource相对工程路径
/// </summary>
/// <returns></returns>
private static string genDevAssetForMap()
{
string[] bundleNames = AssetDatabase.GetAllAssetBundleNames();
StringBuilder buf = new StringBuilder();
foreach (string bundleName in bundleNames)
{
string[] assetPathArr = AssetDatabase.GetAssetPathsFromAssetBundle(bundleName);
string fileType = "none";
string[] fileAndType = bundleName.Replace(AppPathUtils.BundleSuffix, "").Split('_');
if (fileAndType.Length > 1) fileType = fileAndType[fileAndType.Length - 1];
foreach (string assetPath in assetPathArr)
{
string suffix = Path.GetExtension(assetPath);
if (!BuildGlobal.MapIndexFilter.Contains(suffix)) continue;
string bundle = bundleName.Replace("_" + fileType.ToLower(), "");
buf.AppendFormat("{0};{1};{2}\n", fileType.ToLower(), bundle, assetPath);
}
}
return buf.ToString();
}
}
<file_sep>/Assets/GameScript/Lua/Common/BaseState.lua
--[[
Author: LiangZG
Email : <EMAIL>
]]
--[[
有限状态基基类
]]
local BaseState = class("BaseState")
function BaseState:OnEnter()
end
function BaseState:OnUpdate()
end
function BaseState:OnExit()
end
return BaseState
<file_sep>/Assets/GEngineScript/Core/NetworkSystem/Socket/SocketEnums.cs
using UnityEngine;
using System.Collections;
namespace GEX.Network
{
public enum SocketState
{
Connecting, //连接中
Connected, //已连接
Disconnecting, //断开中
Disconnected, //已断开
}
}
<file_sep>/Assets/GameScript/Lua/Util/TaskRunner/SingleTask.lua
--[[
Author: LiangZG
Email : <EMAIL>
Desc : 单一任务
]]
local iskindof = iskindof
local Enumerator = require "Collections.Enumerator"
local SingleTask = class("SingleTask" , Enumerator)
function SingleTask:ctor( task )
SingleTask.super.ctor(self)
if iskindof(task , "TaskCollection") then
self._enumerator = task
else
self._task = SerialTaskCollection.new()
self._task:add(task)
self._enumerator = self._task:getEnumerator()
end
end
function SingleTask:current( )
return self._enumerator:current()
end
function SingleTask:moveNext( )
if not self._enumerator:moveNext() then
if self.onComplete then
self.onComplete()
end
return false
end
return true
end
function SingleTask:reset( )
--self._enumerator:reset()
end
return SingleTask<file_sep>/Assets/GEngineScript/Core/SceneManager/LightMap/PrefabLightmapData.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace GOE.Scene
{
/// <summary>
/// 描述:光照模型预设
/// <para>创建时间:</para>
/// </summary>
[DisallowMultipleComponent , ExecuteInEditMode]
public class PrefabLightmapData : MonoBehaviour
{
[SerializeField]
public RendererInfo[] mRendererInfos;
[SerializeField]
public Texture2D[] mLightmapFars;
[SerializeField]
public Texture2D[] mLightmapNears;
void Awake()
{
ApplyLightmaps(mRendererInfos , mLightmapFars , mLightmapNears);
LightmapSettings.lightmapsMode = LightmapsMode.NonDirectional;
}
void Start()
{
// StaticBatchingUtility.Combine(this.gameObject);
}
/// <summary>
/// 应用光照模型,根据指定的渲染信息
/// </summary>
/// <param name="rendererInfos"></param>
/// <param name="lightmapFars"></param>
/// <param name="lightmapNears"></param>
public static void ApplyLightmaps(RendererInfo[] rendererInfos, Texture2D[] lightmapFars,
Texture2D[] lightmapNears)
{
if (rendererInfos == null || rendererInfos.Length <= 0)
{
Debug.LogWarning("<<PrefabLightmapData , ApplyLightmaps>> renderer info is null !");
return;
}
LightmapData[] settingLightMaps = LightmapSettings.lightmaps;
int[] lightmapOffsetIndex = new int[lightmapFars.Length];
List<LightmapData> combinedLightmaps = new List<LightmapData>();
bool existAlready = false;
for (int i = 0; i < lightmapFars.Length; i++)
{
existAlready = false;
for (int j = 0; j < settingLightMaps.Length; j++)
{
if (lightmapFars[i] == settingLightMaps[j].lightmapColor)
{
lightmapOffsetIndex[i] = j;
existAlready = true;
break;
}
}
//如果不存在,则创建新的光照数据
if (!existAlready)
{
lightmapOffsetIndex[i] = settingLightMaps.Length + combinedLightmaps.Count;
LightmapData newLightData = new LightmapData();
newLightData.lightmapColor = lightmapFars[i];
newLightData.lightmapDir = lightmapNears[i];
combinedLightmaps.Add(newLightData);
}
}
//组合数据
LightmapData[] finalCombinedLightData = new LightmapData[combinedLightmaps.Count + settingLightMaps.Length];
settingLightMaps.CopyTo(finalCombinedLightData , 0);
combinedLightmaps.CopyTo(finalCombinedLightData , settingLightMaps.Length);
combinedLightmaps.Clear();
applyRendererInfo(rendererInfos , lightmapOffsetIndex);
//重新绑定
LightmapSettings.lightmaps = finalCombinedLightData;
}
/// <summary>
/// 应用渲染信息
/// </summary>
/// <param name="rendererInfos"></param>
/// <param name="offsetIndexs"></param>
private static void applyRendererInfo(RendererInfo[] rendererInfos, int[] offsetIndexs)
{
for (int i = 0; i < rendererInfos.Length; i++)
{
RendererInfo info = rendererInfos[i];
info.renderer.lightmapIndex = offsetIndexs[info.LightmapIndex];
info.renderer.lightmapScaleOffset = info.LightmapOffsetScale;
}
}
}
}
<file_sep>/Assets/GameScript/Lua/Util/eUtil.lua
--计时器,时间单位
eTimeUnit = { MilliSecond = 0.1 , Second = 1, Min = 60, Hour = 3600}<file_sep>/Assets/GEngineScript/Core/ResourceSystem/UIAtlasCache.cs
using System.Collections.Generic;
using UnityEngine;
namespace GEX.Resource
{
public class UIAtlasCache
{
private Dictionary<string, Sprite> atlas;
private int _refCount = 0;
public UIAtlasCache(Sprite[] sprites)
{
atlas = new Dictionary<string, Sprite>();
for (int i = 0; i < sprites.Length; i++)
{
atlas[sprites[i].name] = sprites[i];
}
}
public Sprite GetSprite(string spriteName)
{
Sprite spt = null;
atlas.TryGetValue(spriteName, out spt);
_refCount++;
return spt;
}
public bool Contains(string spriteName)
{
return atlas.ContainsKey(spriteName);
}
public bool Unload()
{
_refCount--;
return _refCount <= 0;
}
public void Load()
{
_refCount++;
}
}
}<file_sep>/Assets/GameScript/Lua/define.lua
--协议类型--
ProtocalType = {
BINARY = 0,
PB_LUA = 1,
PBC = 2,
SPROTO = 3,
}
require "Engines.table"
require "Engines.string"
require "Engines.class"
--require "AppConst"
--require "AppMain"
require "GameScript"
require "UnityEngines"
require "Engines.init"
require "Common.init"
require "3rd.init"
require "GameState.init"
require "UI.init"
--require "Net.init"
require "Util.init"
--test
require "Test.init"<file_sep>/Assets/GEngineScript/Core/ResourceSystem/Base/LoadOperation.cs
using System;
using System.Collections;
using LuaInterface;
namespace GEX.Resource
{
public abstract class LoadOperation : IEnumerator
{
protected float progress;
/// <summary>
/// 加载进度
/// </summary>
public float Progress { get { return progress; } }
/// <summary>
/// 加载完成时的回调
/// </summary>
public Action<LoadOperation> OnFinish;
/// <summary>
/// 资源路径
/// </summary>
public string assetPath { get; protected set; }
protected bool hasLoaded = false;
public LoadOperation()
{}
public LoadOperation(string path)
{
this.assetPath = path.ToLower();
}
public virtual bool MoveNext()
{
if (!hasLoaded)
{
hasLoaded = true;
this.OnLoad();
}
return !IsDone();
}
public virtual void Reset()
{
}
public virtual object Current { get { return null; } }
public abstract void OnLoad();
public abstract bool IsDone();
[NoToLua]
public abstract T GetAsset<T>() where T : UnityEngine.Object;
protected virtual void onFinishEvent()
{
this.Finish(this);
}
public void Finish(LoadOperation loader)
{
progress = 1.0f;
if (OnFinish != null)
{
OnFinish.Invoke(loader);
OnFinish = null;
}
}
}
}
<file_sep>/Assets/GameScript/Lua/Util/TaskRunner/TaskRunner.lua
--[[
Author: LiangZG
Email : <EMAIL>
Desc : 任务执行器
]]
local TaskRunner = {}
function TaskRunner.run( task )
coroutine.start(function ( )
--print("current :" .. tostring(coroutine.running()))
while task:moveNext() do
local item = task:current()
if item == "function" then
item()
end
end
end)
end
function TaskRunner.run2( task )
local timer = nil
local curTask = nil
local action = function()
if not curTask.isDone then
return
end
if task:moveNext() then
curTask = task:current()
coroutine.start(curTask)
else
timer:Stop()
end
end
timer = FrameTimer.New(action, 1, -1)
timer:Start()
curTask = task:current()
coroutine.start(curTask)
end
return TaskRunner<file_sep>/Assets/GameScript/Lua/UI/Skill/init.lua
-- @Author: <EMAIL>
-- @Desc: 技能界面模块
import (".SkillPanel")
import (".SkillUpdatePanel")<file_sep>/Assets/GEngineScript/Core/ResourceSystem/Loader/SerialLoader.cs
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LuaInterface;
namespace GEX.Resource
{
/// <summary>
/// 串形异步加载容器,容器内部自动缓存加载器,需要手动释放
/// 使用方法:
/// var async = new SerialAsync();
///
/// async.AddLoader("xxx/press/yy.prefab");
/// async.AddLoader("xxx/pres/zzz.ogg" , 5);
///
/// while(async.MoveNext())
/// {
/// if(async.CurrentLoader.IsDone()){
/// var loader = async.CurrentLoader;
/// var gameObj = GameObject.Instantiate(loader.GetAsset<GameObject>());
/// }
/// // progress
/// if(progressAction != null)
/// progressAction.Invoke(async.Progress);
/// yield return null;
/// }
/// </summary>
public class SerialLoader : LoadOperation
{
private class AsyncLoader
{
public int Weight;
public LoadOperation Loader;
}
/// <summary>
/// 权重,占总场景资源量的比重
/// </summary>
public int Weight { get; private set; }
private int completeWeight;
private List<AsyncLoader> assets = new List<AsyncLoader>();
private AsyncLoader curLoader;
private AsyncLoader nextLoader;
private int moveIndex;
//缓存
private Dictionary<LoadOperation, AsyncLoader> cacheLoader;
public SerialLoader()
{
cacheLoader = new Dictionary<LoadOperation, AsyncLoader>();
}
/// <summary>
/// 添加需要被加载的资源
/// </summary>
/// <param name="loader">异步加载器</param>
/// <param name="weight">权重,用于计算进度</param>
public LoadOperation AddLoader(LoadOperation loader, int weight = 1)
{
Weight += weight;
AsyncLoader asyncLoader = new AsyncLoader();
asyncLoader.Weight = weight;
asyncLoader.Loader = loader;
this.assets.Add(asyncLoader);
if (nextLoader == null)
{
nextLoader = asyncLoader;
curLoader = nextLoader;
}
return loader;
}
/// <summary>
/// 添加加载数据
/// </summary>
/// <param name="path">资源路径,类似"Assets/Res/XXXX.yyy"</param>
/// <param name="weight">权重,用于计算进度</param>
public LoadOperation AddLoader(string path, int weight = 1)
{
LoadOperation loadOpt = GResource.LoadAssetAsync(path);
this.AddLoader(loadOpt, weight);
return loadOpt;
}
public override bool MoveNext()
{
if (assets.Count <= 0) return false;
bool isMoveNext = false;
AsyncLoader temLoader = null;
if (cacheLoader.TryGetValue(nextLoader.Loader, out temLoader))
{
nextLoader.Loader.Finish(temLoader.Loader);
isMoveNext = true;
}else
isMoveNext = !nextLoader.Loader.MoveNext();
if (isMoveNext)
{
moveIndex++;
curLoader = nextLoader;
if (!cacheLoader.TryGetValue(curLoader.Loader, out temLoader))
{
cacheLoader[curLoader.Loader] = curLoader;
}
if (moveIndex < assets.Count)
{
completeWeight += nextLoader.Weight;
nextLoader = assets[moveIndex];
}
}
float completedProgress = completeWeight + nextLoader.Loader.Progress * nextLoader.Weight;
progress = completedProgress / Weight;
return !IsDone();
}
public LoadOperation CurrentLoader
{
get { return curLoader.Loader; }
}
public override object Current
{
get { return CurrentLoader; }
}
public override bool IsDone()
{
bool result = moveIndex >= assets.Count;
if(result)
this.onFinishEvent();
return result;
}
public override void Reset()
{
moveIndex = 0;
for (int i = 0; i < assets.Count; i++)
{
assets[i].Loader.Reset();
assets[i].Loader.OnFinish = null;
}
assets.Clear();
cacheLoader.Clear();
nextLoader = null;
curLoader = null;
progress = 0;
Weight = 0;
}
public override void OnLoad()
{
throw new System.NotImplementedException();
}
[NoToLua]
public override T GetAsset<T>()
{
throw new System.NotImplementedException();
}
}
}
<file_sep>/Assets/GEngineScript/Core/SceneManager/SceneStageManager.cs
/************************************************************************************
* @Author : LiangZG
* @Email : <EMAIL>
* @Date : 2017-04-27
***********************************************************************************/
using System.Collections;
using LuaInterface;
using System;
using GEX.Resource;
using LuaFramework;
using UnityEngine;
namespace GEX.SceneManager
{
/// <summary>
/// 游戏场景管理
/// </summary>
public sealed class SceneStageManager : ASingleton<SceneStageManager>
{
public LuaTable curStage { get; private set; }
/// <summary>
/// 异步场景加载器
/// </summary>
public StageLoader stageLoader { get; private set; }
private LuaManager luaMgr;
private string nextSceneName;
/// <summary>
/// 下一个场景的名称
/// </summary>
public string NextSceneName
{
get { return nextSceneName; }
}
void Awake()
{
luaMgr = AppFacade.Instance.GetManager<LuaManager>();
}
public void LoadScene(LuaTable newStage)
{
string sceneName = newStage.GetStringField("stageName");
luaMgr.StartCoroutine(loadScene(sceneName , newStage));
}
private IEnumerator loadScene(string sceneName , LuaTable newStage)
{
LuaTable lastStage = curStage;
curStage = newStage;
CallFunction(lastStage, "onExit");
stageLoader = new StageLoader();
CallFunction(newStage, "onEnter" , stageLoader);
while (stageLoader.MoveNext())
yield return null;
UnityEngine.SceneManagement.SceneManager.LoadScene(sceneName);
while (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name != sceneName)
yield return null;
//wait a frame
yield return null;
this.OnCompleted();
CallFunction(newStage, "onShow");
}
/// <summary>
/// 异步加载本地当前场景切换
/// </summary>
/// <param name="newStage">场景Lua状态</param>
/// <param name="process">加载进度</param>
public void LoadLocalScene(LuaTable newStage , Action<float> process)
{
LuaTable lastStage = curStage;
curStage = newStage;
stageLoader = new StageLoader();
CallFunction(lastStage, "onExit");
luaMgr.StartCoroutine(this.onLoading(process));
}
private IEnumerator onLoading(Action<float> process)
{
CallFunction(curStage, "onEnter", this, stageLoader);
float progress = 0f;
while (stageLoader.MoveNext())
{
progress = Mathf.Lerp(progress, stageLoader.Progress, Time.deltaTime * 10f);
if (process != null)
process.Invoke(progress);
yield return null;
}
if (process != null) process.Invoke(1);
while (!stageLoader.IsSceneDone())
yield return null;
OnCompleted();
CallFunction(curStage, "onShow");
}
/// <summary>
/// 异步加载场景
/// </summary>
/// <param name="newStage">场景Lua状态</param>
public void LoadSceneViaPreloading(LuaTable newStage)
{
LuaTable lastStage = curStage;
curStage = newStage;
//下个场景名
string sceneName = newStage.GetStringField("stageName");
nextSceneName = sceneName;
//过渡场景名
string transitScene = newStage.GetStringField("transitScene");
stageLoader = new StageLoader(sceneName);
CallFunction(lastStage, "onExit");
UnityEngine.SceneManagement.SceneManager.LoadScene(transitScene);
}
/// <summary>
/// 加载切块的场景
/// </summary>
/// <param name="newStage">场景Lua状态</param>
public void LoadChunkScene(LuaTable newStage)
{
LuaTable lastStage = curStage;
curStage = newStage;
//下个场景名
string sceneName = newStage.GetStringField("stageName");
nextSceneName = sceneName;
//过渡场景名
string transitScene = newStage.GetStringField("transitScene");
stageLoader = new StageLoader();
CallFunction(lastStage, "onExit");
UnityEngine.SceneManagement.SceneManager.LoadScene(transitScene);
}
public static void CallFunction(LuaTable luaTab, string func , params object[] args)
{
if (luaTab == null) return;
LuaFunction luaFunc = luaTab.GetLuaFunction(func);
luaFunc.BeginPCall();
luaFunc.Push(luaTab);
luaFunc.PushArgs(args);
luaFunc.PCall();
luaFunc.EndPCall();
}
public void OnCompleted()
{
if(stageLoader != null)
stageLoader.Reset();
stageLoader = null;
}
}
}
<file_sep>/Assets/Libs/LuaDataBind/UI/Command/ButtonClickCommand.cs
using System.Collections.Generic;
using UnityEngine;
namespace LuaDataBind
{
/// <summary>
/// Command to invoke when a button was clicked.
/// </summary>
[AddComponentMenu("Data Bind/Commands/[NGUI] Button Click Command")]
public class ButtonClickCommand : NguiEventCommand<UIButton>
{
protected override List<EventDelegate> GetEvent(UIButton target)
{
return target.onClick;
}
}
}<file_sep>/Assets/GameScript/Lua/Collections/StringBuffer.lua
--[[
Author: LiangZG
Email : <EMAIL>
Desc : stringBuffer
]]
local stringBuffer = class("stringBuffer")
local m = stringBuffer
function m:ctor( )
self.buf = {}
self._size = 0
end
function m:append( str )
table.insert(self.buf , str)
self._size = self._size + 1
end
function m:appendFormat( format , ... )
local str = string.format(format , ...)
self:append(str)
end
function m:appendLine( str )
self:append(str)
table.insert(self.buf , "\n")
end
function m:remove( str )
for i=self:size(),1,-1 do
if self.buf[i] == str then
table.remove(self.buf , i)
self._size = self._size - 1
return
end
end
end
function m:toString()
return table.concat(self.buf, "")
end
function m:clear()
self.buf = {}
self._size = 0
end
function m:size()
return self._size
end
return stringBuffer<file_sep>/Assets/GEngineScript/Core/NetworkSystem/Socket/ByteArray.cs
using System;
using UnityEngine;
using System.Collections;
namespace GEX.Network
{
public class ByteArray
{
private byte[] buffer;
private int position;
public byte[] Bytes
{
get
{
return this.buffer;
}
set
{
this.buffer = value;
}
}
public int BytesAvailable
{
get
{
int num = this.buffer.Length - this.position;
if (num <= this.buffer.Length && num >= 0)
return num;
return 0;
}
}
public int Length
{
get
{
return this.buffer.Length;
}
}
public int Position
{
get
{
return this.position;
}
set
{
this.position = value;
}
}
public ByteArray()
{
this.position = 0;
this.buffer = new byte[0];
}
public ByteArray(byte[] buf)
{
this.position = 0;
this.buffer = buf;
}
public bool ReadBool()
{
byte[] numArray = this.buffer;
int num = this.position;
this.position = num + 1;
int index = num;
return (int)numArray[index] == 1;
}
public byte ReadByte()
{
byte[] numArray = this.buffer;
int num = this.position;
this.position = num + 1;
int index = num;
return numArray[index];
}
public byte[] ReadBytes(int count)
{
byte[] numArray = new byte[count];
Buffer.BlockCopy((Array)this.buffer, this.position, (Array)numArray, 0, count);
this.position = this.position + count;
return numArray;
}
public double ReadDouble()
{
return BitConverter.ToDouble(this.ReverseOrder(this.ReadBytes(8)), 0);
}
public float ReadFloat()
{
return BitConverter.ToSingle(this.ReverseOrder(this.ReadBytes(4)), 0);
}
public int ReadInt()
{
return BitConverter.ToInt32(this.ReverseOrder(this.ReadBytes(4)), 0);
}
public long ReadLong()
{
return BitConverter.ToInt64(this.ReverseOrder(this.ReadBytes(8)), 0);
}
public short ReadShort()
{
return BitConverter.ToInt16(this.ReverseOrder(this.ReadBytes(2)), 0);
}
public ushort ReadUShort()
{
return BitConverter.ToUInt16(this.ReverseOrder(this.ReadBytes(2)), 0);
}
public string ReadUTF()
{
ushort num = this.ReadUShort();
if ((int)num == 0)
return (string)null;
string @string = System.Text.Encoding.UTF8.GetString(this.buffer, this.position, (int)num);
this.position = this.position + (int)num;
return @string;
}
public byte[] ReverseOrder(byte[] dt)
{
if (!BitConverter.IsLittleEndian)
return dt;
byte[] numArray = new byte[dt.Length];
int num = 0;
for (int index = dt.Length - 1; index >= 0; --index)
numArray[num++] = dt[index];
return numArray;
}
public void WriteBool(bool b)
{
this.WriteBytes(new byte[1]{(byte) (!b ? 0 : 1)});
}
public void WriteByte(byte b)
{
this.WriteBytes(new byte[1]{b});
}
public void WriteBytes(byte[] data)
{
this.WriteBytes(data, 0, data.Length);
}
public void WriteBytes(byte[] data, int ofs, int count)
{
byte[] numArray = new byte[count + this.buffer.Length];
Buffer.BlockCopy((Array)this.buffer, 0, (Array)numArray, 0, this.buffer.Length);
Buffer.BlockCopy((Array)data, ofs, (Array)numArray, this.buffer.Length, count);
this.buffer = numArray;
}
public void WriteDouble(double d)
{
this.WriteBytes(this.ReverseOrder(BitConverter.GetBytes(d)));
}
public void WriteFloat(float f)
{
this.WriteBytes(this.ReverseOrder(BitConverter.GetBytes(f)));
}
public void WriteInt(int i)
{
this.WriteBytes(this.ReverseOrder(BitConverter.GetBytes(i)));
}
public void WriteLong(long l)
{
this.WriteBytes(this.ReverseOrder(BitConverter.GetBytes(l)));
}
public void WriteShort(short s)
{
this.WriteBytes(this.ReverseOrder(BitConverter.GetBytes(s)));
}
public void WriteUShort(ushort us)
{
this.WriteBytes(this.ReverseOrder(BitConverter.GetBytes(us)));
}
public void WriteUTF(string str)
{
if (string.IsNullOrEmpty(str))
{
this.WriteUShort((ushort)0);
}
else
{
int num1 = 0;
for (int index = 0; index < str.Length; ++index)
{
int num2 = (int)str[index];
if (num2 >= 1 && num2 <= (int)sbyte.MaxValue)
++num1;
else if (num2 > 2047)
num1 += 3;
else
num1 += 2;
}
if (num1 > 32768)
throw new FormatException("String length cannot be greater then 32768 !");
this.WriteUShort(Convert.ToUInt16(num1));
this.WriteBytes(System.Text.Encoding.UTF8.GetBytes(str));
}
}
}
}
<file_sep>/Assets/GEngineScript/Core/Asset/AssetLoader.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using GOE.Scene;
#if UNITY_EDITOR
using UnityEditor;
#endif
/// <summary>
/// 描述:资源加载器,主要用于加载除场景资源外的其它资源
/// <para>创建时间:2016-06-20</para>
/// </summary>
public class AssetLoader : ASingleton<AssetLoader>{
public enum EAssetType
{
ALL,
Scene, //场景
Model , //模型
Effect , //特效
UI, //UI界面
GameObject, //普通GameObject
}
public enum EAssetBaseType
{
Text , ByteArray , Texture2D , AssetBundle
}
private Dictionary<string , ARCCache<string , Asset>> bundlePoolCache = new Dictionary<string, ARCCache<string, Asset>>();
/// <summary>
/// key:Name Value:Path
/// </summary>
private Dictionary<string , string> nameToPathMap = new Dictionary<string, string>();
private Dictionary<string , string> pathToBundleMap = new Dictionary<string, string>();
private AssetBundleManifest manifest;
/// <summary>
/// 是否是加载Bundle资源
/// </summary>
public static bool isBundle = true;
private AssetLoader()
{
swapnCachePool(EAssetType.ALL.ToString(), 100);
}
#region --------------Lua层的静态调用方法-----------------------
/// <summary>
/// 通过指定资源名加载GameObject资源
/// </summary>
/// <param name="resName">资源名称</param>
/// <param name="callback">加载实例完成后的回调</param>
public static void LoadGameObjectByName(string resName, EAssetType assetType , Action<GameObject> callback)
{
AppInter.StartCoroutine(Instance.SwapAssetByName<UnityEngine.Object>(EAssetType.ALL.ToString() , resName , assetType, (obj) =>
{
if (obj == null)
{
callback.Invoke(null);
return;
}
//实例
GameObject gObj = GameObject.Instantiate(obj) as GameObject;
callback.Invoke(gObj);
}));
}
/// <summary>
/// 通过指定的UI资源名加载实例GameObject对象
/// </summary>
/// <param name="resName">UI资源名</param>
/// <param name="callback">加载实例完成后的回调</param>
public static void LoadUI(string resName, Action<GameObject> callback)
{
LoadGameObjectByName(resName , EAssetType.UI, callback);
}
/// <summary>
/// 通过指定的特效资源名加载实例GameObject对象
/// </summary>
/// <param name="resName">特效资源名</param>
/// <param name="callback">加载实例完成后的回调</param>
public static void LoadEffect(string resName, Action<GameObject> callback)
{
LoadGameObjectByName(resName, EAssetType.Effect, callback);
}
/// <summary>
/// 通过指定的模型资源名加载实例GameObject对象
/// </summary>
/// <param name="resName">模型资源名</param>
/// <param name="callback">加载实例完成后的回调</param>
public static void LoadModel(string resName, Action<GameObject> callback)
{
LoadGameObjectByName(resName, EAssetType.Model, callback);
}
/// <summary>
/// 加载一个普通的GameObject对象
/// </summary>
/// <param name="resName">模型资源名</param>
/// <param name="callback">加载实例完成后的回调</param>
public static void LoadGameObject(string resName, Action<GameObject> callback)
{
LoadGameObjectByName(resName, EAssetType.GameObject, callback);
}
/// <summary>
/// 通过指定路径加载AssetBundle中的Text资源
/// </summary>
/// <param name="path"></param>
/// <param name="callback"></param>
// public static void LoadTextAtPath(string path, Action<string> callback)
// {
// AssetLoader loader = AssetLoader.Instance;
// loader.swapnCachePool(EAssetType.ALL.ToString(), 100);
// loader.SwapAssetAtPath(EAssetType.ALL.ToString(), path, (obj) =>
// {
// if (obj == null)
// {
// callback(null);
// return;
// }
// TextAsset textAss = obj as TextAsset;
// callback(textAss.text);
// });
// }
/// <summary>
/// 通过指定资源名称加载AssetBundle中的Text资源
/// </summary>
/// <param name="resName"></param>
/// <param name="callback"></param>
// public static void LoadTextByName(string resName, Action<string> callback)
// {
// AssetLoader loader = AssetLoader.Instance;
// string path = loader.GetAssetPath(resName);
//// LoadTextAtPath(path, callback);
// }
/// <summary>
/// 通过指定路径加载AssetBundle中的Text资源
/// </summary>
/// <param name="path"></param>
/// <param name="callback"></param>
public static void LoadByteArrayAtPath(string path, Action<byte[]> callback)
{
// Instance.SwapAssetAtPath(EAssetType.ALL.ToString(), path, (obj) =>
// {
// if (obj == null)
// {
// callback(null);
// return;
// }
// //todo
//// TextAsset textAss = obj as TextAsset;
//// callback(textAss.text);
// });
}
// /// <summary>
// /// 通过指定资源名称加载AssetBundle中的Text资源
// /// </summary>
// /// <param name="resName"></param>
// /// <param name="callback"></param>
// public static void LoadByteArrayByName(string resName, Action<byte[]> callback)
// {
// AssetLoader loader = AssetLoader.Instance;
// string path = loader.GetAssetPath(resName);
// //todo
//// LoadTextAtPath(path, callback);
// }
/// <summary>
/// 加载场景资源
/// </summary>
/// <param name="sceneName">场景的名称</param>
/// <param name="callback">场景实例完成的回调</param>
public static IEnumerator LoadScene(string sceneName, Action<GameObject> callback , Action<float, float> progress)
{
if (!sceneName.EndsWith(".prefab")) sceneName += ".prefab";
return Instance.SwapAssetByName<UnityEngine.Object>(EAssetType.ALL.ToString(), sceneName, EAssetType.Scene, (obj) =>
{
if (obj == null)
{
if(callback != null) callback.Invoke(null);
return;
}
//查找当前场景的场景结点,进行删除
PrefabLightmapData curScene = GameObject.FindObjectOfType<PrefabLightmapData>();
if (curScene != null)
{
#if UNITY_EDITOR
GameObject.DestroyImmediate(curScene.gameObject);
#else
GameObject.Destroy(curScene.gameObject);
#endif
}
//实例新场景
GameObject gObj = GameObject.Instantiate(obj) as GameObject;
if (callback != null) callback.Invoke(gObj);
} , progress);
}
#endregion
#region ----------私有方法---------------
/// <summary>
/// 获得CachePool池
/// </summary>
/// <param name="poolName">池的名称</param>
/// <returns>如果不存在指定池,则返回null</returns>
private ARCCache<string, Asset> getCachePool(string poolName)
{
if (!bundlePoolCache.ContainsKey(poolName)) return null;
return bundlePoolCache[poolName];
}
/// <summary>
/// 从缓存链中获取一个指定名称的缓存池
/// </summary>
/// <param name="poolName">池的名称</param>
/// <param name="cacheCount">缓存池的大小</param>
/// <returns>如果缓存链中不存在,则默认会创建</returns>
private ARCCache<string, Asset> swapnCachePool(string poolName , int cacheCount = 10)
{
if (bundlePoolCache.ContainsKey(poolName)) return bundlePoolCache[poolName];
ARCCache<string , Asset> cache = new ARCCache<string, Asset>(cacheCount);
//释放清理
cache.DestroyCallback = bundle =>
{
bundle.Value.Unload(false);
Resources.UnloadUnusedAssets();
System.GC.Collect();
};
bundlePoolCache[poolName] = cache;
return cache;
}
/// <summary>
/// 加载AssetBundle及其依赖的资源
/// </summary>
/// <param name="cachePool">缓存池</param>
/// <param name="bundleName">目标AssetBundle资源</param>
/// <param name="callback">最终的资源加载完成时的回调</param>
/// <returns></returns>
private IEnumerator loadBundleAndDependenices(ARCCache<string, Asset> cachePool , string bundleName ,
Action<AssetBundle> callback, Action<float, float> progress)
{
string[] depAssetArr = manifest.GetAllDependencies(bundleName);
foreach (string depAsset in depAssetArr)
{
//重新获取Bundle名,因为可能依赖的名称内带有目录信息
string depBundleName = Path.GetFileName(depAsset);
yield return AppInter.StartCoroutine(AsyncLoadBundleAtPath(depBundleName, (obj) =>
{
if (obj != null)
{
Asset asset = new Asset(depBundleName, obj);
cachePool.Put(depBundleName, asset);
}
}));
}
yield return AppInter.StartCoroutine(AsyncLoadBundleAtPath(bundleName, callback , progress));
}
private IEnumerator loadBundleAndDependenices(ARCCache<string, Asset> cachePool, string bundleName,
Action<AssetBundle> callback)
{
return loadBundleAndDependenices(cachePool, bundleName, callback, null);
}
#endregion
#region -----------公共访问方法---------------------
/// <summary>
/// 异步加载资源
/// </summary>
/// <param name="path">资源的相对路径,相对于Assets的根目录 eg: CustomRes/XXX.prefab</param>
/// <param name="assetType">其它的基础数据类型</param>
/// <param name="callback">加载完成时的回调</param>
/// <returns></returns>
public IEnumerator AsyncLoadAtPath(string path ,EAssetBaseType assetType , Action<object> callback)
{
string finalPath = AppPathUtils.IsSeachExist(path , true);
WWW _www = new WWW(finalPath);
yield return _www;
if (_www.error != null)
{
Debugger.LogError(_www.error + " , path -->> " + finalPath);
callback(null);
yield break;
}
object obj = null;
if (assetType == EAssetBaseType.Text)
{
obj = _www.text;
}else if (assetType == EAssetBaseType.ByteArray)
{
obj = _www.bytes;
}else if (assetType == EAssetBaseType.Texture2D)
obj = _www.texture;
if(callback != null) callback(obj);
}
/// <summary>
/// 异步加载资源
/// </summary>
/// <param name="bundName">未加密的Bundle文件名</param>
/// <param name="callback">加载完成时的回调</param>
public IEnumerator AsyncLoadBundleAtPath(string bundName, Action<AssetBundle> callback, Action<float, float> progress)
{
string finalPath = AppPathUtils.IsSeachExist(GetBundleEncrypeName(bundName), true);
WWW _www = new WWW(finalPath);
if (progress == null)
yield return _www;
else
{
int totalProgress = 0, curTotalProgress;
int offset = 0;
while (!_www.isDone)
{
curTotalProgress = (int)(_www.progress * 100);
offset = curTotalProgress - totalProgress;
totalProgress = curTotalProgress;
progress.Invoke(offset, totalProgress);
yield return null;
}
curTotalProgress = totalProgress == 0 ? (int)(_www.progress * 100) : totalProgress;
offset = 100 - curTotalProgress;
totalProgress = 100;
progress.Invoke(offset, totalProgress);
while (curTotalProgress < totalProgress)
{
curTotalProgress++;
yield return null;
}
yield return null;
}
if (_www.error != null)
{
Debugger.LogError(_www.error + " , path -->> " + finalPath);
callback(null);
yield break;
}
if (callback != null) callback(_www.assetBundle);
}
public IEnumerator AsyncLoadBundleAtPath(string bundName, Action<AssetBundle> callback)
{
return AsyncLoadBundleAtPath(bundName, callback, null);
}
/// <summary>
/// 加载资源
/// </summary>
/// <param name="resName">资源的名称 eg:res01.prefab</param>
public void AsyncLoadBundleByName(string resName, EAssetType assetType , Action<AssetBundle> callback)
{
string finalName = GetBundleName(resName , assetType);
if (string.IsNullOrEmpty(finalName))
{
Debugger.LogWarning("<<AssetLoader , SwapAssetByName>> Cant find file ! name :--->> " + resName + " , bundle :" + finalName);
if (callback != null)
callback(null);
return;
}
AppInter.StartCoroutine(AsyncLoadBundleAtPath(finalName, callback , null));
}
#region -----------Swap----------------
// /// <summary>
// /// 从缓存中获取资源
// /// </summary>
// /// <param name="poolName">缓存池的名称</param>
// /// <param name="path">资源相对路径</param>
// /// <param name="callback">加载完成的回调</param>
// public void SwapAssetAtPath(string poolName , string path , Action<UnityEngine.Object> callback)
// {
// ARCCache<string, AssetBundle> cachePool = swapnCachePool(poolName);
// AssetBundle bundle = cachePool.Get(path);
// if (bundle != null)
// {
// if (callback != null)
// callback(bundle.mainAsset);
// return;
// }
//
// //异步加载
// AppInter.StartCoroutine(AsyncLoadAtPath(path,EAssetBaseType.AssetBundle, (obj) =>
// {
// bundle = obj as AssetBundle;
// if (bundle == null)
// {
// Debugger.LogWarning("<<AssetLoader , SwapAsset>> load faile ! Path -->> " + path);
// return;
// }
// cachePool.Put(path , bundle);
//
// if(callback != null)
// callback(bundle.mainAsset);
// }));
// }
/// <summary>
/// 从AssetBundle缓存中获取资源
/// </summary>
/// <param name="poolName">缓存池的名称</param>
/// <param name="resName">资源名</param>
/// <param name="callback">加载完成的回调</param>
public IEnumerator SwapAssetByName<T>(string poolName, string resName, EAssetType assetType,
Action<UnityEngine.Object> callback , Action<float, float> progress)
where T : UnityEngine.Object
{
ARCCache<string, Asset> cachePool = swapnCachePool(poolName);
string bundleName = GetBundleName(resName, assetType);
if (string.IsNullOrEmpty(bundleName))
{
callback.Invoke(null);
Debugger.LogWarning("<<AssetLoader , SwapAssetByName>> load faile ! Res -->> " + resName);
yield break;
}
Asset bundle = cachePool.Get(bundleName);
#if UNITY_EDITOR
if (!isBundle)
{
if (bundle == null)
{
string path = GetBundleEncrypeName(resName + assetType.ToString().ToLower());
UnityEngine.Object obj = AssetDatabase.LoadAssetAtPath<T>(path);
if (obj == null)
{
Debugger.LogWarning("<<AssetLoader , SwapAssetByName>> load faile ! Path -->> " + path);
callback.Invoke(obj);
yield break;
}
bundle = new Asset(bundleName, obj);
cachePool.Put(bundleName, bundle);
}
callback.Invoke(bundle.Resource);
yield break;
}
#endif
if (bundle != null)
{
if (callback != null)
callback(bundle.Get<AssetBundle>().LoadAsset<T>(resName));
yield break;
}
//异步加载
yield return AppInter.StartCoroutine(loadBundleAndDependenices(cachePool , bundleName, (obj) =>
{
if (obj == null)
{
Debugger.LogWarning("<<AssetLoader , SwapAssetByName>> load faile ! Path -->> " + bundleName);
callback.Invoke(null);
return;
}
Asset asset = new Asset(bundleName , obj);
cachePool.Put(bundleName, asset);
if (callback != null)
callback(obj.LoadAsset<T>(resName));
} , progress));
}
public IEnumerator SwapAssetByName<T>(string poolName, string resName, EAssetType assetType,Action<UnityEngine.Object> callback)
where T : UnityEngine.Object
{
return SwapAssetByName<T>(poolName , resName , assetType , callback , null);
}
#endregion
/// <summary>
/// 初始化预加载
/// </summary>
public IEnumerator InitPreLoad(Action finish)
{
bool isFinishMap = false;
string assetMapName = (!isBundle ? "dev" : "") + AppPathUtils.AssetBundleMap;
yield return AppInter.StartCoroutine(AsyncLoadAtPath(assetMapName, EAssetBaseType.Text, (obj) =>
{
string[] assetArr = ((string) obj).Split('\n');
int chunkIndex = 0;
foreach (string assetInfo in assetArr)
{
string asset = assetInfo.Trim();
if(string.IsNullOrEmpty(asset)) continue;
if (asset == AppPathUtils.AssetForMap)
{
chunkIndex = 1;
continue;
}
string[] fileInfos = asset.Split(';');
string assetType = fileInfos[0];
string fileName = Path.GetFileName(fileInfos[1]); //去掉目录
fileName = fileName.Replace("." , "_" + assetType + ".");
if (chunkIndex == 0)
{
if(isBundle)
nameToPathMap[fileName] = fileInfos[2]; //fileInfos[2] -> Md5值
else
{
string srcfileName = Path.GetFileName(fileInfos[2]);
nameToPathMap[srcfileName + assetType] = fileInfos[2];
}
}else if (chunkIndex == 1)
{
string bundleName = Path.GetFileName(fileInfos[2]); //去掉目录
pathToBundleMap[fileName] = bundleName;
}
}
isFinishMap = true;
}));
while (!isFinishMap) yield return null;
if (isBundle)
{
//加载assetBundleManifest
yield return AppInter.StartCoroutine(AsyncLoadBundleAtPath("bin_none" + AppPathUtils.BundleSuffix, (bundle) =>
{
if (bundle != null)
{
Debugger.LogWarning("<<AssetLoader , InitPreLoad>> Cant find AssetBundleManifest");
return;
}
manifest = bundle.LoadAsset<AssetBundleManifest>("AssetBundleManifest");
}) );
}
if(finish != null) finish.Invoke();
Debugger.Log("AssetLoader , InitPreload is finish ");
}
/// <summary>
/// 获得对应资源所在的Bundle名称
/// </summary>
/// <param name="resName"></param>
/// <returns>返回未加密的Bundle名称</returns>
public string GetBundleName(string resName , EAssetType assetType)
{
string finalName = resName.Replace(".", "_" + assetType.ToString().ToLower() + ".");
if (!isBundle)
{
//如果是开发者非Bundle模式,则直接返回最终名
return finalName;
}
if (!this.pathToBundleMap.ContainsKey(finalName))
{
Debugger.LogWarning("<<AssetLoader , GetBundleName>> Cant find file ! name :--->> " + resName + " ,bundle : " + finalName);
return null;
}
return pathToBundleMap[finalName];
}
/// <summary>
/// 获得加密后的Bundle名称
/// </summary>
/// <param name="resName"></param>
/// <param name="assetType"></param>
/// <returns></returns>
public string GetBundleEncrypeName(string resName, EAssetType assetType)
{
string finalName = GetBundleName(resName, assetType);
if (string.IsNullOrEmpty(finalName)) return null;
return GetBundleEncrypeName(finalName);
}
/// <summary>
/// 获得加密后的Bundle名称
/// </summary>
/// <param name="bundleName">未加密的Bundle文件名</param>
public string GetBundleEncrypeName(string bundleName)
{
if (!nameToPathMap.ContainsKey(bundleName))
{
Debugger.LogWarning("<<AssetLoader , GetBundleEncrypeName>> Cant find file ! name :--->> " + bundleName);
return null;
}
return nameToPathMap[bundleName];
}
/// <summary>
/// 获得Bundle所有的依赖
/// </summary>
/// <param name="bundleName"></param>
/// <returns></returns>
public string[] GetAllDependencies(string bundleName)
{
return manifest.GetAllDependencies(bundleName);
}
#endregion
#region ----------内部类----------------
/// <summary>
/// 资源信息封装
/// </summary>
private class Asset
{
public string Name;
public string Path;
public UnityEngine.Object Resource;
public Asset(string path, UnityEngine.Object obj)
{
Init(path , obj);
}
public void Init(string path, UnityEngine.Object obj)
{
Path = path;
Name = System.IO.Path.GetFileNameWithoutExtension(path);
Resource = obj;
}
public T Get<T>() where T : UnityEngine.Object
{
try
{
return (T) Resource;
}
catch (Exception)
{
}
return default(T);
}
public void Unload(bool force)
{
AssetBundle bundle = Get<AssetBundle>();
if (bundle != null)
{
bundle.Unload(force);
return;
}
#if UNITY_EDITOR
GameObject.DestroyImmediate(Resource);
#else
GameObject.Destroy(Resource);
#endif
}
}
#endregion
}
<file_sep>/Assets/GameScript/Lua/Test/SocketTest.lua
require "Common.functions"
require ("Net/init")
SocketTest = {}
function SocketTest:OnStart()
NetClient:setIp("192.168.21.81",10102)
GameNet:startNetClient()
print("net test ##########################################################################")
local req = NetProtoUser.SendVisitorLogin:new()
req.userName = "abc"
req.password = "<PASSWORD>"
req:send(function(AccountVO)
print(AccountVO.accountName)
end)
end
<file_sep>/Assets/GameScript/Lua/Test/LoaderTest.lua
--[[
Author: LiangZG
Email : <EMAIL>
]]
require "Common.functions"
--[[
资源加载测试
]]
LoaderTest = {}
local this = LoaderTest
--入口
function LoaderTest:Start()
AssetLoader.isBundle = false
LuaAssetLoader.OnInitPreload(nil)
end
--主应用释放
function LoaderTest:OnGUI()
if GUILayout.Button("Clear" , GUILayout.Height(30)) then
if this.target ~= nil then
GameObject.Destroy(this.target)
end
end
--直接传递匿名luaFunction测试 , 结果成功
if GUILayout.Button("Anon LuaFunction Callback" , GUILayout.Height(30)) then
LuaAssetLoader.LoadGameObject("GO1.prefab" , function(obj)
this.target = obj
if obj then
print("game name is " .. obj.name)
else
print("game object is nil ~~~")
end
end)
end
--传递Function 字符名称 , 结果成功
if GUILayout.Button("Function String Callback" , GUILayout.Height(30)) then
LuaAssetLoader.LoadGameObject("GO1.prefab" , "LoaderTest.LoadFinish")
end
--传递luaFunction测试 , 结果成功
if GUILayout.Button("Function Callback" , GUILayout.Height(30)) then
LuaAssetLoader.LoadGameObject("GO1.prefab" , LoaderTest.LoadFinish)
end
end
function LoaderTest.LoadFinish(obj)
this.target = obj
if obj then
print("game name is " .. obj.name)
else
print("game object is nil ~~~")
end
end<file_sep>/Assets/GameScript/Lua/Test/Util/ParallelTaskTest.lua
local ParallelTaskTest = class("ParallelTaskTest")
function ParallelTaskTest:Start ()
self.i = 0
local pt = ParallelTaskCollection.new()
local st = SerialTaskCollection.new()
st:add(handler(self , self.Print ) , "s1");
st:add(handler(self , self.DoSomethingAsynchonously))
st:add(handler(self , self.Print) , "s3")
pt:add(handler(self , self.Print) ,"1")
pt:add(handler(self , self.Print) ,"2")
pt:add(handler(self , self.Print) ,"3")
pt:add(handler(self , self.Print) ,"4")
pt:add(handler(self , self.Print) ,"5")
pt:add(st)
pt:add(handler(self , self.Print) ,"6")
pt:add(self.WWWTest)
pt:add(handler(self , self.Print) ,"7")
pt:add(handler(self , self.Print) ,"8")
TaskRunner.run(pt:getEnumerator())
end
function ParallelTaskTest:Print(i)
Debugger.Log(i);
coroutine.step()
end
function ParallelTaskTest:DoSomethingAsynchonously() --this can be awfully slow, I suppose it is synched with the frame rate
for i = 0, 500 do
self.i = i
coroutine.step()
end
Debugger.Log("index " .. self.i);
end
function ParallelTaskTest:WWWTest()
local www = WWW("www.baidu.com");
coroutine.www(www)
Debugger.Log("www done:" .. www.text);
end
local test = ParallelTaskTest.new()
test:Start()
return ParallelTaskTest<file_sep>/Assets/GameScript/UISystem/UIPageRoot.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using System;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class UIPageRoot : Singleton<UIPageRoot>
{
private static Vector2 screenResolution = new Vector2(1280 , 720);
public Transform root;
public Transform fixedRoot;
public Transform normalRoot;
public Transform popupRoot;
public Camera uiCamera;
private int offsetOrder = 50; //界面深度偏移值
private Vector2 normalRange = new Vector2(500, 1500);
private int normalOrder;
private Vector2 popupRange = new Vector2(1600 , 2000);
private int popupOrder;
protected override void Awake()
{
base.Awake();
initRoot();
}
private void initRoot()
{
GameObject go = new GameObject("UIRoot");
go.layer = LayerMask.NameToLayer("UI");
go.AddComponent<RectTransform>();
GameObject camObj = new GameObject("UICamera");
camObj.layer = LayerMask.NameToLayer("UI");
camObj.transform.parent = go.transform;
camObj.transform.localPosition = new Vector3(0,0,-100f);
Camera cam = camObj.AddComponent<Camera>();
cam.clearFlags = CameraClearFlags.Depth;
cam.orthographic = true;
cam.farClipPlane = 200f;
uiCamera = cam;
cam.cullingMask = 1<<5;
cam.nearClipPlane = -50f;
cam.farClipPlane = 50f;
// Canvas can = go.AddComponent<Canvas>();
// can.renderMode = RenderMode.ScreenSpaceCamera;
// can.pixelPerfect = true;
// can.worldCamera = cam;
//add audio listener
camObj.AddComponent<AudioListener>();
camObj.AddComponent<GUILayer>();
// CanvasScaler cs = go.AddComponent<CanvasScaler>();
// cs.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
// cs.referenceResolution = screenResolution;
// cs.screenMatchMode = CanvasScaler.ScreenMatchMode.Expand;
GameObject subRoot = CreateSubCanvasForRoot(go.transform,250);
subRoot.name = "FixedRoot";
fixedRoot = subRoot.transform;
subRoot = CreateSubCanvasForRoot(go.transform,0);
subRoot.name = "NormalRoot";
normalRoot = subRoot.transform;
subRoot = CreateSubCanvasForRoot(go.transform,500);
subRoot.name = "PopupRoot";
popupRoot = subRoot.transform;
//add Event System
GameObject eventObj = GameObject.Find("EventSystem");
if(eventObj == null)
{
eventObj = new GameObject("EventSystem");
eventObj.AddComponent<EventSystem>();
eventObj.AddComponent<UnityEngine.EventSystems.StandaloneInputModule>();
}
eventObj.layer = LayerMask.NameToLayer("UI");
eventObj.transform.SetParent(go.transform);
//初始化排序
normalOrder = (int)normalRange.x;
}
static GameObject CreateSubCanvasForRoot(Transform root,int sort)
{
GameObject go = new GameObject("canvas");
go.transform.parent = root;
go.layer = LayerMask.NameToLayer("UI");
go.transform.localPosition = Vector3.zero;
go.transform.localScale = Vector3.one;
go.transform.localRotation = Quaternion.identity;
// Canvas can = go.AddComponent<Canvas>();
// RectTransform rect = go.GetComponent<RectTransform>();
// rect.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Left, 0, 0);
// rect.SetInsetAndSizeFromParentEdge(RectTransform.Edge.Top, 0, 0);
// rect.anchorMin = Vector2.zero;
// rect.anchorMax = Vector2.one;
//
// can.overrideSorting = true;
// can.sortingOrder = sort;
//
// go.AddComponent<GraphicRaycaster>();
return go;
}
/// <summary>
/// 获得对应Page类型的Root
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public Transform GetRoot(EPageType type)
{
if(type == EPageType.Fixed) return fixedRoot;
if(type == EPageType.Normal) return normalRoot;
if(type == EPageType.PopUp) return popupRoot;
return root;
}
/// <summary>
/// 增加Normal类型的界面显示序号
/// </summary>
/// <returns></returns>
public int AddOrder(EPageType pageType)
{
switch (pageType)
{
case EPageType.Normal:
normalOrder = (int)Mathf.Clamp(normalOrder + offsetOrder, normalRange.x, normalRange.y);
return normalOrder;
case EPageType.PopUp:
popupOrder = (int)Mathf.Clamp(popupOrder + offsetOrder, popupRange.x, popupRange.y);
return popupOrder;
}
Debug.LogError("固定类型的页界,不进行深度自动排序");
return 0;
}
/// <summary>
/// 减小Normal类型的界面显示序号
/// </summary>
/// <returns></returns>
public int SubOrder(EPageType pageType)
{
switch (pageType)
{
case EPageType.Normal:
normalOrder = (int)Mathf.Clamp(normalOrder - offsetOrder, normalRange.x, normalRange.y);
return normalOrder;
case EPageType.PopUp:
popupOrder = (int)Mathf.Clamp(popupOrder - offsetOrder, popupRange.x, popupRange.y);
return popupOrder;
}
Debug.LogError("固定类型的页界,不进行深度自动排序");
return 0;
}
}
<file_sep>/Assets/GameScript/Lua/UnityEngines.lua
--[[
此脚本用来导入UniyEngine生成的Wrap映射对象
]]
object = System.Object
Type = System.Type
Object = UnityEngine.Object
GameObject = UnityEngine.GameObject
Transform = UnityEngine.Transform
MonoBehaviour = UnityEngine.MonoBehaviour
Component = UnityEngine.Component
Application = UnityEngine.Application
SystemInfo = UnityEngine.SystemInfo
Screen = UnityEngine.Screen
Camera = UnityEngine.Camera
Material = UnityEngine.Material
Renderer = UnityEngine.Renderer
AsyncOperation = UnityEngine.AsyncOperation
CharacterController = UnityEngine.CharacterController
SkinnedMeshRenderer = UnityEngine.SkinnedMeshRenderer
Animation = UnityEngine.Animation
AnimationClip = UnityEngine.AnimationClip
AnimationEvent = UnityEngine.AnimationEvent
AnimationState = UnityEngine.AnimationState
Input = UnityEngine.Input
KeyCode = UnityEngine.KeyCode
AudioClip = UnityEngine.AudioClip
AudioSource = UnityEngine.AudioSource
Physics = UnityEngine.Physics
Collider = UnityEngine.Collider
Light = UnityEngine.Light
LightType = UnityEngine.LightType
ParticleEmitter = UnityEngine.ParticleEmitter
Space = UnityEngine.Space
CameraClearFlags = UnityEngine.CameraClearFlags
RenderSettings = UnityEngine.RenderSettings
MeshRenderer = UnityEngine.MeshRenderer
WrapMode = UnityEngine.WrapMode
QueueMode = UnityEngine.QueueMode
PlayMode = UnityEngine.PlayMode
ParticleAnimator = UnityEngine.ParticleAnimator
TouchPhase = UnityEngine.TouchPhase
AnimationBlendMode = UnityEngine.AnimationBlendMode
PlayerPrefs = UnityEngine.PlayerPrefs
WWW = UnityEngine.WWW
AssetBundle = UnityEngine.AssetBundle
Resources = UnityEngine.Resources
GC = System.GC
AudioSource = UnityEngine.AudioSource
SceneManager = UnityEngine.SceneManagement.SceneManager
AssetBundleManifest = UnityEngine.AssetBundleManifest
AssetBundleRequest = UnityEngine.AssetBundleRequest
TextAsset = UnityEngine.TextAsset
Profiler = UnityEngine.Profiler
SpriteRenderer = UnityEngine.SpriteRenderer
Sprite = UnityEngine.Sprite
BoxCollider = UnityEngine.BoxCollider
BoxCollider2D = UnityEngine.BoxCollider2D
RectTransformUtility = UnityEngine.RectTransformUtility
--UGUI
Image = UnityEngine.UI.Image
RectTransform = UnityEngine.RectTransform
Rect = UnityEngine.Rect
Text = UnityEngine.UI.Text
Button = UnityEngine.UI.Button
RenderMode = UnityEngine.RenderMode
Canvas = UnityEngine.Canvas
CanvasGroup = UnityEngine.CanvasGroup
GraphicRaycaster = UnityEngine.UI.GraphicRaycaster
ScrollRect = UnityEngine.UI.ScrollRect
InputField = UnityEngine.UI.InputField
InputField = UnityEngine.UI.InputField
AudioType = UnityEngine.AudioType
ColorBlock = UnityEngine.UI.ColorBlock
Outline = UnityEngine.UI.Outline
Slider = UnityEngine.UI.Slider
Toggle = UnityEngine.UI.Toggle
LayoutUtility = UnityEngine.UI.LayoutUtility
VerticalLayoutGroup = UnityEngine.UI.VerticalLayoutGroup
GridLayoutGroup = UnityEngine.UI.GridLayoutGroup
Scrollbar = UnityEngine.UI.Scrollbar
TextAnchor = UnityEngine.TextAnchor
Dropdown = UnityEngine.UI.Dropdown
GUILayout = UnityEngine.GUILayout<file_sep>/Assets/GEngineScript/Core/SceneManager/ASceneTransition.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using System.Collections;
using GEX.Resource;
using GEX.SceneManager;
using UnityEngine;
namespace GOE.Scene
{
/// <summary>
/// 描述:场景过滤基类
/// <para>创建时间:2016-06-15</para>
/// </summary>
public abstract class ASceneTransition : MonoBehaviour
{
protected SMTransitionState state = SMTransitionState.Out;
public StageLoader Loader;
/// <summary>
/// Gets the current state of the transition. This is read-only, as the state is controlled by the transition
/// framework.
/// </summary>
/// <remarks>@since version 1.4.5</remarks>
public SMTransitionState CurrentTransitionState
{
get
{
return state;
}
}
public bool timeScaleIndependent = true;
// Prefetching needs Unity 4 therefore we hide it in Unity 3.5
public bool prefetchLevel = false;
/// <summary>
/// The id of the screen that is being loaded.
/// </summary>
[HideInInspector]
public string screenName;
protected SceneStageManager sceneStageMgr;
void Start()
{
sceneStageMgr = SceneStageManager.Instance;
Loader = sceneStageMgr.stageLoader;
if (Time.timeScale <= 0f && !timeScaleIndependent)
{
Debug.LogWarning("Time.timeScale is set to 0 and you have not enabled 'Time Scale Independent' at the transition prefab. " +
"Therefore the transition animation would never start to play. Please either check the 'Time Scale Independent' checkbox" +
"at the transition prefab or set Time.timeScale to a positive value before changing the level.", this);
return; // do not do anything in this case.
}
if (prefetchLevel)
{
Debug.LogWarning("You can only prefetch the level when using asynchronous loading. " +
"Please either uncheck the 'Prefetch Level' checkbox on your level transition prefab or check the " +
"'Load Async' checkbox. Note, that asynchronous loading (and therefore level prefetching) requires a Unity Pro license.", this);
return; // don't do anything in this case.
}
StartCoroutine(DoTransition());
}
/// <summary>
/// This method actually does the transition. It is run in a coroutine and therefore needs to do
/// yield returns to play an animation or do another progress over time. When this method returns
/// the transition is expected to be finished.
/// </summary>
/// <returns>
/// A <see cref="IEnumerator"/> for showing the transition status. Use yield return statements to keep
/// the transition running, otherwise simply end the method to stop the transition.
/// </returns>
protected virtual IEnumerator DoTransition()
{
// make sure the transition doesn't get lost when switching the level.
DontDestroyOnLoad(gameObject);
if (prefetchLevel)
{
state = SMTransitionState.Prefetch;
SendMessage("SMBeforeTransitionPrefetch", this, SendMessageOptions.DontRequireReceiver);
yield return 0; // wait one frame
SendMessage("SMOnTransitionPrefetch", this, SendMessageOptions.DontRequireReceiver);
if (Loader != null)
{
while (Loader.MoveNext())
{
yield return 0;
}
}
}
state = SMTransitionState.Out;
SendMessage("SMBeforeTransitionOut", this, SendMessageOptions.DontRequireReceiver);
Prepare();
SendMessage("SMOnTransitionOut", this, SendMessageOptions.DontRequireReceiver);
float time = 0;
while (Process(time))
{
time += DeltaTime;
// wait for the next frame
yield return 0;
}
SendMessage("SMAfterTransitionOut", this, SendMessageOptions.DontRequireReceiver);
// wait another frame...
yield return 0;
state = SMTransitionState.Hold;
SendMessage("SMBeforeTransitionHold", this, SendMessageOptions.DontRequireReceiver);
SendMessage("SMOnTransitionHold", this, SendMessageOptions.DontRequireReceiver);
// wait another frame...
yield return 0;
if (!prefetchLevel && Loader != null)
{
// level is not prefetched, load it right now.
while (Loader.MoveNext())
{
yield return 0;
}
}
SendMessage("SMAfterTransitionHold", this, SendMessageOptions.DontRequireReceiver);
// wait another frame...
yield return 0;
state = SMTransitionState.In;
SendMessage("SMBeforeTransitionIn", this, SendMessageOptions.DontRequireReceiver);
Prepare();
SendMessage("SMOnTransitionIn", this, SendMessageOptions.DontRequireReceiver);
time = 0;
while (Process(time))
{
time += DeltaTime;
// wait for the next frame
yield return 0;
}
sceneStageMgr.OnCompleted();
SendMessage("SMAfterTransitionIn", this, SendMessageOptions.DontRequireReceiver);
// wait another frame...
yield return 0;
Destroy(gameObject);
}
/// <summary>
/// invoked at the start of the <see cref="SMTransitionState.In"/> and <see cref="SMTransitionState.Out"/> state to
/// initialize the transition
/// </summary>
protected virtual void Prepare()
{
}
/// <summary>
/// Invoked once per frame while the transition is in state <see cref="SMTransitionState.In"/> or <see cref="SMTransitionState.Out"/>
/// to calculate the progress
/// </summary>
/// <param name='elapsedTime'>
/// the time that has elapsed since the start of current transition state in seconds.
/// </param>
/// <returns>
/// false if no further calls are necessary for the current state, true otherwise
/// </returns>
protected abstract bool Process(float elapsedTime);
/// <summary>
/// Gets the delta time according to the settings. If realTimeScaling is enabled, the time scale will not affect
/// the speed at which the transition is playing. Otherwise a change to the time scale will affect the speed
/// at which transitions are played.
/// </summary>
/// <value>The delta time.</value>
protected virtual float DeltaTime
{
get
{
if (timeScaleIndependent)
{
return SMRealTimeHelper.deltaTime;
}
else {
return Time.deltaTime;
}
}
}
}
}
<file_sep>/Assets/Editor/SceneManagerEditor/Strategy/PreFileStrategy.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// 描述:逐文件策略
/// <para>创建时间:2016-06-24</para>
/// </summary>
public class PreFileStrategy : IStrategy {
public void BeginProcess(BuildConfig buildConfig)
{
string absolutionPath = Path.Combine(Application.dataPath, buildConfig.InputDir);
string[] findFile = buildConfig.FileSuffixs.Split('|');
//查找目录文件
List<string> files = new List<string>();
foreach (string fileSuffix in findFile)
{
string[] fileArr = Directory.GetFiles(absolutionPath, fileSuffix, buildConfig.OptionSerach);
files.AddRange(fileArr);
}
//分配文件Bundle
foreach (string filePath in files)
{
if(filePath.EndsWith(BuildGlobal.Meta)) continue;
string fileName = Path.GetFileNameWithoutExtension(filePath);
string relativePath = filePath.Replace("\\", "/");
relativePath = relativePath.Replace(Application.dataPath, "Assets");
AssetBuildEditor.Instance.AssignBundle(fileName, relativePath, fileName);
}
}
public void EndProcess(BuildConfig buildConfig)
{
Debugger.Log("<<PreFileStrategy>> End ! build config name is " + buildConfig.BundleName);
}
}
<file_sep>/Assets/GEngineScript/Utility/AppPathUtils.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using UnityEngine;
using System.Collections;
using System.IO;
using GEX;
/// <summary>
/// 描述:应用路径工具集
/// <para>创建时间:2016-06-25</para>
/// </summary>
public sealed class AppPathUtils
{
public const string AssetBundleMap = "00000016c800000000e8d5d000000000.txt";
public const string AssetForMap = "AssetForBundle:";
public const string BundleSuffix = ".assetsbundle";
/// <summary>
/// 使用WWW加载时,使用的持久化目录
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string WWWPathFormat(string path)
{
#if UNITY_EDITOR
return "file:///" + PersistentDataRootPath + path;
#elif UNITY_ANDROID || UNITY_IPHONE
return "file://" + PersistentDataRootPath + path;
#endif
}
/// <summary>
/// 使用WWW加载时,使用的StreamingAsset目录
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string StreamingPathFormat(string path)
{
using (zstring.Block())
{
#if UNITY_EDITOR
if (AppConst.BundleDebugMode)
return zstring.Format("file:///{0}", Application.dataPath + "/AssetBundle");
else
return zstring.Format("file:///{0}", Application.streamingAssetsPath);
#elif UNITY_ANDROID
//return zstring.Format("jar:file://{0}!/assets/", Application.dataPath);
return string.Concat("jar:file://" , Application.streamingAssetsPath , "/" , path);
#elif UNITY_IOS
//return zstring.Format("file://{0}/Raw/", Application.dataPath);
return string.Concat("file://" , Application.streamingAssetsPath , "/" , path);
#endif
return zstring.Format("file:///{0}", Application.streamingAssetsPath);
}
}
/// <summary>
/// 外部持久化根目录
/// </summary>
public static string PersistentDataRootPath
{
get
{
#if UNITY_EDITOR
string pathAll = Path.Combine(Application.dataPath, "../../AppResBin/");
pathAll = Path.GetFullPath(pathAll);
return pathAll;
#elif UNITY_ANDROID || UNITY_IPHONE
return Application.persistentDataPath;
#endif
}
}
/// <summary>
/// 搜索文件是否存在,优先搜索外部目录
/// </summary>
/// <param name="path"></param>
/// <param name= "isWWW">是否使用WWW加载</param>
/// <returns>默认返回沙盒目录</returns>
public static string IsSeachExist(string path , bool isWWW)
{
string persistendPath = Path.Combine(PersistentDataRootPath, path);
if(File.Exists(persistendPath))
return isWWW ? WWWPathFormat(path) : persistendPath;
return isWWW ? StreamingPathFormat(path) : string.Concat(Application.streamingAssetsPath, "/", path);
}
}
<file_sep>/Assets/Libs/ToLua/Lua/System/coroutine.lua
--------------------------------------------------------------------------------
-- Copyright (c) 2015 - 2016 , 蒙占志(topameng) <EMAIL>
-- All rights reserved.
-- Use, modification and distribution are subject to the "MIT License"
--------------------------------------------------------------------------------
local create = coroutine.create
local running = coroutine.running
local resume = coroutine.resume
local yield = coroutine.yield
local error = error
local unpack = unpack
local debug = debug
local FrameTimer = FrameTimer
local CoTimer = CoTimer
local comap = {}
setmetatable(comap, {__mode = "kv"})
function coroutine.start(f, ...)
local co = create(f)
if running() == nil then
local flag, msg = resume(co, ...)
if not flag then
msg = debug.traceback(co, msg)
error(msg)
end
else
local args = {...}
local timer = nil
local action = function()
local flag, msg = resume(co, unpack(args))
if not flag then
timer:Stop()
msg = debug.traceback(co, msg)
error(msg)
end
end
timer = FrameTimer.New(action, 0, 1)
comap[co] = timer
timer:Start()
end
return co
end
function coroutine.wait(t, co, ...)
local args = {...}
co = co or running()
local timer = nil
local action = function()
local flag, msg = resume(co, unpack(args))
if not flag then
timer:Stop()
msg = debug.traceback(co, msg)
error(msg)
return
end
end
timer = CoTimer.New(action, t, 1)
comap[co] = timer
timer:Start()
return yield()
end
function coroutine.step(t, co, ...)
local args = {...}
co = co or running()
local timer = nil
local action = function()
local flag, msg = resume(co, unpack(args))
if not flag then
timer:Stop()
msg = debug.traceback(co, msg)
error(msg)
return
end
end
timer = FrameTimer.New(action, t or 1, 1)
comap[co] = timer
timer:Start()
return yield()
end
--用于多层协同嵌套
--eg:
-- function onA()
-- print("a start")
-- coroutine.next(onB)
-- print("a end")
-- end
-- function onB()
-- print("b start")
-- coroutine.next(onC)
-- print("b end")
-- end
-- function onC()
-- print("c")
-- end
-- coroutine.start(onA)
-- --->output:
-- a start
-- b start
-- c
-- b end
-- a end
function coroutine.next( f , ... )
local curCo = running()
assert(curCo)
if comap[curCo] then
comap[curCo]:Stop()
end
local timer = nil
local co = nil
local action = function()
local state = coroutine.status(co)
if state ~= "dead" then return end
timer:Stop()
local flag, msg = resume(curCo)
if not flag then
msg = debug.traceback(curCo, msg)
error(msg)
end
end
timer = FrameTimer.New(action, 1, -1)
comap[curCo] = timer
timer:Start()
co = coroutine.start(f , unpack({...}))
return yield()
end
function coroutine.www(www, co)
co = co or running()
local timer = nil
local action = function()
if not www.isDone then
return
end
timer:Stop()
local flag, msg = resume(co)
if not flag then
msg = debug.traceback(co, msg)
error(msg)
return
end
end
timer = FrameTimer.New(action, 1, -1)
comap[co] = timer
timer:Start()
return yield()
end
function coroutine.stop(co)
local timer = comap[co]
if timer ~= nil then
comap[co] = nil
timer:Stop()
end
end
<file_sep>/Assets/Libs/LuaDataBind/UI/Command/EventTriggerClickCommand.cs
using System.Collections.Generic;
using UnityEngine;
namespace LuaDataBind
{
/// <summary>
/// Command which is invoked when a onClick event occured on an event trigger.
/// </summary>
[AddComponentMenu("Data Bind/Commands/[NGUI] Event Trigger Click Command")]
public class EventTriggerClickCommand : NguiEventCommand<UIEventTrigger>
{
protected override List<EventDelegate> GetEvent(UIEventTrigger target)
{
return target.onClick;
}
}
}<file_sep>/Assets/GEngineScript/Core/SceneManager/GSceneManager.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using System;
using System.Collections;
using System.IO;
using UnityEngine;
namespace GOE.Scene
{
/// <summary>
/// 描述:场景管理器,用来管理场景的加载方式,缓存数据
/// <para>创建时间:2016-06-15</para>
/// </summary>
public sealed class GSceneManager {
private static GSceneManager mInstance;
private ARCCache<string, AssetBundle> cache = new ARCCache<string, AssetBundle>(5);
public class Transitions
{
public const string FadeTransition = "Transitions/SMFadeTransition";
public const string BlindsTransition = "Transitions/SMBlindsTransition";
}
private GSceneManager()
{
}
public static GSceneManager Instance
{
get
{
if(mInstance == null)
mInstance = new GSceneManager();
return mInstance;
}
}
/// <summary>
/// 异步加载场景
/// </summary>
/// <param name="sceneName">场景名称</param>
/// <param name="transition">过滤资源相对路径</param>
/// <param name="callback">异步加载完成后的回调</param>
/// <returns>场景加载器,可用于跟踪进度</returns>
public void LoadSceneAsync(string sceneName, string transition , Action callback, Action<float, float> progress)
{
loadScene(sceneName, transition, callback, true , progress);
}
/// <summary>
/// 同步加载场景
/// </summary>
/// <param name="sceneName">场景名称</param>
/// <param name="transition">过滤资源相对路径</param>
public void LoadScene(string sceneName, string transition)
{
loadScene(sceneName, transition, null, false, null);
}
/// <summary>
/// 加载场景
/// </summary>
/// <param name="sceneName">场景名称</param>
/// <param name="transition">过滤资源相对路径</param>
/// <param name="callback">异步加载完成后的回调</param>
/// <param name="isLoadAsync">是否异步加载</param>
/// <returns>场景加载器,可用于跟踪进度</returns>
private static void loadScene(string sceneName, string transition, Action callback, bool isLoadAsync, Action<float, float> progress)
{
UnityEngine.Object obj = Resources.Load(transition);
if (obj == null)
{
throw new ArgumentException("Cant find Object ! Transition Path is " + transition);
}
GameObject gObj = (GameObject)GameObject.Instantiate(obj);
ASceneTransition trans = gObj.GetComponent<ASceneTransition>();
trans.screenName = sceneName;
// trans.Loader = Instance.CurLoader;
}
}
}
<file_sep>/Assets/GameScript/Lua/Test/APITest.lua
--[[
Author: LiangZG
Email : <EMAIL>
]]
require "Common.functions"
--[[
Desc:
]]
APITest = {}
local this = APITest
function this.Awake()
-- body
end
function this.Start( )
-- body
TimeService.ins:adjustServerTime(os.time())
end
function this.OnGUI( )
if GUILayout.Button("StringBuffer" , GUILayout.Height(30)) then
this.testStringBuffer()
end
if GUILayout.Button("testList" , GUILayout.Height(30)) then
this.testList()
end
--this.schedulerAPI()
--this.timerGUI()
--this.arrayGUI()
this.utilGUI()
end
function this.OnDestroy( ... )
-- body
end
function this.testStringBuffer()
local stringBuffer = require "Text.stringBuffer"
local sb = stringBuffer.new()
sb:append("test")
sb:append(" , next ")
sb:appendFormat("%d_%d" , 10 , 1000)
sb:appendLine("appendLine")
sb:appendLine("line2")
print(sb:toString())
print("remove--->" .. sb:size())
sb:remove("test")
print("size:" .. sb:size() .. " ,stringBuffer: " .. sb:toString())
print("clear------>")
sb:clear()
print("size:" .. sb:size() .. " ,stringBuffer: " .. sb:toString())
end
function this.testList()
local list = require "Collections.list"
print("list:" .. tostring(list))
local mList = list.new()
mList:add(1)
mList:add(2)
mList:add(3)
print("size:" .. mList:size() .. " , allValue:" .. mList:toString())
for item in mList:values() do
print(item)
end
print("next for :")
for item in mList:values() do
print(item)
end
print(" 1:" .. mList:get(1))
print(" 2:" .. mList:get(2))
print(" 3:" .. mList:get(3))
print("remove index:2")
mList:removeAt(2)
print("size:" .. mList:size() .. " , allValue:" .. mList:toString())
end
function this.schedulerAPI( )
if GUILayout.Button(" add globalInterval" , GUILayout.Height(30)) then
local index = 0
this.updateFunc = function ( ... )
print("log:" .. index)
index = index + 1
end
Scheduler.ins:startInterval(this.updateFunc , 0.5)
end
if GUILayout.Button("remove globalInterval" , GUILayout.Height(30)) then
Scheduler.ins:remove(this.updateFunc)
end
if GUILayout.Button(" start once" , GUILayout.Height(30)) then
Scheduler.ins:start(function ( )
-- body
print(" do once ")
end , true)
end
if GUILayout.Button(" start delay" , GUILayout.Height(30)) then
print(" start delay ")
Scheduler.ins:startDelay(function ( )
-- body
print(" delay func")
end , 1 , true)
end
end
function this.timerGUI( )
if GUILayout.Button("start time second" , GUILayout.Height(30)) then
local timer = Timer.new()
local curTime = TimeService.ins:totalMillisecondNow() / 1000
timer:setBeginTime(curTime , 10 , eTimeUnit.Second)
local index = 0
timer.changeFunc = function ( ... )
index = index + 1
print("time:" .. index)
end
timer:start()
end
if GUILayout.Button("start time milliSecond" , GUILayout.Height(30)) then
local timer = Timer.new()
local curTime = TimeService.ins:totalMillisecondNow() / 1000
timer:setBeginTime(curTime , 1 , eTimeUnit.MilliSecond)
local index = 0
timer.changeFunc = function ( ... )
index = index + 1
print("time:" .. index)
end
timer:start()
end
if GUILayout.Button("start time custom" , GUILayout.Height(30)) then
local timer = Timer.new()
local curTime = TimeService.ins:totalMillisecondNow() / 1000
timer:setBeginTime(curTime , 10 , 1.2)
local index = 0
timer.changeFunc = function ( ... )
index = index + 1
print("custom time:" .. index)
end
timer:start()
end
end
function this.arrayGUI( )
if GUILayout.Button(" Test Array " , GUILayout.Height(30)) then
require "Collection.ArrayTest"
end
if GUILayout.Button(" Test Queue " , GUILayout.Height(30)) then
require "Collection.QueueTest"
end
if GUILayout.Button(" Test Stack " , GUILayout.Height(30)) then
require "Collection.StackTest"
end
end
function this.utilGUI( )
if GUILayout.Button(" Test SingleTask " , GUILayout.Height(30)) then
require "Util.SingleTaskTest"
end
if GUILayout.Button(" Test SerialTask " , GUILayout.Height(30)) then
require "Util.SerialTaskTest"
end
if GUILayout.Button(" Test ParallelTask " , GUILayout.Height(30)) then
require "Util.ParallelTaskTest"
end
end<file_sep>/Assets/GameScript/Lua/Test/Collection/StackTest.lua
require "test"
test("push should return a table with a , b , c ,size is 3" , function ( )
local stack = Stack.new()
stack:push("a")
stack:push("b")
stack:push("c")
assertEqual(stack:size() , 3)
end)
test("pop should return a string" , function ( )
local stack = Stack.new()
stack:push("a")
stack:push("b")
stack:push("c")
assertEqual(stack:pop() , "c")
assertEqual(stack:pop() , "b")
assertEqual(stack:pop() , "a")
end)
test("pop should return a nil when queue is empty" , function ( )
local stack = Stack.new()
assertEqual(stack:pop() , nil)
stack:push(1)
assertEqual(stack:pop() , 1)
assertEqual(stack:pop() , nil)
end)
-- test("return size is zero when push value is nil " , function ( )
-- local stack = Stack.new()
-- stack:push()
-- assertEqual(stack:size() , 0)
-- end)
-- test("return size is zero when push value is nil " , function ( )
-- local stack = Stack.new()
-- print("-----> set value nil----------- ")
-- queue["_size"] = nil
-- queue["_size"] = 999
-- print("-----> set value nil , size:" .. tostring(stack:size()))
-- end)
test("push over init capactity will work !" , function ( )
local stack = Stack.new(2)
stack:push("a")
stack:push("b")
assertEqual(stack:pop() , "b")
assertEqual(stack:pop() , "a")
assertEqual(stack:pop() , nil)
stack:push("c")
stack:push("d")
stack:push("e")
stack:push("f")
assertEqual(stack:pop() , "f")
assertEqual(stack:pop() , "e")
assertEqual(stack:pop() , "d")
assertEqual(stack:pop() , "c")
assertEqual(stack:pop() , nil)
end)
test("peek dont change queue index !" , function ( )
local stack = Stack.new()
stack:push("a")
stack:push("b")
assertEqual(stack:peek() , "b")
assertEqual(stack:pop() , "b")
assertEqual(stack:peek() , "a")
assertEqual(stack:pop() , "a")
assertEqual(stack:pop() , nil)
end)
test('contains should returns correct position of value in the table', function()
local stack = Stack.new()
stack:push("a")
stack:push(1)
assertEqual(stack:contains('a'), true)
assertEqual(stack:contains(1), true)
end)
test('contains should returns false when the value is not in the table', function()
local stack = Stack.new()
stack:push("a")
stack:push(1)
assertEqual(stack:contains("b"), false)
assertEqual(stack:contains(2), false)
stack:clear()
assertEqual(stack:contains(1), false)
end)
test('enumerator should returns all element ', function()
local stack = Stack.new()
stack:push("a")
stack:push(1)
stack:push("b")
stack:push("false")
local str = {}
for v in stack:enumerator() do
table.insert(str , v)
end
str = table.concat( str, ",")
assertEqual(str , "false,b,1,a")
end)
test('enumerator should returns all element ', function()
local stack = Stack.new()
stack:push("a")
stack:push(1)
stack:push("b")
stack:push("false")
local str = {}
local rator = stack:enumerator()
table.insert(str , rator())
table.insert(str , rator())
table.insert(str , rator())
table.insert(str , rator())
str = table.concat( str, ",")
print("allValue:" .. str)
assertEqual(str , "false,b,1,a")
end)
test('getEnumerator should returns all element ', function()
local stack = Stack.new()
stack:push("a")
stack:push(1)
stack:push("b")
stack:push("false")
local str = {}
local rator = stack:getEnumerator()
while rator:moveNext() do
table.insert(str , rator:current())
end
str = table.concat( str, ",")
print("allValue:" .. str)
assertEqual(str , "false,b,1,a")
end)
<file_sep>/Assets/GameScript/Lua/Collections/List.lua
--[[
Author: LiangZG
Email : <EMAIL>
Desc : 有序list 容器 , 列表的下标从1开始
]]
local List = class("List")
local m = List
function m:ctor( capactity )
self.capactity = capactity
self._list = {}
self._listHash = {}
end
--获取列表中的元素,index 从1开始
function m:get( index )
if index > self:size() or index < 1 then return nil end
return self._list[index]
end
function m:add( item )
if self._listHash[item] or self:isMaxCapactity() then return end
self._listHash[item] = true
table.insert(self._list , item)
end
function m:isMaxCapactity( )
return self.capactity and self:size() >= self.capactity or false
end
-- function m:addRange( collection )
-- -- body
-- end
function m:remove( item )
if not self._listHash[item] or self:isMaxCapactity() then return end
self._listHash[item] = nil
for i=self:size(),1,-1 do
if self._list[i] == item then
table.remove(self._list , i)
return
end
end
end
function m:removeAt( index )
if index > self:size() or index < 1 then return end
local item = self._list[index]
table.remove(self._list , index)
self._listHash[item] = nil
end
-- function m:removeRange( ... )
-- -- body
-- end
function m:clear()
self._listHash = {}
self._list = {}
end
function m:size()
return #self._list
end
function m:contains( item )
return self._listHash[item]
end
-- function m:find( ... )
-- -- body
-- end
function m:insert( index , item )
if index > self:size() or index < 1 or self:isMaxCapactity() then return end
table.insert(self._list , index , item)
self._listHash[item] = true
end
-- function m:insertRange( ... )
-- -- body
-- end
-- function m:findIndex( ... )
-- -- body
-- end
function m:sort( compare )
table.sort(self._list , compare)
end
function m:copyTo( ... )
-- body
end
--用于遍历
function m:enumerator()
local index = 0
return function ()
index = index + 1
return self._list[index]
end
end
function m:toString()
local str = {}
local size = self:size()
for i=1,size do
table.insert(str , tostring(self._list[i]))
end
return table.concat( str, ", ")
end
return List<file_sep>/Assets/GameScript/Lua/Collections/init.lua
local COLLECTIONS_MODEL_NAME = ...
Array = import ".Array"
Queue = import ".Queue"
LinkList = import ".LinkList"
List = import ".List"
Stack = import ".Stack"
Enumerator = import ".Enumerator"<file_sep>/Assets/Libs/LuaDataBind/UI/Command/PopupListChangeCommand.cs
using System.Collections.Generic;
using UnityEngine;
namespace LuaDataBind
{
/// <summary>
/// Command which is triggered when the selected value of a popup list changed.
/// </summary>
[AddComponentMenu("Data Bind/Commands/[NGUI] Popup List Change Command")]
public class PopupListChangeCommand : NguiEventCommand<UIPopupList>
{
/// <summary>
/// Storing popup value for comparison, the onChange event is triggered
/// if the same value is selected again, too.
/// </summary>
private string value;
protected override List<EventDelegate> GetEvent(UIPopupList target)
{
return target.onChange;
}
protected override void OnEnable()
{
base.OnEnable();
if (this.Target != null)
{
this.value = this.Target.value;
}
}
protected override void OnEvent()
{
var newValue = this.Target.value;
if (newValue == this.value)
{
return;
}
base.OnEvent();
this.value = newValue;
}
}
}<file_sep>/Assets/GameScript/Lua/Util/TaskRunner/ParallelTaskCollection.lua
--[[
Author: LiangZG
Email : <EMAIL>
Desc : 并行的任务集合
]]
local iskindof = iskindof
local ParallelTaskCollection = class("ParallelTaskCollection" , TaskCollection)
function ParallelTaskCollection:ctor( )
ParallelTaskCollection.super.ctor(self)
self._listOfStacks = List.new()
end
function ParallelTaskCollection:process( )
-- body
end
function ParallelTaskCollection:getEnumerator( )
return Enumerator.new(0 , 0 , handler(self , self.enumerator))
end
function ParallelTaskCollection:enumerator( )
self._isRunning = true
self._listOfStacks:clear()
for task in self._taskQueue:enumerator() do
local stack = Stack.new()
stack:push(task)
self._listOfStacks:add(stack)
end
local startSize = self._listOfStacks:size()
local size = startSize
local rmList = List.new()
while self._listOfStacks:size() > 0 do
for stack in self._listOfStacks:enumerator() do
if stack:size() > 0 then
local task = stack:peek()
if type(task) == "function" then
self._process = (size - startSize) / size
startSize = startSize - 1
local item = stack:pop()
--print("args:" .. print_lua_table(self._args) .. ", arg:" .. print_lua_table(self._args[task]))
item(unpack(self._args[task]))
elseif iskindof(task , "Enumerator") then
if not task:moveNext() then
self._process = (size - startSize) / size
startSize = startSize - 1
stack:pop()
end
elseif iskindof(task , "AsyncTask") then
stack:push(task)
else
stack:pop()
stack:push(task:getEnumerator())
end
else
rmList:add(stack)
end
end
for stack in rmList:enumerator() do
self._listOfStacks:remove(stack)
end
rmList:clear()
coroutine.step()
end
self._isRunning = false
end
return ParallelTaskCollection<file_sep>/Assets/GEngineScript/Core/ResourceSystem/Base/LoadBundleAsync.cs
using System;
using System.IO;
using UnityEngine;
namespace GEX.Resource
{
/// <summary>
/// 处理异步加载AssetBundle
/// </summary>
public class LoadBundleAsync : LoadOperation
{
private bool isDone = false;
private string extension;
private GameObject owner;
private UnityEngine.Object mainAsset;
public LoadBundleAsync(GameObject owner, string assetName) : base(assetName)
{
this.extension = Path.GetExtension(extension);
this.owner = owner;
}
public override void OnLoad()
{
if (extension == ".prefab")
{
AssetBundleManager.Instance.LoadPrefabAsync(assetPath)
.Then((gObj) => loadFinishCallback(gObj));
}
else
{
AssetBundleManager.Instance.LoadAssetAsync<UnityEngine.Object>(assetPath, extension, owner)
.Then((gObj) => loadFinishCallback(gObj));
}
}
private void loadFinishCallback(UnityEngine.Object gameObject)
{
this.mainAsset = gameObject;
isDone = true;
this.onFinishEvent();
}
public override bool IsDone()
{
return isDone;
}
public override T GetAsset<T>()
{
return mainAsset as T;
}
}
}
<file_sep>/Assets/GameScript/Lua/Net/Protocol/Task.lua
--local NetREQ_ = NetREQ
NetProtoTask = {}
NetProto.NetModule[11] = NetProtoTask
NetProtoTask.st = {
['TaskUnitVO'] = function(T)
if not(T:result()) then return end
T:vint32('doneNum') --已做次数
T:vint8('state') --状态集合
T:vint32('taskId') --任务id
end,
['TaskUnitsPushVO'] = function(T)
if not(T:result()) then return end
T:array('taskUnitVOs', NetProtoTask.st.TaskUnitVO) --任务单元数组
T:vint32('type') --任务类型
end,
}
NetProtoTask.send = {
['GetTaskUnitVOs'] = function(T)
if not(T:result()) then return end
T:vint32('type') --任务类型
end,
['GetLastTaskUnitVO'] = function(T)
if not(T:result()) then return end
T:vint32('type') --任务类型
end,
['GetAcceptableTaskIds'] = function(T)
if not(T:result()) then return end
T:vint32('type') --任务类型
end,
['AcceptTask'] = function(T)
if not(T:result()) then return end
T:vint32('taskId') --任务ID
end,
['AutoAcceptTasks'] = function(T)
if not(T:result()) then return end
T:vint32('type') --任务类型
end,
['ReceiveRewards'] = function(T)
if not(T:result()) then return end
T:array('taskIds', T.vint32) --任务ID数组
end,
['ReceiveRewardAndAcceptNext'] = function(T)
if not(T:result()) then return end
T:vint32('taskId') --任务ID
end,
['GetAppointTaskUnitVOs'] = function(T)
if not(T:result()) then return end
T:vint32('type') --任务类型
T:vint32('gettingType') --获取方式:1 全部,2 指定类型 3 排除指定类型
T:array('secondTyps', T.vint32) --第二类型数组
end,
['PostSevenLoginTask'] = function(T)
if not(T:result()) then return end
end,
}
-- ***自动提示帮助***
NetProtoTask.TaskUnitVO = {
['doneNum'] = nil, --已做次数
['state'] = nil, --状态集合
['taskId'] = nil, --任务id
}
NetProtoTask.TaskUnitsPushVO = {
['taskUnitVOs'] = nil, --任务单元数组
['type'] = nil, --任务类型
}
local T = NetProto.st
-- ***请求处理***
--列出所有任务
NetProtoTask.SendGetTaskUnitVOs = {
['new'] = NetProto.new,
['_MOD_'] = 11,
['_MED_'] = 1,
['type'] = nil, --任务类型
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoTask.send.GetTaskUnitVOs, NetProto.st.array(NetProtoTask.st.TaskUnitVO), fnRespond)
end,
}
--获得最后一个任务
NetProtoTask.SendGetLastTaskUnitVO = {
['new'] = NetProto.new,
['_MOD_'] = 11,
['_MED_'] = 2,
['type'] = nil, --任务类型
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoTask.send.GetLastTaskUnitVO, NetProtoTask.st.TaskUnitVO, fnRespond)
end,
}
--列出可接受任务
NetProtoTask.SendGetAcceptableTaskIds = {
['new'] = NetProto.new,
['_MOD_'] = 11,
['_MED_'] = 3,
['type'] = nil, --任务类型
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoTask.send.GetAcceptableTaskIds, NetProto.st.array(T.vint32), fnRespond)
end,
}
--接受任务 --返回:状态码
NetProtoTask.SendAcceptTask = {
['new'] = NetProto.new,
['_MOD_'] = 11,
['_MED_'] = 4,
['taskId'] = nil, --任务ID
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoTask.send.AcceptTask, T.vint32, fnRespond)
end,
}
--自动接受任务 --返回:状态码
NetProtoTask.SendAutoAcceptTasks = {
['new'] = NetProto.new,
['_MOD_'] = 11,
['_MED_'] = 5,
['type'] = nil, --任务类型
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoTask.send.AutoAcceptTasks, T.vint32, fnRespond)
end,
}
--领取奖励 --返回:状态码
NetProtoTask.SendReceiveRewards = {
['new'] = NetProto.new,
['_MOD_'] = 11,
['_MED_'] = 6,
['taskIds'] = nil, --任务ID数组
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoTask.send.ReceiveRewards, T.vint32, fnRespond)
end,
}
--领取奖励 --返回:状态码
NetProtoTask.SendReceiveRewardAndAcceptNext = {
['new'] = NetProto.new,
['_MOD_'] = 11,
['_MED_'] = 7,
['taskId'] = nil, --任务ID
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoTask.send.ReceiveRewardAndAcceptNext, T.vint32, fnRespond)
end,
}
--列出指定任务
NetProtoTask.SendGetAppointTaskUnitVOs = {
['new'] = NetProto.new,
['_MOD_'] = 11,
['_MED_'] = 8,
['type'] = nil, --任务类型
['gettingType'] = nil, --获取方式:1 全部,2 指定类型 3 排除指定类型
['secondTyps'] = nil, --第二类型数组
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoTask.send.GetAppointTaskUnitVOs, NetProto.st.array(NetProtoTask.st.TaskUnitVO), fnRespond)
end,
}
--触发七天登录任务 --返回:状态码
NetProtoTask.SendPostSevenLoginTask = {
['new'] = NetProto.new,
['_MOD_'] = 11,
['_MED_'] = 9,
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoTask.send.PostSevenLoginTask, T.vint32, fnRespond)
end,
}
-- ***推送处理***
NetProtoTask.MesssagePush = {
[101] = {['msg']='msgPushTaskUnits' ,['st'] = NetProtoTask.st.TaskUnitsPushVO}, --推送任务单元
}
DeclareInterface(NetProtoTask, 'msgPushInterface')
function NetProtoTask.listenMessagePush(listener)
ListenInterface(NetProtoTask, 'msgPushInterface', listener)
end
function NetProtoTask.removeMessagePush(listener)
RemoveInterface(NetProtoTask, 'msgPushInterface', listener)
end
<file_sep>/Assets/Editor/SceneManagerEditor/LightMapEditor.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using UnityEngine;
using System.Collections.Generic;
using System.IO;
using GOE.Scene;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
using SceneManager = UnityEngine.SceneManagement.SceneManager;
/// <summary>
/// 描述:动态烘焙场景光照模型,并产生对应的Prefab文件
/// <para>创建时间:2016-06-15</para>
/// </summary>
public sealed class LightMapEditor
{
private const string LightMapsDir = "Resources/Lightmaps/";
private static List<RemapTexture2D> sceneLightmaps = new List<RemapTexture2D>();
public static void UpdateLightmaps()
{
PrefabLightmapData pld = GameObject.FindObjectOfType<PrefabLightmapData>();
if (pld == null) return;
LightmapSettings.lightmaps = null;
PrefabLightmapData.ApplyLightmaps(pld.mRendererInfos , pld.mLightmapFars , pld.mLightmapNears);
Debug.Log("Prefab Lightmap updated");
}
public static void GenLightmap()
{
genBakeLightmapAndPrefab(false);
EditorSceneManager.SaveOpenScenes();
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
Debug.Log("----------------Update to Prefab Lightmap Finish -------------------------");
}
/// <summary>
/// 生成lightmap和prefab资源
/// </summary>
/// <param name="isQuiet">是否静默执行,true不会出现异常提示</param>
private static void genBakeLightmapAndPrefab(bool isQuiet)
{
if (Lightmapping.giWorkflowMode != Lightmapping.GIWorkflowMode.OnDemand)
{
Debug.LogError("ExtractLightmapData requires that you have baked you lightmaps and Auto mode is disabled.");
return;
}
Debug.ClearDeveloperConsole();
PrefabLightmapData[] pldArr = GameObject.FindObjectsOfType<PrefabLightmapData>();
if (pldArr == null || pldArr.Length <= 0)
{
if(!isQuiet)
EditorUtility.DisplayDialog("提示", "没有找到必要的脚本PrefabLightmapData,请检查场景", "OK");
return;
}
Lightmapping.Bake();
sceneLightmaps.Clear();
string path = Path.Combine(Application.dataPath, LightMapsDir);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
Scene curScene = EditorSceneManager.GetActiveScene();
string sceneName = Path.GetFileNameWithoutExtension(curScene.name);
string scenePath = Path.GetDirectoryName(curScene.path) + "/" + sceneName + "/";
string resourcesPath = Path.GetDirectoryName(curScene.path) + "/" + sceneName + "_lightmap/" + sceneName;
foreach (PrefabLightmapData pld in pldArr)
{
GameObject gObj = pld.gameObject;
List<RendererInfo> renderers = new List<RendererInfo>();
List<Texture2D> lightmapFars = new List<Texture2D>();
List<Texture2D> lightmapNears = new List<Texture2D>();
genLightmapInfo(scenePath, resourcesPath, gObj, renderers, lightmapFars, lightmapNears);
pld.mRendererInfos = renderers.ToArray();
pld.mLightmapFars = lightmapFars.ToArray();
pld.mLightmapNears = lightmapNears.ToArray();
GameObject targetPrefab = PrefabUtility.GetPrefabParent(gObj) as GameObject;
//生成拷贝副本
GameObject cloneGObj = (GameObject)GameObject.Instantiate(gObj);
//删除过滤结点
FilterSceneFlag[] flags = cloneGObj.GetComponentsInChildren<FilterSceneFlag>();
foreach (FilterSceneFlag flag in flags)
flag.ClearSelf();
if (targetPrefab != null)
{
//自定义存放的路径
PrefabUtility.ReplacePrefab(cloneGObj, targetPrefab);
}
else
{
//默认路径
string prefabPath = Path.GetDirectoryName(curScene.path) + "/" + sceneName + ".prefab";
PrefabUtility.CreatePrefab(prefabPath, cloneGObj, ReplacePrefabOptions.ConnectToPrefab);
}
GameObject.DestroyImmediate(cloneGObj);
//改变当前场景中的光照贴图信息
PrefabLightmapData.ApplyLightmaps(pld.mRendererInfos, pld.mLightmapFars, pld.mLightmapNears);
}
}
/// <summary>
/// 生成所有场景的Prefab资源
/// </summary>
public static void GenLightmapPrefabAll()
{
EditorSceneManager.SaveOpenScenes();
AssetDatabase.SaveAssets();
string[] sceneDirs = new[] {"Assets/AllResources/scene-s/"};
string curScenePath = EditorSceneManager.GetActiveScene().path;
foreach (string sceneDir in sceneDirs)
{
string[] sceneArr = Directory.GetFiles(sceneDir, "*.unity" , SearchOption.AllDirectories);
if(sceneArr == null || sceneArr.Length <= 0) continue;
int index = 0;
foreach (string scenePath in sceneArr)
{
EditorUtility.DisplayProgressBar("生成Lightmap Prefab", "正在打包生成资源,请等待...", index / (float)sceneArr.Length);
Scene curScene = EditorSceneManager.OpenScene(scenePath.Replace("\\", "/"));
SceneManager.SetActiveScene(curScene);
genBakeLightmapAndPrefab(true);
index++;
}
}
EditorUtility.ClearProgressBar();
//还原打包前打开的场景
EditorSceneManager.OpenScene(curScenePath);
EditorSceneManager.SaveOpenScenes();
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
Debug.Log("已完成打包" + System.DateTime.Now.ToString("HH:mm:ss"));
EditorUtility.DisplayDialog("提示", "已完成批量打包!" + System.DateTime.Now.ToString("HH:mm:ss"), "OK");
}
private static void genLightmapInfo(string scenePath , string resourcePath , GameObject root,
List<RendererInfo> renderers, List<Texture2D> lightmapFars,
List<Texture2D> lightmapNears)
{
MeshRenderer[] subRenderers = root.GetComponentsInChildren<MeshRenderer>();
LightmapData[] srcLightData = LightmapSettings.lightmaps;
foreach (MeshRenderer meshRenderer in subRenderers)
{
if(meshRenderer.lightmapIndex == -1) continue;
RendererInfo renderInfo = new RendererInfo();
renderInfo.renderer = meshRenderer;
renderInfo.LightmapIndex = meshRenderer.lightmapIndex;
renderInfo.LightmapOffsetScale = meshRenderer.lightmapScaleOffset;
Texture2D lightmapFar = srcLightData[meshRenderer.lightmapIndex].lightmapColor;
Texture2D lightmapNear = srcLightData[meshRenderer.lightmapIndex].lightmapDir;
int sceneCacheIndex = addLightmap(scenePath, resourcePath, renderInfo.LightmapIndex, lightmapFar,
lightmapNear);
renderInfo.LightmapIndex = lightmapFars.IndexOf(sceneLightmaps[sceneCacheIndex].LightmapFar);
if (renderInfo.LightmapIndex == -1)
{
renderInfo.LightmapIndex = lightmapFars.Count;
lightmapFars.Add(sceneLightmaps[sceneCacheIndex].LightmapFar);
lightmapNears.Add(sceneLightmaps[sceneCacheIndex].LightmapNear);
}
renderers.Add(renderInfo);
}
}
private static int addLightmap(string scenePath, string resourcePath, int originalLightmapIndex,
Texture2D lightmapFar,
Texture2D lightmapNear)
{
for (int i = 0; i < sceneLightmaps.Count; i++)
{
if (sceneLightmaps[i].OriginalLightmapIndex == originalLightmapIndex)
{
return i;
}
}
RemapTexture2D remapTex = new RemapTexture2D();
remapTex.OriginalLightmapIndex = originalLightmapIndex;
remapTex.OrginalLightmap = lightmapFar;
string fileName = scenePath + "Lightmap-" + originalLightmapIndex;
remapTex.LightmapFar = getLightmapAsset(fileName + "_comp_light.exr", resourcePath + "_light",
originalLightmapIndex);
if(lightmapNear != null)
remapTex.LightmapNear = getLightmapAsset(fileName + "_comp_dir.exr", resourcePath + "_dir",
originalLightmapIndex);
sceneLightmaps.Add(remapTex);
return sceneLightmaps.Count - 1;
}
private static Texture2D getLightmapAsset(string fileName, string resourecPath, int originalLightmapIndex)
{
TextureImporter importer = AssetImporter.GetAtPath(fileName) as TextureImporter;
if (importer == null) return null;
importer.isReadable = true;
AssetDatabase.ImportAsset(fileName , ImportAssetOptions.ForceUpdate);
Texture2D assetLightmap = AssetDatabase.LoadAssetAtPath<Texture2D>(fileName);
string assetPath = resourecPath + "_" + originalLightmapIndex + ".asset";
Texture2D newLightmap = GameObject.Instantiate<Texture2D>(assetLightmap);
string dir = Path.GetDirectoryName(assetPath);
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
// byte[] bytes = newLightmap.EncodeToPNG();
// File.WriteAllBytes(assetPath, bytes);
AssetDatabase.CreateAsset(newLightmap , assetPath);
newLightmap = AssetDatabase.LoadAssetAtPath<Texture2D>(assetPath);
importer.isReadable = false;
AssetDatabase.ImportAsset(assetPath , ImportAssetOptions.ForceUpdate);
return newLightmap;
}
}
<file_sep>/Assets/GameScript/Lua/Net/Socket.lua
NetSocket = {}
NetSocket = class("NetSocket",function()
local o = core.SocketNet:new()
return o
end)
NetSocket.moduleMsgPushMap = {}
function NetSocket:registerModuleMsgPush(module_number,func)
self.moduleMsgPushMap[module_number] = func
end
<file_sep>/Assets/GameScript/Lua/UI/Common/NoticePanel.lua
-- @Author: <EMAIL>
-- @Last Modified time: 2017-01-01 00:00:00
-- @Desc: 提示
NoticePanel = {}
local this = NoticePanel
local curUiId = 0
--- 由LuaBehaviour自动调用
function NoticePanel.Awake(gameObject)
this.widgets = {
{field="root", path ="", src=LuaCanvas},
{field="btn_confim",path="content.btn_confim",src=LuaButton, onClick = this._onClickClose },
}
LuaUIHelper.bind(this.gameObject , NoticePanel )
end
function NoticePanel.Show( func )
UIManager:Show("Prefab/GUI/Common/NoticePanel", nil)
this.closeFunc = func
end
--- 由LuaBehaviour自动调用
function NoticePanel.OnInit(basePage)
this.basePage = basePage
this.basePage:SetPage(EPageType.PopUp , EShowMode.None , ECollider.Normal)
--每次显示自动修改UI中所有Panel的depth
--LuaUIHelper.addUIDepth(this.gameObject , NoticePanel)
this._registeEvents(this.event)
end
-- 注册界面事件监听
function NoticePanel._registeEvents(event)
end
--- 关闭界面
function NoticePanel._onClickClose( )
UIManager:Hide(this.basePage.assetPath)
if this.closeFunc ~= nil then
this.closeFunc()
this.closeFunc = nil
end
end
--- 由LuaBehaviour自动调用
function NoticePanel.OnClose()
--LuaUIHelper.removeUIDepth(this.gameObject) --还原全局深度
end
--- 由LuaBehaviour自动调用--
function NoticePanel.OnDestroy()
this.gameObject = nil
this.transform = nil
this.widgets = nil
end<file_sep>/Assets/GameScript/Lua/Util/TaskRunner/TaskCollection.lua
local TaskCollection = class("TaskCollection")
function TaskCollection:ctor( )
self._taskQueue = Queue.new()
self._args = {}
end
function TaskCollection:isRunning( )
return self._isRunning or false
end
function TaskCollection:process()
return 0
end
function TaskCollection:addAsyncTask( task , ...)
self:add(AsyncTask.new(task) , unpack({...}))
end
function TaskCollection:add( asyncTask , ... )
self._args[asyncTask] = {...}
self._taskQueue:enqueue(asyncTask)
end
--@abstract
function TaskCollection:getEnumerator( )
return nil
end
return TaskCollection<file_sep>/Assets/GameScript/Utility/UIHelper/UIGenFlag.cs
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.EventSystems;
#if UNITY_EDITOR
using System.Xml;
#endif
#if UGUI
using UnityEngine.UI;
#endif
namespace UIHelper
{
/// <summary>
/// UIPrefab 结点标志
/// </summary>
public class UIGenFlag : MonoBehaviour
{
/// <summary>
/// 用于查询的全局ID
/// </summary>
public string Uri;
/// <summary>
/// 程序代码使用的字段名称
/// </summary>
public string Field;
/// <summary>
/// 脚本类型
/// </summary>
public string ScriptType;
/// <summary>
/// 层次深度
/// </summary>
public int Depth = -1;
public string relativeHierarchy;
public string initRelativeHierarchy(GameObject root)
{
Depth = 0;
Transform trans = this.transform;
List<string> buf = new List<string>();
while (trans && !trans.gameObject.Equals(root))
{
buf.Add(trans.name);
trans = trans.parent;
Depth++;
}
buf.Reverse();
if (string.IsNullOrEmpty(ScriptType))
ScriptType = FindWidgetTypes()[0];
relativeHierarchy = string.Join(".", buf.ToArray());
return relativeHierarchy;
}
public List<string> FindWidgetTypes()
{
List<string> types = new List<string>();
#if NGUI
UIRect[] rectArr = this.gameObject.GetComponents<UIRect>();
foreach (UIRect rect in rectArr)
types.Add(rect.GetType().FullName);
UIWidgetContainer[] container = this.gameObject.GetComponents<UIWidgetContainer>();
foreach (UIWidgetContainer widget in container)
types.Add(widget.GetType().FullName);
UIInput input = this.gameObject.GetComponent<UIInput>();
if (input) types.Add(input.GetType().FullName);
UIWrapContent wrap = this.gameObject.GetComponent<UIWrapContent>();
if (wrap)
types.Add(wrap.GetType().FullName);
#elif UGUI
Graphic[] graphics = this.gameObject.GetComponents<Graphic>();
foreach (Graphic g in graphics)
{
types.Add(g.GetType().Name);
}
UIBehaviour[] uiBehavs = this.gameObject.GetComponents<UIBehaviour>();
foreach (UIBehaviour uib in uiBehavs)
{
types.Add(uib.GetType().Name);
}
#endif
//if (types.Count <= 0)
{
types.Add("GameObject");
types.Add("Transform");
}
return types;
}
#if UNITY_EDITOR
/// <summary>
/// 序列化UI配置数据
/// </summary>
/// <param name="root"></param>
/// <returns></returns>
public void serializeFlag(XmlElement ele)
{
ele.SetAttribute("field", this.Field);
ele.SetAttribute("ScriptType", this.ScriptType);
ele.SetAttribute("hierarchy", this.relativeHierarchy);
}
/// <summary>
/// 反序列化记录数据
/// </summary>
/// <param name="doc"></param>
public void deserializeFlag(XmlElement ele)
{
this.Field = ele.GetAttribute("field");
this.ScriptType = ele.GetAttribute("ScriptType");
this.relativeHierarchy = ele.GetAttribute("hierarchy");
}
#endif
}
}<file_sep>/Assets/GameScript/Lua/Test/Util/SerialTaskTest.lua
local SerialTasksTest = class("SerialTasksTest")
function SerialTasksTest:Start ()
local st = SerialTaskCollection.new()
local st2 = SerialTaskCollection.new()
st2:add(handler(self , self.Print) , "a")
st2:add(handler(self ,self.DoSomethingAsynchonously) , 1)
st2:add(handler(self ,self.Print) , "b")
st:add(handler(self , self.Print) , 1)
st:add(handler(self , self.Print) , 2)
st:add(handler(self , self.DoSomethingAsynchonously) , 1)
st:add(handler(self , self.Print) , 4)
st:add(handler(self , self.DoSomethingAsynchonously) , 5)
st:add(handler(self , self.Print) , 5)
st:add(self.WWWTest)
st:add(handler(self , self.Print) , 6)
st:add(st2)
st:add(handler(self , self.Print) , 7)
TaskRunner.run(st:getEnumerator())
end
function SerialTasksTest:Print(i)
Debugger.Log(i);
coroutine.step()
end
function SerialTasksTest:DoSomethingAsynchonously(time)
--print("time:" .. print_lua_table(time))
coroutine.wait(time);
Debugger.Log("waited " .. time);
end
function SerialTasksTest:WWWTest()
local www = WWW("www.baidu.com");
coroutine.www(www)
Debugger.Log("www done:" .. www.text);
end
local test = SerialTasksTest.new()
test:Start()
return SerialTasks<file_sep>/Assets/GameScript/UISystem/ClickEventListener.cs
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class ClickEventListener : MonoBehaviour, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler
{
public static ClickEventListener Get(GameObject obj)
{
ClickEventListener listener = obj.GetComponent<ClickEventListener>();
if (listener == null)
{
listener = obj.AddComponent<ClickEventListener>();
}
return listener;
}
Action<GameObject, PointerEventData> mClickedHandler = null;
Action<GameObject, PointerEventData> mDoubleClickedHandler = null;
Action<GameObject, PointerEventData> mOnPointerDownHandler = null;
Action<GameObject, PointerEventData> mOnPointerUpHandler = null;
Action<GameObject, PointerEventData> mOnPointerEnterHandler = null;
Action<GameObject, PointerEventData> mOnPointerExitHandler = null;
bool mIsPressed = false;
bool mForbidEvent = false;//意义 禁用当前自己的事件
public bool IsPressd
{
get { return mIsPressed; }
}
public void OnPointerClick(PointerEventData eventData)
{
if (!mForbidEvent)
{
if (eventData.clickCount == 2)
{
if (mDoubleClickedHandler != null)
{
mDoubleClickedHandler(gameObject, eventData);
}
}
else
{
if (mClickedHandler != null)
{
mClickedHandler(gameObject, eventData);
}
}
}
}
public void SetClickEventHandler(Action<GameObject, PointerEventData> handler)
{
mClickedHandler += handler;
}
public void SetDoubleClickEventHandler(Action<GameObject, PointerEventData> handler)
{
mDoubleClickedHandler += handler;
}
public void SetPointerDownHandler(Action<GameObject, PointerEventData> handler)
{
mOnPointerDownHandler += handler;
}
public void SetPointerUpHandler(Action<GameObject, PointerEventData> handler)
{
mOnPointerUpHandler += handler;
}
public void SetPointerEnterHandler(Action<GameObject, PointerEventData> handler)
{
mOnPointerEnterHandler += handler;
}
public void SetPointerExitHandler(Action<GameObject, PointerEventData> handler)
{
mOnPointerExitHandler += handler;
}
public void OnPointerDown(PointerEventData eventData)
{
mIsPressed = true;
if (mOnPointerDownHandler != null)
{
mOnPointerDownHandler(gameObject, eventData);
}
}
public void OnPointerUp(PointerEventData eventData)
{
mIsPressed = false;
if (mOnPointerUpHandler != null)
{
mOnPointerUpHandler(gameObject, eventData);
}
mForbidEvent = false;
if (eventData.pointerCurrentRaycast.gameObject != null &&
(eventData.pointerCurrentRaycast.gameObject.layer == LayerMask.NameToLayer("TipsPenetrate")))
{
//再往下传
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(eventData, results);
GameObject current = eventData.pointerCurrentRaycast.gameObject;
for (int i = 0; i < results.Count; i++)
{
var nextObject = results[i].gameObject;
if (current != nextObject)
{
bool canClick = ExecuteEvents.CanHandleEvent<IPointerClickHandler>(nextObject);
if (canClick && nextObject.tag == "ItemCell")
{
mForbidEvent = true;
ExecuteEvents.Execute(nextObject, eventData, ExecuteEvents.pointerClickHandler);
break;
}
}
}
}
}
public void OnPointerEnter(PointerEventData eventData)
{
if (mOnPointerEnterHandler != null)
{
mOnPointerEnterHandler(gameObject, eventData);
}
}
public void OnPointerExit(PointerEventData eventData)
{
if (mOnPointerExitHandler != null)
{
mOnPointerExitHandler(gameObject, eventData);
}
}
private void OnDestroy()
{
mClickedHandler = null;
mDoubleClickedHandler = null;
mOnPointerDownHandler = null;
mOnPointerUpHandler = null;
mOnPointerEnterHandler = null;
mOnPointerExitHandler = null;
}
}
<file_sep>/Assets/GameScript/Lua/GameState/FightState.lua
--[[
Author: LiangZG
Email : <EMAIL>
]]
local BaseState = require "Common.BaseState"
--[[
战斗状态,玩法展示状态
]]
local FightState = class("FightState" , BaseState)
function FightState:OnEnter()
print("FightState ---> OnEnter")
end
function FightState:OnExit()
print("FightState <---- OnExit")
end
return FightState<file_sep>/Assets/GEngineScript/Core/ResourceSystem/Loader/ParallelLoader.cs
using System.Collections;
using System.Collections.Generic;
using LuaInterface;
namespace GEX.Resource
{
/// <summary>
/// 并行异步加载容器,容器内部自动缓存加载器,需要手动释放
/// 使用方法:
/// var async = new ParallelAsync();
///
/// async.AddLoader("xxx/press/yy.prefab");
/// async.AddLoader("xxx/pres/zzz.ogg" , 5);
///
/// while(async.MoveNext())
/// {
/// // progress
/// if(progressAction != null)
/// progressAction.Invoke(async.Progress);
/// yield return null;
/// }
/// </summary>
public class ParallelLoader : LoadOperation
{
private class AsyncLoader
{
public int Weight;
public LoadOperation Loader;
}
/// <summary>
/// 权重,占总场景资源量的比重
/// </summary>
public int Weight { get; private set; }
private float completeWeight;
private int maxParallelCount = 5;
private List<AsyncLoader> loaders = new List<AsyncLoader>();
private List<int> finishs = new List<int>();
public ParallelLoader() : base("")
{
}
public ParallelLoader(int maxParallelCount)
: this()
{
this.maxParallelCount = maxParallelCount;
}
/// <summary>
/// 添加需要被加载的资源
/// </summary>
/// <param name="loader">异步加载器</param>
/// <param name="weight">权重,用于计算进度</param>
public LoadOperation AddLoader(LoadOperation loader, int weight = 1)
{
Weight += weight;
AsyncLoader asyncLoader = new AsyncLoader();
asyncLoader.Weight = weight;
asyncLoader.Loader = loader;
this.loaders.Add(asyncLoader);
return loader;
}
/// <summary>
/// 添加加载数据
/// </summary>
/// <param name="path">资源路径,类似"Assets/Res/XXXX.yyy"</param>
/// <param name="weight">权重,用于计算进度</param>
public LoadOperation AddLoader(string path, int weight = 1)
{
LoadOperation loadOpt = GResource.LoadAssetAsync(path);
this.AddLoader(loadOpt, weight);
return loadOpt;
}
public override void OnLoad()
{
throw new System.NotImplementedException();
}
[NoToLua]
public override T GetAsset<T>()
{
throw new System.NotImplementedException();
}
public override bool MoveNext()
{
if (loaders.Count <= 0) return false;
float weigeting = 0;
for (int i = 0 , count = loaders.Count; i < count; i++)
{
if (i >= maxParallelCount) break;
AsyncLoader asynloader = loaders[i];
if (!asynloader.Loader.MoveNext())
{
completeWeight += asynloader.Weight;
finishs.Add(i);
}
else
{
weigeting += asynloader.Loader.Progress * asynloader.Weight;
}
}
if (finishs.Count > 0)
{
finishs.Sort((x , y)=>x.CompareTo(y) * -1);
for (int i = 0; i < finishs.Count; i++)
{
loaders.RemoveAt(finishs[i]);
}
finishs.Clear();
}
progress = (weigeting + completeWeight) / Weight;
return IsDone() == false;
}
public override object Current
{
get { return null; }
}
public override bool IsDone()
{
bool result = loaders.Count <= 0;
if(result) this.onFinishEvent();
return result;
}
public override void Reset()
{
for (int i = 0; i < loaders.Count; i++)
{
loaders[i].Loader.Reset();
}
loaders.Clear();
Weight = 0;
}
}
}
<file_sep>/Assets/GameScript/Lua/Util/TaskRunner/SerialTaskCollection.lua
--[[
Author: LiangZG
Email : <EMAIL>
Desc : 串联的任务集合
]]
local iskindof = iskindof
local SerialTaskCollection = class("SerialTaskCollection" , TaskCollection)
function SerialTaskCollection:ctor( )
SerialTaskCollection.super.ctor(self)
end
function SerialTaskCollection:process( )
-- body
end
function SerialTaskCollection:getEnumerator( )
return Enumerator.new(0 , 1 , handler(self , self.enumerator))
end
function SerialTaskCollection:enumerator( )
self._isRunning = true
local startSize = self._taskQueue:size()
while self._taskQueue:size() > 0 do
local stack = Stack.new()
stack:push(self._taskQueue:dequeue())
while stack:size() > 0 do
local task = stack:peek()
if type(task) == "function" then
self._process = (startSize - self._taskQueue:size()) / startSize
self._subProgress = 0
local item = stack:pop()
item(unpack(self._args[task]))
elseif iskindof(task , "Enumerator") then
if not task:moveNext() then
stack:pop()
end
else
if iskindof(task , "AsyncTask") then
stack:push(task)
else
stack:push(task:getEnumerator())
end
-- if (ce is AsyncTask) //asyn
-- _subProgress = (ce as AsyncTask).task.progress * (((float)(startingCount - (registeredEnumerators.Count)) / (float)startingCount) - progress);
-- if (ce is EnumeratorWithProgress) //asyn
-- _subProgress = (ce as EnumeratorWithProgress).progress * (((float)(startingCount - (registeredEnumerators.Count)) / (float)startingCount) - progress);
--处理进度
if iskindof(task , "AsyncTask") then
self._subProgress = task._progress * ((startSize - self._taskQueue:size()) / startSize - self._progress)
else
end
end
coroutine.step()
end
end
self._isRunning = false
end
return SerialTaskCollection<file_sep>/Assets/GEngineScript/Core/ResourceSystem/AssetBundleManager.cs
using UnityEngine;
using System.Collections;
using LuaFramework;
using System.IO;
using System.Collections.Generic;
using System;
using GEX.Utility;
using RSG;
namespace GEX.Resource
{
public class BundleInfo
{
public AssetBundle bundle
{
get
{
refCount++;
lastTimeVisited = Time.realtimeSinceStartup;
AssetBundleManager abMgr = AssetBundleManager.Instance;
var deps = abMgr.GetAllDependencies(_bundleName);
for (int i = 0; i < deps.Count; ++i)
{
if (deps[i].Contains("tmp/")) continue;
BundleInfo bundleInfo;
if (abMgr.GetBundleInfo(deps[i], out bundleInfo))
{
bundleInfo.refCount++;
}
else if (abMgr.bundleLoadingQueue.Contains(deps[i]))
{
continue;
}
else
{
var temp = AssetBundle.LoadFromFile(Util.DataPath + deps[i]);
abMgr.AddBundleToLoaded(deps[i], temp);
//abMgr.bundleLoaded.Add(, new BundleInfo(temp, deps[i]));
}
}
return _bundle;
}
private set
{
_bundle = value;
}
}
private AssetBundle _bundle;
public int refCount
{
get { return _refCount; }
set
{
if (value > _refCount) lastTimeVisited = Time.realtimeSinceStartup;
_refCount = value;
}
}
private int _refCount;
public float timeCreated { get; private set; }
public float lastTimeVisited { get; private set; }
public string _bundleName { get; private set; }
public BundleInfo(AssetBundle bundle, string name)
{
this._bundle = bundle;
this._refCount = 1;
this._bundleName = name;
timeCreated = Time.realtimeSinceStartup;
lastTimeVisited = Time.realtimeSinceStartup;
}
public bool Unload()
{
AssetMap map;
if (AssetBundleManager.Instance.bundleLoadTypeMap.TryGetValue(_bundleName, out map))
if (map.type == AssetMap.LoadType.Preload) return false;
using (zstring.Block())
Debugger.Log(zstring.Format("<color=green>assetbundle unload: {0}</color>", _bundleName));
if (_bundle != null) _bundle.Unload(true);
_bundle = null;
return true;
}
}
public struct AssetMap
{
public enum LoadType
{
None,
Preload,
Limited,
}
public string name;
/// <summary>
/// asset类型: 0 普通类型; 1 预加载; 2 限制加载(总数量限制)
/// </summary>
public LoadType type;
}
public sealed class AssetBundleManager : Singleton<AssetBundleManager>
{
public AssetBundleManifest allBundleManifest { get; private set; }
/// <summary>
/// 正在加载的bundle资源
/// </summary>
public HashSet<string> bundleLoadingQueue = new HashSet<string>();
/// <summary>
/// 已经加载的bundle资源
/// </summary>
public Dictionary<string, BundleInfo> bundleCache = new Dictionary<string, BundleInfo>();
/// <summary>
/// asset资源map映射表
/// </summary>
public Dictionary<string, string> assetbundleMap = new Dictionary<string, string>();
private Dictionary<string , UIAtlasCache> atlasMap = new Dictionary<string, UIAtlasCache>();
private Dictionary<string, int> assetIntanceCounts = new Dictionary<string, int>();
private Queue<BundleInfo> unloadQueue = new Queue<BundleInfo>();
public delegate void OnProgressChanged(float value);
public OnProgressChanged onProgressChange;
public Dictionary<string, AssetMap> bundleLoadTypeMap = new Dictionary<string, AssetMap>();
/// <summary>
/// 已经加载的限制类型bundle资源(refcount=0需立即释放)
/// </summary>
private Dictionary<string, BundleInfo> limitedBundleCache = new Dictionary<string, BundleInfo>();
public UnityEngine.Object[] shaderAssets;
public Font font;
private AssetBundleCreateRequest preloadAbcr = null;
private int curIndex = 0;
const float MAXDELAY_CLEAR_TIME = 10 * 60;
private float delayClearTime;
private float delayUnloadTime;
//private AssetBundle sceneDependency = null;
private Dictionary<string, List<string>> dependenciesCache = new Dictionary<string, List<string>>();
new void Awake()
{
delayClearTime = MAXDELAY_CLEAR_TIME;
}
public void AssetBundleInit(Action callback)
{
LoadAssetbundleMap();
LoadManifest();
StartCoroutine(PreloadAsset(callback));
//limitedBundleCache.SetDestroyStrategy(new BundleDestoryStrategy(AssetBundleManager.Instance));
}
private void LoadAssetbundleMap()
{
var content = File.ReadAllBytes(string.Format("{0}/bundlemap.ab", Util.DataPath));
var decryptoStrs = Encoding.GetString(Crypto.Decode(content)).Split('\n');
for (int i = 0; i < decryptoStrs.Length; ++i)
{
if (!string.IsNullOrEmpty(decryptoStrs[i]))
{
var temp = decryptoStrs[i].Split('|');
Debug.Assert(temp.Length == 3);
if (assetbundleMap.ContainsKey(temp[0]))
{
throw new ArgumentException(string.Format("{0} is already exists", temp[0]));
}
if (temp[0].CustomStartsWith("atlas/"))
assetbundleMap[temp[0].Split('-')[0]] = temp[1];
else
assetbundleMap[temp[0]] = temp[1];
if (!bundleLoadTypeMap.ContainsKey(temp[1]))
{
AssetMap map = new AssetMap();
map.name = temp[1];
map.type = (AssetMap.LoadType)(Convert.ToInt32(temp[2].Trim()));
bundleLoadTypeMap[map.name] = map;
}
//if (temp[2].Trim() == "1" && !preloadAssets.Contains(temp[1]))
// preloadAssets.Add(temp[1]);
}
}
}
private void LoadManifest()
{
string path = string.Format("{0}{1}.ab", Util.DataPath, LuaConst.osDir.ToLower());
if (!File.Exists(path))
{
Debug.LogError(string.Format("no manifest file exists in {0}", path));
return;
}
var allBundle = AssetBundle.LoadFromFile(path);
if (allBundle)
{
allBundleManifest = allBundle.LoadAsset("AssetBundleManifest") as AssetBundleManifest;
allBundle.Unload(false);
var bundles = allBundleManifest.GetAllAssetBundles();
for (int i = 0; i < bundles.Length; ++i)
{
AssetMap map;
if (bundleLoadTypeMap.TryGetValue(bundles[i], out map))
{
var deps = GetAllDependencies(bundles[i]);
for (int k = 0; k < deps.Count; ++k)
{
if (deps[k].Contains("tmp/")) continue;
if (map.type == AssetMap.LoadType.Preload && !IsBundleLoaded(deps[k]))
{
AssetMap depMap;
if (!bundleLoadTypeMap.TryGetValue(deps[k], out depMap))
{
depMap = new AssetMap();
depMap.name = deps[k];
depMap.type = AssetMap.LoadType.Preload;
bundleLoadTypeMap[deps[k]] = depMap;
}
else if(depMap.type != AssetMap.LoadType.Preload)
{
AssetMap tmp = new AssetMap();
tmp.name = depMap.name;
tmp.type = AssetMap.LoadType.Preload;
bundleLoadTypeMap[deps[k]] = tmp;
}
}
}
}
}
}
}
public IEnumerator PreloadAsset(Action callback)
{
foreach (var map in bundleLoadTypeMap.Values)
{
if (map.type == AssetMap.LoadType.Preload)
{
string assetName = map.name;
string path = string.Format("{0}{1}", Util.DataPath, assetName);
if (assetName.CustomEndsWith(".ab") && File.Exists(path))
{
if (!IsBundleLoaded(assetName))
{
preloadAbcr = AssetBundle.LoadFromFileAsync(path);
yield return preloadAbcr;
AddBundleToLoaded(assetName, preloadAbcr.assetBundle);
}
}
}
curIndex++;
if (curIndex % 20 == 0)
yield return null;
}
preloadAbcr = null;
if (callback != null) callback();
}
public Shader GetShader(string name)
{
for (int i = 0; i < shaderAssets.Length; ++i)
{
if (shaderAssets[i].name.Equals(name))
return shaderAssets[i] as Shader;
}
return null;
}
public IEnumerator PreloadShaderAndFont()
{
if (!AppConst.AssetBundleMode) yield break;
string dataPath = Util.DataPath; //数据目录
string resPath = AppPathUtils.StreamingPathFormat(LuaConst.osDir); //游戏包资源目录
//加载shader.ab
string shaderABName = "shader.ab";
string shaderFile = Path.Combine(resPath, shaderABName);
string outFile = Path.Combine(dataPath, shaderABName);
AssetMap map = new AssetMap();
map.name = shaderABName;
map.type = AssetMap.LoadType.Preload;
bundleLoadTypeMap.Add(shaderABName, map);
yield return preload(shaderFile, outFile, shaderABName);
//加载font.ab
string fontABName = "font.ab";
string fontFile = Path.Combine(resPath, fontABName);
outFile = Path.Combine(dataPath, fontABName);
map = new AssetMap();
map.name = fontABName;
map.type = AssetMap.LoadType.Preload;
bundleLoadTypeMap.Add(fontABName, map);
yield return preload(fontFile, outFile, fontABName);
font = GetBundleFromLoaded(fontABName).LoadAsset("FZCuYuan") as Font;
shaderAssets = GetBundleFromLoaded(shaderABName).LoadAllAssets();
Shader.WarmupAllShaders();
}
IEnumerator preload(string url, string outFile, string key)
{
WWW www = new WWW(url);
yield return www;
if (string.IsNullOrEmpty(www.error))
{
var abcr = AssetBundle.LoadFromMemoryAsync(www.bytes);
yield return abcr;
AddBundleToLoaded(key, abcr.assetBundle);
//bundleCache.Add(key, new BundleInfo(abcr.assetBundle, key));
AssetMap map;
if (bundleLoadTypeMap.TryGetValue(key, out map))
{
map.type = AssetMap.LoadType.Preload;
}
//preloadAssets.Add(key);
}
else
{
Debug.LogError(www.error);
yield break;
}
www.Dispose();
}
void Update()
{
if (preloadAbcr != null)
{
if (onProgressChange != null)
onProgressChange((float)(curIndex + 1 + preloadAbcr.progress) / (float)bundleLoadTypeMap.Count);
}
delayClearTime -= Time.deltaTime;
//if (Input.GetMouseButton(0) || Input.touchCount > 0)
//{
// delayClearTime = MAXDELAY_CLEAR_TIME;
//}
if (delayClearTime <= 0)
{
delayClearTime = MAXDELAY_CLEAR_TIME;
Util.ClearMemory();
}
}
private void FixedUpdate()
{
#if UNITY_IOS
float realTime = Time.realtimeSinceStartup;
if (unloadQueue.Count > 0)
{
BundleInfo info = unloadQueue.Dequeue();
if (info.refCount <= 0)
{
info.Unload();
limitedBundleCache.Remove(info._bundleName);
UnityEngine.Resources.UnloadUnusedAssets();
}
}
if (realTime - delayUnloadTime >= 10)
{
foreach (var val in limitedBundleCache.Values)
{
if (val.refCount <= 0)
unloadQueue.Enqueue(val);
}
delayUnloadTime = realTime;
}
#endif
}
public IEnumerator LoadSceneDependency(string sceneBundleName)
{
var deps = GetAllDependencies(sceneBundleName);
for (int i = 0; i < deps.Count; ++i)
{
if (deps[i].Contains("tmp/")) continue;
while (bundleLoadingQueue.Contains(deps[i]))
yield return Yielders.EndOfFrame;
BundleInfo bundleInfo;
if (GetBundleInfo(deps[i], out bundleInfo))
{
bundleInfo.refCount++;
}
else
{
using (zstring.Block())
{
zstring depPath = Util.DataPath + deps[i];
if (File.Exists(depPath))
{
bundleLoadingQueue.Add(deps[i]);
var abcr = AssetBundle.LoadFromFileAsync(depPath);
yield return abcr;
bundleLoadingQueue.Remove(deps[i]);
AddBundleToLoaded(deps[i], abcr.assetBundle);
//bundleLoaded.Add(deps[i], new BundleInfo(abcr.assetBundle, deps[i]));
}
else
{
Debug.LogWarning(zstring.Format("{0} not exists", depPath));
}
}
}
}
}
public void UnloadSceneDependency()
{
//if (sceneDependency != null)
// sceneDependency.Unload(false);
//sceneDependency = null;
}
public AssetBundle TryGetBundle(string bundleName)
{
AssetBundle bundle = null;
try
{
using (zstring.Block())
{
zstring key = bundleName;
bundle = GetBundleFromLoaded(key);
if (bundle == null)
{
if (bundleLoadingQueue.Contains(key))
{
Debug.LogWarning(zstring.Format("资源正在异步加载中: {0}", key));
return null;
}
else
{
var deps = GetAllDependencies(key);
for (int i = 0; i < deps.Count; ++i)
{
if (deps[i].Contains("tmp/")) continue;
var depBundle = GetBundleFromLoaded(deps[i]);
if (depBundle == null)
{
if (bundleLoadingQueue.Contains(deps[i]))
{
Debug.LogWarning(zstring.Format("资源正在异步加载中: {0}", key));
return null;
}
else
{
zstring depPath = Util.DataPath + deps[i];
if (File.Exists(depPath))
{
var temp = AssetBundle.LoadFromFile(depPath);
AddBundleToLoaded(deps[i], temp);
//bundleLoaded.Add(deps[i], new BundleInfo(temp, deps[i]));
}
else
{
throw new FileNotFoundException(zstring.Format("File {0} not exists", depPath));
}
}
}
}
zstring path = Util.DataPath + key;
if (File.Exists(path))
{
if (!IsBundleLoaded(key))
{
bundle = AssetBundle.LoadFromFile(path);
AddBundleToLoaded(key, bundle);
//bundleLoaded.Add(key, new BundleInfo(bundle, key));
}
else
{
throw new ArgumentException(zstring.Format("key {0} is already exist in bundleLoaded", key));
}
}
else
{
throw new FileNotFoundException(zstring.Format("File {0} not exists", path));
}
}
}
}
}
catch (Exception e)
{
Debug.LogWarning(string.Format("Get Assetbundle Exception, Name: {0}", bundleName));
Debug.LogException(e);
return null;
}
return bundle;
}
public AssetBundle TryGetBundleByFile(string fileName)
{
AssetBundle bundle = null;
string key;
if (!assetbundleMap.TryGetValue(fileName, out key))
{
Debug.LogWarning(string.Format("{0} has no assetbundle resource", fileName));
}
else
{
return TryGetBundle(key);
}
return bundle;
}
public IEnumerator TryToGetBundleAsync(string fileName, Action<AssetBundle> callback)
{
using (zstring.Block())
{
AssetBundle bundle = null;
string key;
if (!assetbundleMap.TryGetValue(fileName, out key))
{
Debug.LogError(zstring.Format("{0} has no assetbundle resource", fileName));
}
else
{
while (bundleLoadingQueue.Contains(key))
yield return Yielders.EndOfFrame;
bundle = GetBundleFromLoaded(key);
if (bundle == null)
{
bundleLoadingQueue.Add(key);
var deps = GetAllDependencies(key);
for (int i = 0; i < deps.Count; ++i)
{
if (string.IsNullOrEmpty(deps[i]) || deps[i].Contains("tmp/")) continue;
while (bundleLoadingQueue.Contains(deps[i]))
yield return Yielders.EndOfFrame;
var depBundle = GetBundleFromLoaded(deps[i]);
if (depBundle == null)
{
zstring depPath = Util.DataPath + deps[i];
if (File.Exists(depPath))
{
bundleLoadingQueue.Add(deps[i]);
var abcr = AssetBundle.LoadFromFileAsync(depPath);
yield return abcr;
bundleLoadingQueue.Remove(deps[i]);
AddBundleToLoaded(deps[i], abcr.assetBundle);
//bundleLoaded.Add(deps[i], new BundleInfo(abcr.assetBundle, deps[i]));
}
else
{
Debug.LogWarning(zstring.Format("{0} not exists", depPath));
}
}
}
zstring path = Util.DataPath + key;
if (File.Exists(path))
{
var mainAbcr = AssetBundle.LoadFromFileAsync(path);
yield return mainAbcr;
bundle = mainAbcr.assetBundle;
AddBundleToLoaded(key, bundle);
//if (!bundleLoaded.ContainsKey(key))
// bundleLoaded.Add(key, new BundleInfo(bundle, key));
}
else
{
Debug.LogWarning(zstring.Format("{0} not exists", path));
}
bundleLoadingQueue.Remove(key);
}
}
if (callback != null) callback(bundle);
}
}
public List<string> GetAllDependencies(string key)
{
List<string> result;
try
{
if (!dependenciesCache.TryGetValue(key, out result))
{
result = new List<string>();
result.AddRange(allBundleManifest.GetAllDependencies(key));
dependenciesCache.Add(key, result);
}
}
catch
{
result = new List<string>();
}
return result;
}
public bool GetBundleInfo(string bundleName, out BundleInfo bundleInfo)
{
bundleInfo = null;
if (!bundleCache.TryGetValue(bundleName, out bundleInfo))
return limitedBundleCache.TryGetValue(bundleName, out bundleInfo);
return true;
}
AssetBundle GetBundleFromLoaded(string bundleName)
{
BundleInfo bundleInfo;
AssetBundle bundle = null;
if (bundleCache.TryGetValue(bundleName, out bundleInfo))
{
bundle = bundleInfo.bundle;
}
else if (limitedBundleCache.TryGetValue(bundleName, out bundleInfo))
{
bundle = bundleInfo.bundle;
}
return bundle;
}
public void AddBundleToLoaded(string bundleName, AssetBundle bundle)
{
AssetMap map;
if (bundleLoadTypeMap.TryGetValue(bundleName, out map))
{
if (map.type == AssetMap.LoadType.Limited)
{
if (!limitedBundleCache.ContainsKey(bundleName))
limitedBundleCache.Add(bundleName, new BundleInfo(bundle, bundleName));
}
else
{
if (!bundleCache.ContainsKey(bundleName))
bundleCache.Add(bundleName, new BundleInfo(bundle, bundleName));
}
}
else
{
map = new AssetMap();
map.name = bundleName;
map.type = AssetMap.LoadType.None;
bundleLoadTypeMap.Add(bundleName, map);
if (!bundleCache.ContainsKey(bundleName))
bundleCache.Add(bundleName, new BundleInfo(bundle, bundleName));
}
}
bool IsBundleLoaded(string bundleName)
{
return bundleCache.ContainsKey(bundleName) || limitedBundleCache.ContainsKey(bundleName);
}
AssetMap.LoadType GetAssetLoadType(string assetName)
{
if (assetbundleMap.ContainsKey(assetName))
{
var key = assetbundleMap[assetName];
AssetMap map;
if (bundleLoadTypeMap.TryGetValue(key, out map))
return map.type;
}
return AssetMap.LoadType.None;
}
void RemoveBundle(string bundleName)
{
if (!bundleCache.ContainsKey(bundleName))
bundleCache.Remove(bundleName);
else if (!limitedBundleCache.ContainsKey(bundleName))
limitedBundleCache.Remove(bundleName);
}
public IPromise<T> LoadAssetAsync<T>(string assetName, string extension, GameObject owner)
where T : UnityEngine.Object
{
return new Promise<T>((resolved, reject) =>
{
new Promise<AssetBundle>((s, j) =>
{
StartCoroutine(TryToGetBundleAsync(assetName, s));
}).Then((bundle) =>
{
StartCoroutine(_loadBundleAsset(owner, assetName, extension, bundle, resolved));
}).Catch((e) =>
{
reject(e);
Debug.LogException(e);
});
});
}
public IPromise<GameObject> LoadPrefabAsync(string assetName)
{
return LoadAssetAsync<GameObject>(assetName, "prefab", null).Then((go) =>
{
using (zstring.Block())
{
if (go == null)
{
zstring assetPath = zstring.Concat(GResource.RuntimeAssetsRoot , assetName , ".prefab");
throw new Exception(zstring.Format("load prefab error: {0}", assetPath));
}
#if UNITY_EDITOR
Util.ResetShader(go);
#endif
string bundleName;
if (assetbundleMap.TryGetValue(assetName, out bundleName))
{
go.transform.GetOrAddComponent<AssetWatcher>().bundleName = bundleName;
}
else
{
Debug.LogErrorFormat("can't find {0} in bundleMap", assetName);
}
}
}).Catch(e =>
{
Debug.LogException(e);
});
}
#region -------------同步加载----------------------
/// <summary>
/// 同步加载Prefab文件
/// </summary>
/// <returns></returns>
public GameObject LoadPrefab(string name)
{
using (zstring.Block())
{
zstring zname = name.ToLower();
zstring assetName = zstring.Format("{0}.prefab", zname);
GameObject obj = LoadAssets<GameObject>(assetName);
if (obj != null)
{
#if UNITY_EDITOR
Util.ResetShader(obj);
#endif
string bundleName;
if (assetbundleMap.TryGetValue(zname, out bundleName))
{
obj.transform.GetOrAddComponent<AssetWatcher>().bundleName = bundleName;
}
else
{
Debug.LogErrorFormat("can't find {0} in bundleMap", zname);
}
}
else
{
Debug.LogWarning(string.Format("load prefab error: {0}, {1}", zname, assetName));
}
return obj;
}
}
public Sprite LoadSprite(GameObject owner, string spriteName, string atlasName)
{
using (zstring.Block())
{
zstring assetName = atlasName.ToLower();
zstring ext = Path.GetExtension(assetName);
if (!string.IsNullOrEmpty(ext))
assetName = assetName.Replace(ext, "");
string bundleRelativePath = assetName;
if (!assetbundleMap.TryGetValue(assetName, out bundleRelativePath))
{
Debug.LogWarning(zstring.Format("{0} has no assetbundle resource", assetName));
return null;
}
UIAtlasCache atlasCache = null;
if (!atlasMap.TryGetValue(bundleRelativePath, out atlasCache))
{
AssetBundle bundle = TryGetBundleByFile(assetName);
if (bundle == null) return null;
var assets = bundle.LoadAllAssets<Sprite>();
if (assets == null)
Debug.LogWarning(zstring.Format("Cant find sprite: {0} in bundle {1}", spriteName, bundleRelativePath));
atlasCache = new UIAtlasCache(assets);
atlasMap[bundleRelativePath] = atlasCache;
}
Sprite sprite = atlasCache.GetSprite(spriteName);
TextureWatcher watcher = owner.transform.GetOrAddComponent<TextureWatcher>();
watcher.AddBundleName(bundleRelativePath);
return sprite;
}
}
public Texture LoadTexture(GameObject owner, string assetPath)
{
using (zstring.Block())
{
zstring assetName = assetPath.ToLower();
zstring ext = Path.GetExtension(assetName);
if (!zstring.IsNullOrEmpty(ext))
assetName = assetName.Replace(ext, "");
AssetBundle bundle = TryGetBundleByFile(assetName);
if (bundle == null) return null;
TextureWatcher watcher = owner.transform.GetOrAddComponent<TextureWatcher>();
string bundleName;
if (assetbundleMap.TryGetValue(assetName, out bundleName))
watcher.AddBundleName(bundleName);
string assetRoot = GResource.RuntimeAssetsRoot.ToLower();
if (!assetName.StartsWith(assetRoot))
assetName = zstring.Concat(assetRoot, assetPath);
var asset = bundle.LoadAsset(assetName) as Texture;
if (asset == null)
Debug.LogWarning(zstring.Format("Cant find ab: {0}", assetName));
return asset;
}
}
/// <summary>
/// 加载字节数组
/// </summary>
/// <param name="path">无.bytes后缀的路径</param>
/// <returns></returns>
public byte[] LoadBytes(string path)
{
using (zstring.Block())
{
zstring zpath = path.ToLower();
TextAsset textAss = LoadAssets<TextAsset>(zstring.Format("{0}.bytes", zpath));
if (textAss != null)
return textAss.bytes;
return null;
}
}
/// <summary>
/// 同步加载资源
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path"></param>
/// <returns></returns>
public T LoadAssets<T>(string path) where T : UnityEngine.Object
{
using (zstring.Block())
{
zstring assetName = path.ToLower();
zstring ext = Path.GetExtension(assetName);
if (!zstring.IsNullOrEmpty(ext))
assetName = assetName.Replace(ext, "");
AssetBundle bundle = TryGetBundleByFile(assetName);
if (bundle == null) return null;
string assetRoot = GResource.RuntimeAssetsRoot.ToLower();
if (!assetName.StartsWith(assetRoot))
assetName = zstring.Concat(assetRoot , path);
var asset = bundle.LoadAsset(assetName) as T;
if (asset == null)
Debug.LogWarning(zstring.Format("Cant find ab: {0}", assetName));
return asset;
}
}
#endregion
public IPromise<AudioClip> LoadAudioClipBundleAsync(GameObject owner, string assetName, string extension)
{
assetName = assetName.ToLower();
return LoadAssetAsync<AudioClip>(assetName, extension, owner);
}
private IEnumerator _loadBundleAsset<T>(GameObject owner, string goName, string extension, AssetBundle bundle, Action<T> callback)
where T : UnityEngine.Object
{
if (bundle != null)
{
using (zstring.Block())
{
zstring assetName = zstring.Format("{0}{1}.{2}", GResource.RuntimeAssetsRoot.ToLower() , goName, extension.TrimStart('.'));
var abcr = bundle.LoadAssetAsync(assetName);
yield return abcr;
var mainAsset = (T)abcr.asset;
if (extension == ".asset")
{
TextAssetWatcher watcher = owner.transform.GetOrAddComponent<TextAssetWatcher>();
string bundleName;
if (assetbundleMap.TryGetValue(goName, out bundleName))
{
watcher.AddBundleName(bundleName);
}
else Debug.LogError("can't find " + goName + " in assetbundleMap");
}
callback(mainAsset);
}
}
else
callback(default(T));
}
public int GetRefCount(string assetName)
{
BundleInfo info;
if (GetBundleInfo(assetName, out info))
return info.refCount;
return -1;
}
#region LoadAsset & UnloadAsset
public void LoadAsset(string bundleName, GameObject go)
{
if (!assetIntanceCounts.ContainsKey(bundleName))
{
assetIntanceCounts.Add(bundleName, 1);
}
else
{
assetIntanceCounts[bundleName]++;
}
}
public void UnloadAsset(string bundleName, GameObject go)
{
bool unload = false;
if (assetIntanceCounts.ContainsKey(bundleName))
{
assetIntanceCounts[bundleName]--;
unload = assetIntanceCounts[bundleName] <= 0;
}
else
unload = true;
if (unload)
{
UnloadDependency(bundleName);
BundleInfo info;
if (GetBundleInfo(bundleName, out info)) info.refCount--;
assetIntanceCounts.Remove(bundleName);
}
}
public void LoadAsset(string assetName)
{
UIAtlasCache cache;
if (!atlasMap.TryGetValue(assetName, out cache))
{
BundleInfo info;
if (GetBundleInfo(assetName, out info))
{
LoadDependency(assetName);
info.refCount++;
}
else
{
Debug.LogError("load asset error! can't find asset in cache: " + assetName);
}
return;
}
cache.Load();
}
public void UnloadAsset(string name)
{
UIAtlasCache cache;
if (!atlasMap.TryGetValue(name, out cache))
{
BundleInfo info;
if (GetBundleInfo(name, out info))
{
UnloadDependency(name);
info.refCount--;
}
else
{
Debug.LogError("unload asset error! can't find asset in cache: " + name);
}
return;
}
if (cache.Unload())
{
BundleInfo info;
if (GetBundleInfo(name, out info))
{
UnloadDependency(name);
info.refCount--;
}
}
}
private void UnloadDependency(string name)
{
var deps = GetAllDependencies(name);
for (int i = 0; i < deps.Count; ++i)
{
BundleInfo info;
if (deps[i].Contains("tmp/")) continue;
if (GetBundleInfo(deps[i], out info))
info.refCount--;
}
}
private void LoadDependency(string name)
{
var deps = GetAllDependencies(name);
for (int i = 0; i < deps.Count; ++i)
{
BundleInfo info;
if (deps[i].Contains("tmp/")) continue;
if (GetBundleInfo(deps[i], out info))
info.refCount++;
}
}
public void Clear()
{
delayClearTime = MAXDELAY_CLEAR_TIME;
var keys = new List<string>();
foreach (var key in bundleCache.Keys)
{
if (bundleCache[key].refCount <= 0)
{
if (bundleCache[key].Unload())
keys.Add(key);
}
}
for (int i = 0; i < keys.Count; ++i)
{
if (atlasMap.ContainsKey(keys[i]))
atlasMap.Remove(keys[i]);
bundleCache.Remove(keys[i]);
}
foreach (var key in limitedBundleCache.Keys)
{
limitedBundleCache[key].Unload();
}
limitedBundleCache.Clear();
Util.ClearMemory();
}
#endregion
}
}<file_sep>/Assets/GameScript/Lua/Test/Collection/ArrayTest.lua
require "test"
test('is_array should returns false when object is not a table', function()
assertEqual(Array.isArray('lua'), false)
end)
test('is_array should returns false when the table is working like a dictionary', function()
assertEqual(Array.isArray({ language='lua' }), false)
end)
test('is_array should returns true when table is empty', function()
assertEqual(Array.isArray(Array.new({})), true)
end)
test('is_array should returns true when table is empty', function()
assertEqual(Array.isArray({}), true)
end)
test('is_array should returns true when table is working like an array', function()
assertEqual(Array.isArray({ 'a', 'b', 'c', 'd' }), true)
end)
test('isEmpty should returns false when table has at least one item', function()
assertEqual(Array.isEmpty(Array.new({ 'a' })), false)
end)
test('isEmpty should returns false when table does not have any item', function()
local array = Array.new({})
-- print("array:" .. array:length() .. ":" .. print_lua_table(array))
assertEqual(Array.isEmpty(array), true)
end)
test('first should returns nil when table is working like a dictionary', function()
local array = Array.new({language='lua'})
assertEqual(array:first(), nil)
end)
test('first should returns first item from table', function()
local array = Array.new({ 'a', 'b', 'c', 'd' })
assertEqual(array:first(), 'a')
end)
test('last should returns nil when table is working like a dictionary', function()
local array = Array.new({language='lua'})
assertEqual(array:last(), nil)
end)
test('last should returns last item from table', function()
local array = Array.new({ 'a', 'b', 'c', 'd' })
assertEqual(array:last(), 'd')
end)
test('slice should returns a empty table when it does not have any element', function()
local array = Array.new({})
local sliceArr = Array.slice(array , 1, 2)
assertEqual(sliceArr, nil)
end)
test('slice should returns a table with values between start index and end index', function()
local array = Array.new({ 'lua', 'javascript', 'python', 'ruby', 'c' })
local result = Array.slice(array , 2, 4)
assertEqual(type(result), 'table')
assertEqual(result:length(), 3)
assertEqual(result[1], 'javascript')
assertEqual(result[2], 'python')
assertEqual(result[3], 'ruby')
end)
test('slice should returns a table with every values from start index until last index', function()
local array = Array.new({ 'lua', 'javascript', 'python', 'ruby', 'c' })
local result = Array.slice(array , 2)
assertEqual(type(result), 'table')
assertEqual(result:length(), 4)
assertEqual(result[1], 'javascript')
assertEqual(result[2], 'python')
assertEqual(result[3], 'ruby')
assertEqual(result[4], 'c')
end)
test('reverse should returns an inverted table', function()
local array = Array.new({ 'lua', 'javascript', 'python'})
local result = array:reverse()
assertEqual(type(result), 'table')
assertEqual(result:length(), 3)
assertEqual(result[1], 'python')
assertEqual(result[2], 'javascript')
assertEqual(result[3], 'lua')
end)
-- test('map should returns a table with 2, 4, 6 values', function()
-- local result = array:map({ 1, 2, 3 }, function(value)
-- return value * 2
-- end)
-- assertEqual(type(result), 'table')
-- assertEqual(#result, 3)
-- assertEqual(result[1], 2)
-- assertEqual(result[2], 4)
-- assertEqual(result[3], 6)
-- end)
-- test('filter should returns a table with 10, 15, 20 values', function()
-- local result = array:filter({ 15, 10, 5, 3, 20 }, function(value)
-- return value >= 10
-- end)
-- assertEqual(type(result), 'table')
-- assertEqual(#result, 3)
-- assertEqual(result[1], 15)
-- assertEqual(result[2], 10)
-- assertEqual(result[3], 20)
-- end)
-- test('max should returns the biggest value from a table', function()
-- assertEqual(array:max({ 20, 22, 1, 3, 30, 42 }), 42)
-- end)
-- test('max should returns nil when table is empty', function()
-- assertEqual(array:max({}), nil)
-- end)
-- test('min should returns the smallest value from a table', function()
-- assertEqual(array:min({ 20, 22, 1, 3, 30, 42 }), 1)
-- end)
-- test('min should returns nil when table is empty', function()
-- assertEqual(array:min({}), nil)
-- end)
-- test('reduce should returns 90', function()
-- local result = array:reduce({ 20, 30, 40 }, function(memo, value)
-- return memo + value
-- end)
-- assertEqual(result, 90)
-- end)
-- test('reduce should returns 100', function()
-- local result = array:reduce({ 20, 30, 40 }, function(memo, value)
-- return memo + value
-- end, 10)
-- assertEqual(result, 100)
-- end)
test('indexOf should returns correct position of value in the table', function()
local array = Array.new({ 20, 30, 40, 50 })
assertEqual(array:indexOf(40), 3)
end)
test('indexOf should returns -1 when the value is not in the table', function()
local array = Array.new({ 20, 30, 40})
assertEqual(array:indexOf(50), -1)
end)
test("copy source array to dest array !" , function ()
local a = Array.new({1,2,3})
local b = Array.new("a" , 'b' , 'c')
Array.copy(a , 1 , b , b:length() + 1, a:length())
assertEqual(b:length() , 6)
assertEqual(b[4] , 1)
assertEqual(b[5] , 2)
assertEqual(b[6] , 3)
end)
test("copyTo should returns contain source array elements !" , function ()
local a = Array.new({1,2,3})
local b = Array.new("a" , 'b' , 'c')
a:copyTo(b , 1)
assertEqual(b:length() , 6)
assertEqual(b[4] , 1)
assertEqual(b[5] , 2)
assertEqual(b[6] , 3)
end)
test("append should returns contain all array elements !" , function ()
local a = {1,2,3}
local b = Array.new({"a" , 'b' , 'c'})
b:append(a)
assertEqual(b:length() , 6)
assertEqual(b[4] , 1)
assertEqual(b[5] , 2)
assertEqual(b[6] , 3)
b:append('e' , 'f' , 7 , 8)
assertEqual(b:length() , 10)
assertEqual(b[7] , 'e')
assertEqual(b[8] , 'f')
assertEqual(b[9] , 7)
assertEqual(b[10] , 8)
end)<file_sep>/Assets/Editor/SceneManagerEditor/IStrategy.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using UnityEngine;
using System.Collections;
/// <summary>
/// 描述:打包策略统一接口
/// <para>创建时间:</para>
/// </summary>
public interface IStrategy
{
/// <summary>
/// 开始流程
/// </summary>
void BeginProcess(BuildConfig buildConfig);
/// <summary>
/// 结束流程
/// </summary>
void EndProcess(BuildConfig buildConfig);
}
<file_sep>/Assets/GameScript/Lua/Engines/string.lua
string._htmlspecialchars_set = {}
string._htmlspecialchars_set["&"] = "&"
string._htmlspecialchars_set["\""] = """
string._htmlspecialchars_set["'"] = "'"
string._htmlspecialchars_set["<"] = "<"
string._htmlspecialchars_set[">"] = ">"
--[[--
将特殊字符转为 HTML 转义符
~~~ lua
print(string.htmlspecialchars("<ABC>"))
-- 输出 <ABC>
~~~
@param string input 输入字符串
@return string 转换结果
]]
function string.htmlspecialchars(input)
for k, v in pairs(string._htmlspecialchars_set) do
input = string.gsub(input, k, v)
end
return input
end
--[[--
将 HTML 转义符还原为特殊字符,功能与 string.htmlspecialchars() 正好相反
~~~ lua
print(string.restorehtmlspecialchars("<ABC>"))
-- 输出 <ABC>
~~~
@param string input 输入字符串
@return string 转换结果
]]
function string.restorehtmlspecialchars(input)
for k, v in pairs(string._htmlspecialchars_set) do
input = string.gsub(input, v, k)
end
return input
end
--[[--
将字符串中的 \n 换行符转换为 HTML 标记
~~~ lua
print(string.nl2br("Hello\nWorld"))
-- 输出
-- Hello<br />World
~~~
@param string input 输入字符串
@return string 转换结果
]]
function string.nl2br(input)
return string.gsub(input, "\n", "<br />")
end
--[[--
将字符串中的特殊字符和 \n 换行符转换为 HTML 转移符和标记
~~~ lua
print(string.nl2br("<Hello>\nWorld"))
-- 输出
-- <Hello><br />World
~~~
@param string input 输入字符串
@return string 转换结果
]]
function string.text2html(input)
input = string.gsub(input, "\t", " ")
input = string.htmlspecialchars(input)
input = string.gsub(input, " ", " ")
input = string.nl2br(input)
return input
end
--[[--
用指定字符或字符串分割输入字符串,返回包含分割结果的数组
~~~ lua
local input = "Hello,World"
local res = string.split(input, ",")
-- res = {"Hello", "World"}
local input = "Hello-+-World-+-Quick"
local res = string.split(input, "-+-")
-- res = {"Hello", "World", "Quick"}
~~~
@param string input 输入字符串
@param string delimiter 分割标记字符或字符串
@return array 包含分割结果的数组,起始下标index从1开始
]]
function string.split(input, delimiter)
input = tostring(input)
delimiter = tostring(delimiter)
if (delimiter=='') then return false end
local pos,arr = 0, {}
-- for each divider found
for st,sp in function() return string.find(input, delimiter, pos, true) end do
table.insert(arr, string.sub(input, pos, st - 1))
pos = sp + 1
end
table.insert(arr, string.sub(input, pos))
return arr
end
--[[--
去除输入字符串头部的空白字符,返回结果
~~~ lua
local input = " ABC"
print(string.ltrim(input))
-- 输出 ABC,输入字符串前面的两个空格被去掉了
~~~
空白字符包括:
- 空格
- 制表符 \t
- 换行符 \n
- 回到行首符 \r
@param string input 输入字符串
@return string 结果
@see string.rtrim, string.trim
]]
function string.ltrim(input)
return string.gsub(input, "^[ \t\n\r]+", "")
end
--[[--
去除输入字符串尾部的空白字符,返回结果
~~~ lua
local input = "ABC "
print(string.ltrim(input))
-- 输出 ABC,输入字符串最后的两个空格被去掉了
~~~
@param string input 输入字符串
@return string 结果
@see string.ltrim, string.trim
]]
function string.rtrim(input)
return string.gsub(input, "[ \t\n\r]+$", "")
end
--[[--
去掉字符串首尾的空白字符,返回结果
@param string input 输入字符串
@return string 结果
@see string.ltrim, string.rtrim
]]
function string.trim(input)
input = string.gsub(input, "^[ \t\n\r]+", "")
return string.gsub(input, "[ \t\n\r]+$", "")
end
--[[--
将字符串的第一个字符转为大写,返回结果
~~~ lua
local input = "hello"
print(string.ucfirst(input))
-- 输出 Hello
~~~
@param string input 输入字符串
@return string 结果
]]
function string.ucfirst(input)
return string.upper(string.sub(input, 1, 1)) .. string.sub(input, 2)
end
local function urlencodechar(char)
return "%" .. string.format("%02X", string.byte(char))
end
--[[--
将字符串转换为符合 URL 传递要求的格式,并返回转换结果
~~~ lua
local input = "hello world"
print(string.urlencode(input))
-- 输出
-- hello%20world
~~~
@param string input 输入字符串
@return string 转换后的结果
@see string.urldecode
]]
function string.urlencode(input)
-- convert line endings
input = string.gsub(tostring(input), "\n", "\r\n")
-- escape all characters but alphanumeric, '.' and '-'
input = string.gsub(input, "([^%w%.%- ])", urlencodechar)
-- convert spaces to "+" symbols
return string.gsub(input, " ", "+")
end
--[[--
将 URL 中的特殊字符还原,并返回结果
~~~ lua
local input = "hello%20world"
print(string.urldecode(input))
-- 输出
-- hello world
~~~
@param string input 输入字符串
@return string 转换后的结果
@see string.urlencode
]]
function string.urldecode(input)
input = string.gsub (input, "+", " ")
input = string.gsub (input, "%%(%x%x)", function(h) return string.char(checknumber(h,16)) end)
input = string.gsub (input, "\r\n", "\n")
return input
end
--[[--
计算 UTF8 字符串的长度,每一个中文算一个字符
~~~ lua
local input = "你好World"
print(string.utf8len(input))
-- 输出 7
~~~
@param string input 输入字符串
@return integer 长度
]]
function string.utf8len(input)
local len = string.len(input)
local left = len
local cnt = 0
local arr = {0, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc}
while left ~= 0 do
local tmp = string.byte(input, -left)
local i = #arr
while arr[i] do
if tmp >= arr[i] then
left = left - i
break
end
i = i - 1
end
cnt = cnt + 1
end
return cnt
end
--[[--
将数值格式化为包含千分位分隔符的字符串
~~~ lua
print(string.formatnumberthousands(1924235))
-- 输出 1,924,235
~~~
@param number num 数值
@return string 格式化结果
]]
function string.formatnumberthousands(num)
local formatted = tostring(checknumber(num))
local k
while true do
formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
if k == 0 then break end
end
return formatted
end
--返回当前字符实际占用的字符数
function string.subStringGetByteCount(str , index)
local curByte = string.byte(str , index)
local byteCount = 1
if curByte == nil then
byteCount = 0
elseif curByte > 0 and curByte <= 127 then
byteCount = 1
elseif curByte >= 192 and curByte <= 223 then
byteCount = 2
elseif curByte >= 224 and curByte <= 239 then
byteCount = 3
elseif curByte >= 240 and curByte <= 247 then
byteCount = 4
end
return byteCount
end
--获取中英混合UTF8 字符串的真实符数量
function string.subStringGetTotalIndex(str)
local curIndex = 0
local i = 1
local lastCount = 1
repeat
lastCount = string.subStringGetByteCount(str , i)
i = i + lastCount
curIndex = curIndex + 1
until(lastCount == 0)
return curIndex - 1
end
--获取中英混合UTF8 字符串的真实符数量
function string.subStringGetTrueIndex(str , index)
local curIndex = 0
local i = 1
local lastCount = 1
repeat
lastCount = string.subStringGetByteCount(str , i)
i = i + lastCount
curIndex = curIndex + 1
until(curIndex >= index)
return i - lastCount
end
--[[
字符串截取 索引从1开始截取
print(string.subString('字符串123截取') , 4)
--输出 123截取
print(string.subString('字符串123截取') , 4 , 7)
--输出 123截
@str 字符串
@startIndex 开始截取索引
@endIndex 结束索引 (可有可无)
]]
function string.subString(str , startIndex , endIndex)
if startIndex < 0 then
startIndex = string.subStringGetTotalIndex(str) + startIndex + 1
end
if endIndex ~= nil and endIndex < 0 then
endIndex = string.subStringGetTotalIndex(str) + endIndex + 1
end
if endIndex == nil then
return string.sub(str , string.subStringGetTrueIndex(str , startIndex))
else
return string.sub(str , string.subStringGetTrueIndex(str , startIndex) , string.subStringGetTrueIndex(str , endIndex + 1) -1)
end
end
--[[
字符串是否为空
]]
function string.isEmptyOrNil(str)
if str then
str = string.trim(str)
return string.len(str) <= 0
end
return true
end
function string.setColor(str,color)
return string.format("<color=%s>%s</color>",color,str)
end<file_sep>/Assets/GameScript/Lua/Localization/Localization.lua
Localization = {}
--初始化
function Localization:InitLocalization()
self.Keys = {}
self.files = {}
self.language = AppConst.Language.CHINESE
self:SetLanguage(self.language)
self:RegisterModule()
self:LoadData()
end
--注册功能模块配置表
function Localization:RegisterModule()
local function register_module(file)
local path = "Localization/"..self.language.."/"..file
table.insert(self.files,path)
end
--注册不同模块的配置表
for key, var in ipairs(AppConst.LocalizationModule) do
register_module(var)
end
end
--设置语言
function Localization:SetLanguage(languageType)
if self.language ~= languageType then
self.language = languageType
self:ClearKeys()
self:RegisterModule()
self:LoadData()
end
end
--加载配置表
function Localization:LoadData()
for key, var in pairs(self.files) do
local flie = require(var)
for key, var in pairs(flie) do
self.Keys[key] = var
end
end
end
--根据key获取value
function Localization:GetText(key)
local value = self.Keys[key]
assert(value,"not found value ,key = "..key)
return self.Keys[key]
end
--清除数据
function Localization:ClearKeys()
self.Keys = {}
end
--根据中的key获取对应的value,然后替换文本
function Localization:ReplaceByKey(key,count,...)
local str = self:GetText(key)
print(str)
return self:ReplaceText(str,count,...)
end
--替换字符串
function Localization:ReplaceText(str,count,...)
local args = {...}
print(...)
for key, var in ipairs(args) do
if key > count then
break
end
local match = "$"..key
str = string.gsub(str,match,tostring(var))
end
return str
end<file_sep>/Assets/GEngineScript/Core/ResourceSystem/Watcher/TextAssetWatcher.cs
using UnityEngine;
using System.Collections.Generic;
namespace GEX.Resource
{
public class TextAssetWatcher : MonoBehaviour {
public List<string> bundleNames = new List<string>();
public void AddBundleName(string bundleName)
{
bundleNames.Add(bundleName);
}
void OnDestroy()
{
if (AssetBundleManager.Instance != null)
{
for (int i = 0; i < bundleNames.Count; ++i)
{
AssetBundleManager.Instance.UnloadAsset(bundleNames[i]);
}
}
}
}
}
<file_sep>/Assets/GameScript/Lua/Localization/CN/LTCommon.lua
--多语言配置表
--避免key冲突,key命名规则:模块名+key 如:['LTCommon_Name'] = "商业大亨"
local LTCommon = {}
LTCommon.LTCommon_AppName = "商业大亨"
LTCommon.LTCommon_HeHe = "呵呵"
LTCommon.LTCommon_DongWang = "动网$1商业$2"
return LTCommon<file_sep>/Assets/Editor/SceneManagerEditor/BuildConfig.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngineInternal;
/// <summary>
/// 资源工具所需的全局路径
/// </summary>
public class BuildGlobal
{
/// <summary>
/// 保存导出文件的根目录
/// </summary>
public static string EXPORT_BUNDLE_ROOT
{
get
{
string path = Path.Combine(Application.dataPath, "../../export/");
path = Path.GetFullPath(path);
return path;
}
}
/// <summary>
/// 配置保存目录
/// </summary>
public static string EXPORT_CONFIG_DIR = EXPORT_BUNDLE_ROOT + "Config/";
public const string Meta = ".meta";
public static HashSet<string> FilterAsset = new HashSet<string>()
{
".cs" , ".shader"
};
//全局索引文件,只映射指定类型的文件
public static HashSet<string> MapIndexFilter = new HashSet<string>(new[] { ".prefab", ".txt" });
}
/// <summary>
/// 描述:打包配置
/// <para>创建时间:</para>
/// </summary>
[Serializable]
public class BuildConfig
{
/// <summary>
/// 自定义的Bundle名称(可选)
/// </summary>
[SerializeField]
public string BundleName = "";
/// <summary>
/// 输入路径
/// </summary>
[SerializeField]
public string InputDir="";
/// <summary>
/// 输出路径
/// </summary>
[SerializeField]
public string OutputDir="";
/// <summary>
/// 打包策略
/// </summary>
[SerializeField]
public string BuildStrategy;
/// <summary>
/// 文件查找方式
/// </summary>
[SerializeField]
public SearchOption OptionSerach;
/// <summary>
/// 前置打包
/// </summary>
[SerializeField]
public string PreBuild;
/// <summary>
/// 文件后缀
/// </summary>
[SerializeField]
public string FileSuffixs = "*.prefab";
/// <summary>
/// 资源的分类
/// </summary>
[SerializeField]
public string AssetType = "None";
}
public class BuildConfigManager : ASingleton<BuildConfigManager>
{
private Dictionary<string , BuildConfig> configDic = new Dictionary<string, BuildConfig>();
private string allPath = Path.Combine(BuildGlobal.EXPORT_CONFIG_DIR, "buildConfigs.json");
private BuildConfigManager() { }
public void ReadConfig()
{
configDic.Clear();
if (!File.Exists(allPath)) return;
string configJson = File.ReadAllText(allPath);
BuildConfig[] configs = AssetBundleUtil.FromJsonArray<BuildConfig>(ref configJson);
foreach (BuildConfig buildConfig in configs)
{
AddBuildConfig(buildConfig);
}
}
public void SaveConfig() {
string jsonStr = AssetBundleUtil.ToJsonArray(BuildConfigs);
if (string.IsNullOrEmpty(jsonStr)) return;
string dir = Path.GetDirectoryName(allPath);
if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);
File.WriteAllText(allPath , jsonStr);
}
public BuildConfig GetBuildConfig(string key)
{
if (!configDic.ContainsKey(key)) return null;
return configDic[key];
}
public BuildConfig[] BuildConfigs
{
get
{
BuildConfig[] configs = new BuildConfig[configDic.Count];
configDic.Values.CopyTo(configs , 0);
return configs;
}
}
public BuildConfig AddBuildConfig(string configName)
{
if (configDic.ContainsKey(configName)) return configDic[configName];
BuildConfig bc = new BuildConfig();
bc.BundleName = configName;
configDic[configName] = bc;
return bc;
}
public BuildConfig AddBuildConfig(BuildConfig bc)
{
if (configDic.ContainsKey(bc.BundleName)) return configDic[bc.BundleName];
configDic[bc.BundleName] = bc;
return bc;
}
/// <summary>
/// 根据资源的项目相对路径查找对应的配置信息
/// </summary>
/// <param name="assetPath">相对项目的路径 eg:Assets/Res/xxx.prefab</param>
/// <returns></returns>
public BuildConfig FindAssetBuildConfig(string assetPath)
{
string assetRootPath = assetPath.Substring(0 , assetPath.LastIndexOf("/"));
assetRootPath = assetRootPath.Replace("Assets/", "");
//查找最佳匹配
int length = 0;
BuildConfig config = null;
foreach (BuildConfig buildConf in configDic.Values)
{
if (assetRootPath.StartsWith(buildConf.InputDir) && buildConf.InputDir.Length > length)
{
length = buildConf.InputDir.Length;
config = buildConf;
}
}
return config;
}
public void RemoveConfig(string configName)
{
configDic.Remove(configName);
}
}
public sealed class AssetBundleUtil
{
/// <summary>
/// 分配Bundle管理
/// </summary>
/// <param name="assetPath">资源的项目相对路径 eg:Assets/Res/xxx.unity</param>
/// <param name="bundleName">AssetBundle的名称 eg:Res01/res</param>
/// <param name="variant"></param>
public static void AssignBundle(string assetPath, string bundleName, string variant)
{
AssetImporter assetImpt = AssetImporter.GetAtPath(assetPath);
if (assetImpt == null) return;
assetImpt.assetBundleName = bundleName;
assetImpt.assetBundleVariant = variant;
}
/// <summary>
/// 分配Bundle管理
/// </summary>
/// <param name="assetPath">资源的项目相对路径 eg:Assets/Res/xxx.unity</param>
/// <param name="bundleName">AssetBundle的名称 eg:Res01/res</param>
public static void AssignBundle(string assetPath, string bundleName)
{
if (assetPath.IndexOf(":") != -1)
assetPath = assetPath.Replace(Application.dataPath, "Assets");
string newBundleName = bundleName;
if (!bundleName.EndsWith(".assetsbundle"))
newBundleName += ".assetsbundle";
AssignBundle(assetPath , newBundleName, null);
}
/// <summary>
/// 清除Bundle绑定
/// </summary>
/// <param name="assetPath">资源的项目相对路径 eg:Assets/Res/xxx.unity</param>
public static void ClearBundle(string assetPath)
{
if (assetPath.IndexOf(":") != -1)
assetPath = assetPath.Replace(Application.dataPath, "Assets");
AssignBundle(assetPath , null, null);
}
public static string FormatOutputPath(BuildConfig buildConf)
{
return FormatOutputPath(buildConf.OutputDir);
}
/// <summary>
/// 格式化输出路径
/// </summary>
/// <param name="outputPath">相对路径格式 eg:../../xxxx/</param>
/// <returns>完整的绝对输出路径</returns>
public static string FormatOutputPath(string outputPath)
{
string allPath = Path.Combine(BuildGlobal.EXPORT_BUNDLE_ROOT, outputPath);
allPath = Path.GetFullPath(allPath);
return allPath;
}
/// <summary>
/// 同一目录,多个文件打包到同一个Bundle内
/// </summary>
/// <param name="bundleName"></param>
/// <param name="assetType"></param>
/// <param name="absolutionPath"></param>
/// <param name="findFile"></param>
/// <param name="optionSearch"></param>
public static void MulInOneBundle(string bundleName, string assetType,
string absolutionPath, string[] findFile, SearchOption optionSearch)
{
List<string> files = new List<string>();
foreach (string fileSuffix in findFile)
{
string[] fileArr = Directory.GetFiles(absolutionPath, fileSuffix, optionSearch);
files.AddRange(fileArr);
}
//为文件分配到指定Bundle
List<string> allBundleFile = new List<string>();
foreach (string filePath in files)
{
if (filePath.EndsWith(BuildGlobal.Meta)) continue;
string relativePath = filePath.Replace("\\", "/");
relativePath = relativePath.Replace(Application.dataPath, "Assets");
List<string> bundleFiles = AssetBuildEditor.Instance.AssignBundle(bundleName, relativePath, bundleName);
allBundleFile.AddRange(bundleFiles);
}
}
#region ----------------JSON 序列化--------------------------------------
public static T[] FromJsonArray<T>(ref string json)
{
Wrapper<T> wrapper = JsonUtility.FromJson<Wrapper<T>>(json);
return wrapper.array;
}
public static string ToJsonArray<T>(T[] array)
{
if (array == null || array.Length <= 0) return null;
Wrapper<T> wrapper = new Wrapper<T>();
wrapper.array = array;
return JsonUtility.ToJson(wrapper);
}
[Serializable]
private class Wrapper<T>
{
public T[] array;
}
#endregion
}<file_sep>/Assets/GameScript/Lua/Net/gInterface.lua
GInterfaces = {}
function ClearAllInterface()
for obj,interface in pairs(GInterfaces) do
for k, v in pairs(interface) do
interface[k] = nil
end
end
GInterfaces = {}
end
function DeclareInterface(obj,intfacename)
obj._interfaces_ = obj._interfaces_ or {}
obj._interfaces_[intfacename] = {}
end
function ListenInterface(obj,intfaceName,listener)
assert(listener,"listener is nil")
local _interfaces_ = obj._interfaces_
assert(_interfaces_,"object have no declare any interface!")
local interface = _interfaces_[intfaceName]
assert(interface,"object have no declare this interface!")
for key, var in pairs(interface) do
if var == listener then
assert(false,"listener already added!")
return
end
end
if table.empty(interface) then
GInterfaces[obj] = interface
end
table.insert(interface,listener)
end
function RemoveInterface(obj,intfaceName,listener)
assert(listener,"listener is nil")
local _interfaces_ = obj._interfaces_
assert(_interfaces_,"object have no declare any interface!")
local interface = _interfaces_[intfaceName]
assert(interface,"object have no declare this interface!")
for key, var in pairs(interface) do
if var == listener then
interface[key] = nil
if table.empty(interface) then
GInterfaces[obj] = nil
end
return
end
end
assert(false,"listener was not be added!")
end
function NotifyEvent(obj,intfaceName,eventName,...)
local _interfaces_ = obj._interfaces_
assert(_interfaces_,"object have no declare any interface!")
local interface = _interfaces_[intfaceName]
assert(interface,"object have no declare this interface!")
for k,v in pairs(interface) do
local fn = v[eventName]
if fn then
fn(v,...)
end
end
end
<file_sep>/Assets/GEngineScript/Core/ResourceSystem/Base/LoadEditorAssetAsync.cs
using System;
using LuaInterface;
namespace GEX.Resource
{
/// <summary>
/// 加载开发期的资源
/// </summary>
public class LoadEditorAssetAsync : LoadOperation
{
private UnityEngine.Object mainAsset;
private enum ELoadType
{
AssetPath , Prefab
}
private ELoadType loadType;
public LoadEditorAssetAsync(string path)
: base(path)
{
loadType = ELoadType.AssetPath;
}
public LoadEditorAssetAsync(UnityEngine.Object asset , string path)
: base(path)
{
mainAsset = asset;
loadType = ELoadType.Prefab;
}
public override void OnLoad()
{
#if UNITY_EDITOR
if(loadType == ELoadType.AssetPath)
{
mainAsset = UnityEditor.AssetDatabase.LoadAssetAtPath<UnityEngine.Object>(assetPath);
if (mainAsset == null)
UnityEngine.Debug.LogError("Cant find Asset! " + assetPath);
}
#endif
}
public override bool IsDone()
{
this.onFinishEvent();
return true;
}
[NoToLua]
public override T GetAsset<T>()
{
return (T)mainAsset;
}
}
}
<file_sep>/Assets/GameScript/Manager/LuaManager.cs
using UnityEngine;
using System.Collections;
using LuaInterface;
namespace LuaFramework {
public class LuaManager : BaseLuaManager {
private LuaLoader loader;
// Use this for initialization
protected void Awake() {
loader = new LuaLoader();
base.Awake();
}
public void InitStart() {
InitLuaBundle();
base.InitStart();
this.StartMain();
}
void StartMain()
{
lua.DoFile("AppMain.lua");
LuaFunction main = lua.GetFunction("AppMain.Main");
main.Call();
main.Dispose();
}
/// <summary>
/// 初始化LuaBundle
/// </summary>
void InitLuaBundle() {
if (loader.beZip) {
loader.AddBundle("lua/lua.unity3d");
loader.AddBundle("lua/lua_math.unity3d");
loader.AddBundle("lua/lua_system.unity3d");
loader.AddBundle("lua/lua_system_reflection.unity3d");
loader.AddBundle("lua/lua_unityengine.unity3d");
loader.AddBundle("lua/lua_common.unity3d");
loader.AddBundle("lua/lua_logic.unity3d");
loader.AddBundle("lua/lua_view.unity3d");
loader.AddBundle("lua/lua_controller.unity3d");
loader.AddBundle("lua/lua_misc.unity3d");
loader.AddBundle("lua/lua_protobuf.unity3d");
loader.AddBundle("lua/lua_3rd_cjson.unity3d");
loader.AddBundle("lua/lua_3rd_luabitop.unity3d");
loader.AddBundle("lua/lua_3rd_pbc.unity3d");
loader.AddBundle("lua/lua_3rd_pblua.unity3d");
loader.AddBundle("lua/lua_3rd_sproto.unity3d");
}
}
public void Close() {
LuaFunction destroy = lua.GetFunction("AppMain.Destroy");
destroy.Call();
destroy.Dispose();
loader = null;
base.Close();
}
}
}<file_sep>/Assets/GameScript/Lua/GameState/LoginState.lua
--[[
Author: LiangZG
Email : <EMAIL>
]]
local BaseState = require "Common.BaseState"
--[[
登录主状态,登录、选服、创号等功能
]]
local LoginState = class("LoginState" , BaseState)
function LoginState:OnEnter()
print("LoginState ---> OnEnter")
end
function LoginState:OnExit()
print("LoginState <---- OnExit")
end
return LoginState<file_sep>/Assets/GameScript/Lua/Net/Protocol/Admin.lua
--local NetREQ_ = NetREQ
NetProtoAdmin = {}
NetProto.NetModule[200] = NetProtoAdmin
NetProtoAdmin.st = {
}
NetProtoAdmin.send = {
['GetServerState'] = function(T)
if not(T:result()) then return end
end,
['Maintenance'] = function(T)
if not(T:result()) then return end
end,
}
-- ***自动提示帮助***
local T = NetProto.st
-- ***请求处理***
--获取服务器动态配置状态(1已设置;0未设置)
NetProtoAdmin.SendGetServerState = {
['new'] = NetProto.new,
['_MOD_'] = 200,
['_MED_'] = 23,
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoAdmin.send.GetServerState, T.vint32, fnRespond)
end,
}
--维护服务器
NetProtoAdmin.SendMaintenance = {
['new'] = NetProto.new,
['_MOD_'] = 200,
['_MED_'] = 24,
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoAdmin.send.Maintenance, T.vint32, fnRespond)
end,
}
-- ***推送处理***
NetProtoAdmin.MesssagePush = {
}
DeclareInterface(NetProtoAdmin, 'msgPushInterface')
function NetProtoAdmin.listenMessagePush(listener)
ListenInterface(NetProtoAdmin, 'msgPushInterface', listener)
end
function NetProtoAdmin.removeMessagePush(listener)
RemoveInterface(NetProtoAdmin, 'msgPushInterface', listener)
end
<file_sep>/Assets/GameScript/Lua/Util/TaskExceuter.lua
--[[
Author: LiangZG
Desc : 任务执行器
]]
local TaskExeuter = class("TaskExeuter" , Task)
local m = TaskExeuter
return TaskExeuter<file_sep>/Assets/GEngineScript/Core/NetworkSystem/Socket/PacketMsg.cs
using System;
using System.IO;
namespace GEX.Network
{
/// <summary>
/// 消息解包
/// </summary>
public sealed class PacketMsg
{
public enum PacketReadState
{
WAIT_NEW_PACKET,
WAIT_DATA_SIZE,
WAIT_DATA_SIZE_FRAGMENT,
WAIT_DATA,
INVALID_DATA,
}
private MemoryStream packetStream ;
private static readonly int INT_BYTE_SIZE = 4;
private int _expectedLength = -1;
private PacketReadState readState;
private int _skipBytes;
public Action<byte[]> OnBroadcastPacket;
public PacketMsg()
{
packetStream = new MemoryStream();
readState = PacketReadState.WAIT_NEW_PACKET;
}
/// <summary>
/// 解析数据包
/// </summary>
/// <param name="msgs"></param>
public void ParsePacketMsg(byte[] msgs)
{
if (msgs.Length <= 0)
throw new Exception("Unexpected empty packet msgs: no readable bytes available!");
ByteArray data = new ByteArray(msgs);
while (data.BytesAvailable > 0)
{
if (this.readState == PacketReadState.WAIT_NEW_PACKET)
this.readNewPacket(data);
else if (this.readState == PacketReadState.WAIT_DATA_SIZE)
this.readMsgSize(data);
else if (this.readState == PacketReadState.WAIT_DATA_SIZE_FRAGMENT)
this.readMsgFragment(data);
else if (this.readState == PacketReadState.WAIT_DATA)
this.readPacketData(data);
else if (this.readState == PacketReadState.INVALID_DATA)
this.readInvalidData(data);
}
}
/// <summary>
/// 开始读取新包
/// </summary>
/// <param name="data"></param>
private void readNewPacket(ByteArray data)
{
this.packetStream.Seek(0, SeekOrigin.Begin);
this.packetStream.SetLength(0);
this._expectedLength = -1;
this.readState = PacketReadState.WAIT_DATA_SIZE;
}
/// <summary>
/// 读取数据的大小
/// </summary>
/// <param name="msg"></param>
private void readMsgSize(ByteArray msg)
{
int num = msg.ReadInt();
int pos = PacketMsg.INT_BYTE_SIZE;
if (num != -1)
{
this._expectedLength = num;
resizeByteArray(msg , msg.Length - pos);
this.readState = PacketReadState.WAIT_DATA;
return;
}
this.readState = PacketReadState.WAIT_DATA_SIZE_FRAGMENT;
resizeByteArray(msg, msg.Length);
}
/// <summary>
/// 读取消息的数据片段
/// </summary>
/// <param name="msg"></param>
private void readMsgFragment(ByteArray msg)
{
int num1 = PacketMsg.INT_BYTE_SIZE - (int)this.packetStream.Length;
if (msg.Length >= num1)
{
resizeByteArray(msg, num1);
if (msg.Length > num1)
{
resizeByteArray(msg , msg.Length - num1);
}
this.readState = PacketReadState.WAIT_DATA;
return ;
}
resizeByteArray(msg, msg.Length);
}
/// <summary>
/// 非法数据读取
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
private void readInvalidData(ByteArray data)
{
if (this._skipBytes == 0)
{
this.readState = PacketReadState.WAIT_NEW_PACKET;
return ;
}
int pos = Math.Min(data.Length, this._skipBytes);
resizeByteArray(data , data.Length - pos);
this._skipBytes = this._skipBytes - pos;
}
private void readPacketData(ByteArray data)
{
int num = this._expectedLength - (int)this.packetStream.Length;
bool flag = data.Length >= num;
try
{
if (flag)
{
resizeByteArray(data, num);
this.packetStream.Flush();
this.dispatchRequest(this.packetStream);
this.readState = PacketReadState.WAIT_NEW_PACKET;
resizeByteArray(data, data.Length - num);
}
else
resizeByteArray(data, data.Length);
}
catch (Exception ex)
{
Debugger.LogException("Error handling data ", ex);
this._skipBytes = num;
this.readState = PacketReadState.INVALID_DATA;
}
}
private void dispatchRequest(MemoryStream stream)
{
// IMPObject mpObject = (IMPObject)MPObject.NewFromBinaryData(_buffer);
// Packet packet = new Packet();
// if (mpObject.IsNull("a"))
// throw new Exception("Request rejected: No Action ID in request!");
// packet.ActionID = mpObject.GetByte("a");
// packet.Parameters = mpObject.GetMPObject("p");
// this._controller.HandlePacket(packet);
byte[] packetMsgs = stream.ToArray();
OnBroadcastPacket.Invoke(packetMsgs);
}
private void resizeByteArray(ByteArray data, int len)
{
if (len <= 0) return;
byte[] buf = data.ReadBytes(len);
packetStream.Write(buf , 0 , buf.Length);
}
}
}
<file_sep>/Assets/Libs/LuaDataBind/UI/Command/NguiEventCommand.cs
using UnityEngine;
using System.Collections.Generic;
using LuaInterface;
namespace LuaDataBind
{
/// <summary>
/// Base class for a command when a NGUI event on a widget occured.
/// </summary>
/// <typeparam name="TWidget">Type of widget to monitor.</typeparam>
public abstract class NguiEventCommand<TWidget> : Command
where TWidget : MonoBehaviour
{
/// <summary>
/// Target widget to work with.
/// </summary>
[HideInInspector]
public TWidget Target;
protected override void Awake()
{
base.Awake();
if (this.Target == null)
{
this.Target = this.GetComponent<TWidget>();
}
}
/// <summary>
/// Returns the event from the specified target to observe.
/// </summary>
/// <param name="target">Target behaviour to get event from.</param>
/// <returns>Event from the specified target to observe.</returns>
protected abstract List<EventDelegate> GetEvent(TWidget target);
/// <summary>
/// Unity callback.
/// </summary>
protected virtual void OnDisable()
{
if (this.Target != null)
{
EventDelegate.Remove(this.GetEvent(this.Target), this.OnEvent);
}
}
/// <summary>
/// Unity callback.
/// </summary>
protected virtual void OnEnable()
{
if (this.Target != null)
{
EventDelegate.Add(this.GetEvent(this.Target), this.OnEvent);
}
}
/// <summary>
/// Called when the observed event occured.
/// </summary>
protected virtual void OnEvent()
{
this.invokeCommand();
}
protected override void invokeCommand()
{
if (Context == null || Context.LuaView == null) return;
LuaTable modelTable = Context.LuaView;
LuaFunction func = modelTable.GetLuaFunction(Func);
if (func == null)
{
Debug.LogWarning("Cant find Lua Function ! Function name is " + Func);
return;
}
func.BeginPCall();
func.Push(modelTable);
func.Push(this.Target);
func.PCall();
func.EndPCall();
}
}
}<file_sep>/Assets/GEngineScript/Core/ResourceSystem/Watcher/AssetWatcher.cs
using UnityEngine;
namespace GEX.Resource
{
public sealed class AssetWatcher : MonoBehaviour
{
public string bundleName;
private bool loaded = false;
void OnEnable()
{
if (!loaded)
AssetBundleManager.Instance.LoadAsset(bundleName, gameObject);
loaded = true;
}
void OnDisable()
{
loaded = false;
if (AssetBundleManager.Instance != null)
AssetBundleManager.Instance.UnloadAsset(bundleName, gameObject);
}
}
}
<file_sep>/Assets/GameScript/Lua/UI/Common/init.lua
-- @Author: <EMAIL>
-- @Desc: 公共UI
import (".NoticePanel")<file_sep>/Assets/GameScript/Lua/Test/test.lua
local format = string.format
function test( name , func )
xpcall(function ( )
func()
print(format("[pass] %s" , name))
end,function ( err )
logError(format("[fail] %s : %s" , name , err))
end
)
end
function _equal( a , b )
return a == b
end
function assertEqual( a , b )
assert(_equal(a , b))
end
<file_sep>/Assets/GameScript/Lua/Net/Proto.lua
NetProto = {}
NetProto.NetModule = {}
function NetProto.readArray(T,readFunc)
local arrayCount = T._v_:readVarint16()
local o = {}
for i=1,arrayCount do
local o2 = {}
local T2 = NetProto.TE.create(NetProto.RT,T._v_,o2)
local key = '_array_'..i
readFunc(T2,key)
if o2[key] ~= nil then
table.insert(o,o2[key])
else
table.insert(o,o2)
end
end
return o
end
function NetProto.writeArray(T,s,writeFunc)
local len = 0
local array = T._o_[s]
assert(array,"REQ param is nil!")
for k,v in pairs(array) do
len = len + 1
end
T._v_:writeVarint16(len)
local T2 = NetProto.TE.create(NetProto.WT,T._v_,array)
for key, var in pairs(array) do
writeFunc(T2,key)
end
end
function NetProto.readStruct(T,s,st)
local o = {}
local T2 = NetProto.TE.create(NetProto.RT,T._v_,o)
st(T2)
T._o_[s] = o
end
NetProto.RT = {
['result'] = function(self,s)
local c = self._v_:readVarint8()
local rst = ( c > 0)
self._o_['_result_'] = rst
return rst
end,
['string'] = function(self,s) self._o_[s] = self._v_:readString() end,
['int8'] = function(self,s) self._o_[s] = self._v_:readInt8() end,
['int16'] = function(self,s) self._o_[s] = self._v_:readInt16() end,
['int32'] = function(self,s) self._o_[s] = self._v_:readInt32() end,
['int64'] = function(self,s) self._o_[s] = self._v_:readInt64() end,
['vstring'] = function(self,s) self._o_[s] = self._v_:readVarintString()end,
['vint8'] = function(self,s) self._o_[s] = self._v_:readVarint8() end,
['vint16'] = function(self,s) self._o_[s] = self._v_:readVarint16() end,
['vint32'] = function(self,s) self._o_[s] = self._v_:readVarint32() end,
['vint64'] = function(self,s) self._o_[s] = self._v_:readVarint64() end,
['array'] = function(self,s,st) self._o_[s] = NetProto.readArray(self,st) end,
['struct'] = NetProto.readStruct,
}
NetProto.RT.__index = NetProto.RT
NetProto.WT = {
['result'] = function() return true end,
['string'] = function(self,s)assert(self._o_[s]) self._v_:writeString(self._o_[s]) end,
['int8'] = function(self,s)assert(self._o_[s]) self._v_:writeInt8(self._o_[s]) end,
['int16'] = function(self,s)assert(self._o_[s]) self._v_:writeInt16(self._o_[s]) end,
['int32'] = function(self,s)assert(self._o_[s]) self._v_:writeInt32(self._o_[s]) end,
['int64'] = function(self,s)assert(self._o_[s]) self._v_:writeInt64(self._o_[s]) end,
['vstring'] = function(self,s)assert(self._o_[s]) self._v_:writeVarintString(self._o_[s]) end,
['vint8'] = function(self,s)assert(self._o_[s]) self._v_:writeVarint8(self._o_[s]) end,
['vint16'] = function(self,s)assert(self._o_[s]) self._v_:writeVarint16(self._o_[s]) end,
['vint32'] = function(self,s)assert(self._o_[s]) self._v_:writeVarint32(self._o_[s]) end,
['vint64'] = function(self,s)assert(self._o_[s]) self._v_:writeVarint64(self._o_[s]) end,
['array'] = function(self,s,st) NetProto.writeArray(self,s,st) end
}
NetProto.WT.__index = NetProto.WT
NetProto.st = {
['result'] = function() return true end,
['int8'] = function(T) T:int8('int8') end,
['int16'] = function(T) T:int16('int16') end,
['int32'] = function(T) T:int32('int32') end,
['int64'] = function(T) T:int64('int64') end,
['string'] = function(T) T:string('string') end,
['vint8'] = function(T) T:vint8('vint8') end,
['vint16'] = function(T) T:vint16('vint16') end,
['vint32'] = function(T) T:vint32('vint32') end,
['vint64'] = function(T) T:vint64('vint64') end,
['vstring'] = function(T) T:vstring('vstring') end,
['array'] = function(st) return function(T) T:array('array',st) end end,
['void'] = function(T) --[[-T:vstring(string.format(%d,#T._o_))]] end,
}
NetProto.TE = {}
function NetProto.TE.create(T,v,o)
local o2 = {}
setmetatable(o2,T)
o2['_v_'] = v
o2['_o_'] = o
return o2
end
function NetProto.readStructArray(T,readFunc)
local arrayCount = T._v_:readVarint16()
local o = {}
for i=1,arrayCount do
local o2 = {}
local T2 = NetProto.TE.create(NetProto.RT,T._v_,o2)
readFunc(T2)
table.insert(o,o2)
end
return o
end
function NetProto.handleSendPackHead(packVarStrem,ModuleNumber,MethodNuber)
--清空缓冲
local packBuffer = packVarStrem:byteBuffer()
packBuffer:clearBuffer()
--写包头
packVarStrem:writeInt8(ModuleNumber)
packVarStrem:writeInt8(MethodNuber)
packVarStrem:writeInt32(0)--预留六字节
packVarStrem:writeInt16(0)
end
function NetProto.handleReceivePackHead(varStream,ModuleNumber,MethodNuber)
local buffer = varStream:byteBuffer()
-- 消耗 1字节包头
local datatlen = buffer:dataSize()
local sn = varStream:readInt8()
--读包头
local module = varStream:readVarint8()
local method = varStream:readVarint8()
--断言回应方法与之对应
assert(module == ModuleNumber,'respond module number no match!')
assert(method == MethodNuber,'respond module number no match!')
end
function NetProto.new(cls)
local instance = {}
cls.__index = cls
rawset(instance,'class',cls)
setmetatable(instance, cls)
return instance
end
return nil
<file_sep>/Assets/GameScript/Lua/Net/init.lua
--[[
@Author: <EMAIL>
网络模块
]]
local NET_MODE = ...
require('Net/Proto')
require('Net/gInterface')
require "Net/NetClient"
Dequeue = require ('Net/Dequeue')
--��������
GameNet = NetClient
NetClient:init()
--NetClient:setIp("192.168.22.45",10102)
local function load_net_file(file)
--table.insert(require_files,'Net/Protocol/'..file)
require('Net/Protocol/'..file)
--log("Net/Protocol/"..file)
end
load_net_file('Activity')
load_net_file('Admin')
load_net_file('Api')
load_net_file('Chat')
load_net_file('Item')
load_net_file('Mail')
load_net_file('Notice')
load_net_file('Task')
load_net_file('User')
<file_sep>/Assets/GameScript/Lua/Net/Protocol/Item.lua
--local NetREQ_ = NetREQ
NetProtoItem = {}
NetProto.NetModule[4] = NetProtoItem
NetProtoItem.st = {
['GoodVO'] = function(T)
if not(T:result()) then return end
T:vint8('backpack') --装备/道具背包号
T:vint32('baseId') --装备/道具基础ID
T:vint16('count') --装备/道具的数量
T:vint64('expiration') --失效时间,0为永久不失效
T:vint8('goodsType') --物品类型. 0:道具;1:装备
T:vint16('gridIndex') --格子索引,从0开始
T:vint64('id') --装备/道具的主键ID
end,
['EquipVO'] = function(T)
if not(T:result()) then return end
T:vstring('attributes') --[装备]装备的基础属性:属性下标1_属性编号1_属性值1|属性下标2_属性编号2_属性值2|...
T:vint64('dressingId') --[装备]穿戴对象ID
T:vint32('fightCapacity') --[装备]战斗力
T:struct('goodVO', NetProtoItem.st.GoodVO) --物品VO
T:vint8('newState') --对于玩家来说是否是新装备(是否刚刚获得)0:否;1:是
T:vint8('starLevel') --[装备]装备的星级
end,
['ItemVO'] = function(T)
if not(T:result()) then return end
T:struct('goodVO', NetProtoItem.st.GoodVO) --物品VO
end,
['BackpackVO'] = function(T)
if not(T:result()) then return end
T:array('equipVOs', NetProtoItem.st.EquipVO) --装备VO数组
T:array('itemVOs', NetProtoItem.st.ItemVO) --道具VO数组
end,
['GridsExpandVO'] = function(T)
if not(T:result()) then return end
T:vint16('expandNum') --能扩展的格子数量
T:vint16('itemCostNum') --消耗解锁晶的数量
T:vint16('itemOwnNum') --拥有解封晶的数量
end,
['RewardVO'] = function(T)
if not(T:result()) then return end
T:vint32('baseId') --[道具和装备有效]物品基础id
T:vint32('count') --奖励物品的数量
T:vint32('goodsType') --奖励的类型(详看GoodsType)
T:vint32('starLevel') --[装备有效]强化等级
end,
['UseItemResultVO'] = function(T)
if not(T:result()) then return end
T:vint32('result') --状态码
T:array('rewardVOs', NetProtoItem.st.RewardVO) --道具使用后的所得
end,
['BulkOperationEquipVO'] = function(T)
if not(T:result()) then return end
T:array('equipVOs', NetProtoItem.st.EquipVO) --装备VO数组
T:vint32('resultCode') --操作结果
end,
}
NetProtoItem.send = {
['ListPackageGoods'] = function(T)
if not(T:result()) then return end
end,
['TakeGoodsFromShopBackpack'] = function(T)
if not(T:result()) then return end
T:vint8('goodType') --物品类型;0:道具,1:装备
T:vint64('id') --物品唯一id
end,
['ShowGridsExpand'] = function(T)
if not(T:result()) then return end
end,
['ExpandGrids'] = function(T)
if not(T:result()) then return end
T:vint16('expandSize') --扩展的大小
end,
['QueryUserItem'] = function(T)
if not(T:result()) then return end
T:array('userItemIds', T.vint64) --道具唯一id数组
end,
['UseItem'] = function(T)
if not(T:result()) then return end
T:vint64('userItemId') --道具唯一id
T:vint32('count') --数量
end,
['SellGoods'] = function(T)
if not(T:result()) then return end
T:array('userItemIds', T.vint64) --道具唯一id数组
T:array('counts', T.vint32) --道具数量数组(对应道具id数组)
end,
['QueryUserEquip'] = function(T)
if not(T:result()) then return end
T:array('userEquipIds', T.vint64) --装备唯一id数组
end,
['DressEquip'] = function(T)
if not(T:result()) then return end
T:vint64('userPetId') --兽兽id,0为角色
T:vint64('userEquipId') --装备唯一id
end,
['UndressEquip'] = function(T)
if not(T:result()) then return end
T:vint64('userEquipId') --装备唯一id
end,
['ListFightUserEquips'] = function(T)
if not(T:result()) then return end
T:vint64('queryPlayerId') --查询的玩家id,查自己可传0
end,
['UndressAllEquip'] = function(T)
if not(T:result()) then return end
T:vint64('roleId') --换装角色id,魔王为0
end,
['RedressAllEquip'] = function(T)
if not(T:result()) then return end
T:vint64('roleId') --换装角色id,魔王为0
end,
}
-- ***自动提示帮助***
NetProtoItem.GoodVO = {
['backpack'] = nil, --装备/道具背包号
['baseId'] = nil, --装备/道具基础ID
['count'] = nil, --装备/道具的数量
['expiration'] = nil, --失效时间,0为永久不失效
['goodsType'] = nil, --物品类型. 0:道具;1:装备
['gridIndex'] = nil, --格子索引,从0开始
['id'] = nil, --装备/道具的主键ID
}
NetProtoItem.EquipVO = {
['attributes'] = nil, --[装备]装备的基础属性:属性下标1_属性编号1_属性值1|属性下标2_属性编号2_属性值2|...
['dressingId'] = nil, --[装备]穿戴对象ID
['fightCapacity'] = nil, --[装备]战斗力
['goodVO'] = nil, --物品VO
['newState'] = nil, --对于玩家来说是否是新装备(是否刚刚获得)0:否;1:是
['starLevel'] = nil, --[装备]装备的星级
}
NetProtoItem.ItemVO = {
['goodVO'] = nil, --物品VO
}
NetProtoItem.BackpackVO = {
['equipVOs'] = nil, --装备VO数组
['itemVOs'] = nil, --道具VO数组
}
NetProtoItem.GridsExpandVO = {
['expandNum'] = nil, --能扩展的格子数量
['itemCostNum'] = nil, --消耗解锁晶的数量
['itemOwnNum'] = nil, --拥有解封晶的数量
}
NetProtoItem.RewardVO = {
['baseId'] = nil, --[道具和装备有效]物品基础id
['count'] = nil, --奖励物品的数量
['goodsType'] = nil, --奖励的类型(详看GoodsType)
['starLevel'] = nil, --[装备有效]强化等级
}
NetProtoItem.UseItemResultVO = {
['result'] = nil, --状态码
['rewardVOs'] = nil, --道具使用后的所得
}
NetProtoItem.BulkOperationEquipVO = {
['equipVOs'] = nil, --装备VO数组
['resultCode'] = nil, --操作结果
}
local T = NetProto.st
-- ***请求处理***
--列出背包物品列表
NetProtoItem.SendListPackageGoods = {
['new'] = NetProto.new,
['_MOD_'] = 4,
['_MED_'] = 1,
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoItem.send.ListPackageGoods, NetProtoItem.st.BackpackVO, fnRespond)
end,
}
--从商城背包提取物品 --返回:状态码
NetProtoItem.SendTakeGoodsFromShopBackpack = {
['new'] = NetProto.new,
['_MOD_'] = 4,
['_MED_'] = 3,
['goodType'] = nil, --物品类型;0:道具,1:装备
['id'] = nil, --物品唯一id
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoItem.send.TakeGoodsFromShopBackpack, T.vint32, fnRespond)
end,
}
--查看格子扩展信息 --返回:扩展格子信息VO
NetProtoItem.SendShowGridsExpand = {
['new'] = NetProto.new,
['_MOD_'] = 4,
['_MED_'] = 4,
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoItem.send.ShowGridsExpand, NetProtoItem.st.GridsExpandVO, fnRespond)
end,
}
--扩展格子 --返回:状态码
NetProtoItem.SendExpandGrids = {
['new'] = NetProto.new,
['_MOD_'] = 4,
['_MED_'] = 5,
['expandSize'] = nil, --扩展的大小
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoItem.send.ExpandGrids, T.vint32, fnRespond)
end,
}
--查询用户道具列表
NetProtoItem.SendQueryUserItem = {
['new'] = NetProto.new,
['_MOD_'] = 4,
['_MED_'] = 21,
['userItemIds'] = nil, --道具唯一id数组
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoItem.send.QueryUserItem, NetProto.st.array(NetProtoItem.st.ItemVO), fnRespond)
end,
}
--使用用户道具 --返回:使用道具返回结果
NetProtoItem.SendUseItem = {
['new'] = NetProto.new,
['_MOD_'] = 4,
['_MED_'] = 22,
['userItemId'] = nil, --道具唯一id
['count'] = nil, --数量
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoItem.send.UseItem, NetProtoItem.st.UseItemResultVO, fnRespond)
end,
}
--出售物品 --返回:状态码
NetProtoItem.SendSellGoods = {
['new'] = NetProto.new,
['_MOD_'] = 4,
['_MED_'] = 23,
['userItemIds'] = nil, --道具唯一id数组
['counts'] = nil, --道具数量数组(对应道具id数组)
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoItem.send.SellGoods, T.vint32, fnRespond)
end,
}
--查询用户装备列表
NetProtoItem.SendQueryUserEquip = {
['new'] = NetProto.new,
['_MOD_'] = 4,
['_MED_'] = 61,
['userEquipIds'] = nil, --装备唯一id数组
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoItem.send.QueryUserEquip, NetProto.st.array(NetProtoItem.st.EquipVO), fnRespond)
end,
}
--上装 --返回:状态码
NetProtoItem.SendDressEquip = {
['new'] = NetProto.new,
['_MOD_'] = 4,
['_MED_'] = 62,
['userPetId'] = nil, --兽兽id,0为角色
['userEquipId'] = nil, --装备唯一id
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoItem.send.DressEquip, T.vint32, fnRespond)
end,
}
--下装 --返回:状态码
NetProtoItem.SendUndressEquip = {
['new'] = NetProto.new,
['_MOD_'] = 4,
['_MED_'] = 63,
['userEquipId'] = nil, --装备唯一id
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoItem.send.UndressEquip, T.vint32, fnRespond)
end,
}
--查询所有穿在身上的装备
NetProtoItem.SendListFightUserEquips = {
['new'] = NetProto.new,
['_MOD_'] = 4,
['_MED_'] = 64,
['queryPlayerId'] = nil, --查询的玩家id,查自己可传0
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoItem.send.ListFightUserEquips, NetProto.st.array(NetProtoItem.st.EquipVO), fnRespond)
end,
}
--一键脱装
NetProtoItem.SendUndressAllEquip = {
['new'] = NetProto.new,
['_MOD_'] = 4,
['_MED_'] = 65,
['roleId'] = nil, --换装角色id,魔王为0
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoItem.send.UndressAllEquip, NetProtoItem.st.BulkOperationEquipVO, fnRespond)
end,
}
--一键换装
NetProtoItem.SendRedressAllEquip = {
['new'] = NetProto.new,
['_MOD_'] = 4,
['_MED_'] = 66,
['roleId'] = nil, --换装角色id,魔王为0
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoItem.send.RedressAllEquip, NetProtoItem.st.BulkOperationEquipVO, fnRespond)
end,
}
-- ***推送处理***
NetProtoItem.MesssagePush = {
[101] = {['msg']='msgPushBackpackVO' ,['st'] = NetProtoItem.st.BackpackVO}, --推送背包VO
}
DeclareInterface(NetProtoItem, 'msgPushInterface')
function NetProtoItem.listenMessagePush(listener)
ListenInterface(NetProtoItem, 'msgPushInterface', listener)
end
function NetProtoItem.removeMessagePush(listener)
RemoveInterface(NetProtoItem, 'msgPushInterface', listener)
end
<file_sep>/Assets/GameScript/Lua/Test/Util/TaskRunnerTest.lua
[TestFixture]
local TaskRunnerTests = class("TaskRunnerTests")
[SetUp]
function TaskRunnerTest.Setup ()
serialTasks1 = new SerialTaskCollection();
parallelTasks1 = new ParallelTaskCollection();
serialTasks2 = new SerialTaskCollection();
parallelTasks2 = new ParallelTaskCollection();
task1 = new Task(15);
task2 = new Task(5);
iterable1 = new Enumerable(15);
iterable2 = new Enumerable(5);
iterations = 0;
_taskRunner = TaskRunner.Instance;
end
function TaskRunnerTest.TestSingleEnumerationBlockExecution()
IEnumerator enumerable = iterable1.GetEnumerator();
while (enumerable.MoveNext() == true);
Assert.That(iterable1.AllRight(), Is.True);
end
function TaskRunnerTest.TestEnumerableAreExecutedInSerial()
bool allDone = false;
serialTasks1.onComplete += () => allDone = true; ;
serialTasks1.Add (iterable1);
serialTasks1.Add (iterable2);
_taskRunner.RunSync (serialTasks1);
Assert.That (allDone == true);
Assert.That (iterable1.AllRight() == true);
Assert.That (iterable2.AllRight() == true);
end
function TaskRunnerTest.TestEnumerableAreExecutedInParallel()
bool allDone = false;
bool test2MustFinishBeforeTest1 = false;
iterable1.onComplete += () =>
Assert.That (test2MustFinishBeforeTest1 == true);
;
iterable2.onComplete += () =>
test2MustFinishBeforeTest1 = true;
;
parallelTasks1.onComplete += () => allDone = true; ;
parallelTasks1.Add (iterable1);
parallelTasks1.Add (iterable2);
_taskRunner.RunSync (parallelTasks1);
Assert.That (allDone == true);
end
function TaskRunnerTest.TestSingleTaskExecution()
task1.Execute();
while (task1.isDone == false);
Assert.That(task1.isDone == true);
end
function TaskRunnerTest.TestSingleTaskExecutionCallsOnComplete()
bool test1Done = false;
task1.OnComplete((b) =>
test1Done = true; );
task1.Execute();
while (task1.isDone == false);
Assert.That(test1Done == true);
end
function TaskRunnerTest.TestSerializedTasksAreExecutedInSerial()
bool allDone = false;
serialTasks1.onComplete += () => allDone = true; ;
SetupAndRunSerialTasks();
Assert.That(allDone == true);
end
function TaskRunnerTest.TestTask1IsExecutedBeforeTask2()
bool test1Done = false;
task1.OnComplete((b) => test1Done = true; );
task2.OnComplete((b) => Assert.That (test1Done == true); );
SetupAndRunSerialTasks();
end
function TaskRunnerTest.TestEnumerable1AndTask2AreExecutedInParallel()
bool allDone = false;
parallelTasks1.onComplete += () => allDone = true; ;
SetupAndRunParallelTasks();
Assert.That(allDone, Is.EqualTo(true));
end
function TaskRunnerTest.TestParallelTasks1IsExecutedBeforeParallelTask2 ()
bool parallelTasks1Done = false;
parallelTasks1.Add (task1);
parallelTasks1.Add (iterable1);
parallelTasks1.onComplete += () => parallelTasks1Done = true; ;
parallelTasks2.Add (task2);
parallelTasks2.Add (iterable2);
parallelTasks2.onComplete += () => Assert.That(parallelTasks1Done == true); ;
serialTasks1.Add (parallelTasks1);
serialTasks1.Add (parallelTasks2);
_taskRunner.RunSync (serialTasks1);
end
function TaskRunnerTest.TestParallelTasksAreExecutedInSerial ()
bool allDone = false;
bool parallelTasks1Done = false;
bool parallelTasks2Done = false;
parallelTasks1.Add (task1);
parallelTasks1.Add (iterable1);
parallelTasks1.onComplete += () => parallelTasks1Done = true; ;
parallelTasks2.Add (task2);
parallelTasks2.Add (iterable2);
parallelTasks2.onComplete += () => parallelTasks2Done = true; ;
serialTasks1.Add (parallelTasks1);
serialTasks1.Add (parallelTasks2);
serialTasks1.onComplete += () => allDone = true; ;
_taskRunner.RunSync (serialTasks1);
Assert.That (parallelTasks1Done == true, "parallelTasks1Done");
Assert.That (parallelTasks2Done == true, "parallelTasks2Done");
Assert.That (allDone == true, "allDone");
end
function TaskRunnerTest.TestSerialTasks1ExecutedInParallel ()
bool serialTasks1Done = false;
serialTasks1.Add (iterable1);
serialTasks1.Add (iterable2);
serialTasks1.onComplete += () => serialTasks1Done = true; ;
serialTasks2.Add (task1);
serialTasks2.Add (task2);
parallelTasks1.Add (serialTasks1);
parallelTasks1.Add (serialTasks2);
_taskRunner.RunSync (parallelTasks1);
Assert.That (serialTasks1Done == true);
end
function TaskRunnerTest.TestSerialTasks2ExecutedInParallel ()
bool serialTasks2Done = false;
serialTasks1.Add (iterable1);
serialTasks1.Add (iterable2);
serialTasks2.Add (task1);
serialTasks2.Add (task2);
serialTasks2.onComplete += () => serialTasks2Done = true; ;
parallelTasks1.Add (serialTasks1);
parallelTasks1.Add (serialTasks2);
_taskRunner.RunSync (parallelTasks1);
Assert.That (serialTasks2Done == true);
end
function TaskRunnerTest.TestSerialTasksAreAllExecutedInParallel ()
bool allDone = false;
serialTasks1.Add (iterable1);
serialTasks1.Add (iterable2);
serialTasks2.Add (task1);
serialTasks2.Add (task2);
parallelTasks1.Add (serialTasks1);
parallelTasks1.Add (serialTasks2);
parallelTasks1.onComplete += () => allDone = true; ;
_taskRunner.RunSync (parallelTasks1);
Assert.That (allDone == true);
end
function TaskRunnerTest.TestSerialTasksExecutedInParallelWithEnumFunction ()
_taskRunner.RunSync (EnumerableFunction());
Assert.That (iterations == 10);
end
local Task = class("Task")
event System.Action<bool> _onComplete;
function Task:OnComplete(System.Action<bool> action)
_onComplete += action;
return self
end
public bool isDone get; private set;
public float progress get; private set;
function Task:ctor(niterations)
isDone = false;
progress = 0.0f;
end
function Task:Execute()
-- //usually this is an async operation (like www)
-- //otherwise it would not make much sense :)
isDone = true;
progress = 1.0f;
if (_onComplete != null)
_onComplete(true);
end
local Enumerable = class("Enumerable")
int totalIterations;
int iterations;
public event System.Action onComplete;
public Enumerable(int niterations)
iterations = 0;
totalIterations = niterations;
public bool AllRight()
return iterations == totalIterations;
public IEnumerator GetEnumerator()
while (iterations < totalIterations)
iterations++;
yield return null;
if (onComplete != null)
onComplete();
TaskRunner _taskRunner;
SerialTaskCollection serialTasks1;
SerialTaskCollection serialTasks2;
ParallelTaskCollection parallelTasks1;
ParallelTaskCollection parallelTasks2;
Task task1;
Task task2;
Enumerable iterable1;
Enumerable iterable2;
int iterations;
function Enumerable:SetupAndRunSerialTasks ()
serialTasks1.Add (task1);
serialTasks1.Add (task2);
_taskRunner.RunSync (serialTasks1);
end
function Enumerable:SetupAndRunParallelTasks ()
parallelTasks1.Add (task1);
parallelTasks1.Add (task2);
_taskRunner.RunSync (parallelTasks1);
IEnumerable EnumerableFunction ()
while (iterations < 10)
iterations++;
yield return null;
end
<file_sep>/Assets/GameScript/Lua/Util/TaskRunner/ITask.lua
IATask = {}
IATask.isDone = false
IATask.process = 0
function IATask:onComplete( action ) end
ITask = {}
implement(ITask , IATask)
function ITask:execute() end
--print(print_lua_table(ITask))<file_sep>/Assets/GameScript/AppMain.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using UnityEngine;
using System.Collections;
/// <summary>
/// 描述:应用主框架入口
/// <para>创建时间:2016-08-03</para>
/// </summary>
public class AppMain : MonoBehaviour {
// Use this for initialization
void Start () {
GameObject.DontDestroyOnLoad(this.gameObject);
AppFacade.Instance.StartUp(); //启动游戏
}
}
<file_sep>/Assets/Libs/LuaDataBind/Foundation/DataProvider/DataProvider.cs
using UnityEngine;
namespace LuaDataBind
{
public abstract class DataProvider : MonoBehaviour
{
/// <summary>
/// Current data value.
/// </summary>
public abstract object Value { get; }
public abstract void OnObjectChanged(object value);
}
}<file_sep>/Assets/Editor/SceneManagerEditor/Strategy/SceneStrategy.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using UnityEngine;
using System.Collections;
using System.IO;
using UnityEditor;
/// <summary>
/// 描述:场景打包策略
/// <para>创建时间:2016-06-27</para>
/// </summary>
public class SceneStrategy : IStrategy
{
private BuildConfig curBuildConfig;
public void BeginProcess(BuildConfig buildConfig)
{
curBuildConfig = buildConfig;
string absolutionInputPath = Path.Combine(Application.dataPath, buildConfig.InputDir);
string[] sceneFilePathArr = System.IO.Directory.GetFiles(absolutionInputPath, "*.unity",SearchOption.AllDirectories);
foreach (string scenePath in sceneFilePathArr)
{
string scenePrefab = scenePath.Replace(".unity", ".prefab");
scenePrefab = scenePrefab.Replace("\\" , "/");
if(!File.Exists(scenePrefab)) continue;
assignBundle(AssetBundleUtil.FormatOutputPath(buildConfig) , scenePrefab);
}
}
/// <summary>
/// 分配Bundle
/// </summary>
/// <param name="outputPath">输出路径</param>
/// <param name="scenePrefabPath">资源的绝对路径</param>
private void assignBundle(string outputPath , string scenePrefabPath)
{
string sceneName = Path.GetFileNameWithoutExtension(scenePrefabPath);
string relativeScenePath = scenePrefabPath.Replace(Application.dataPath, "Assets");
string[] depAssetArr = AssetDatabase.GetDependencies(relativeScenePath);
string rootPath = Path.GetDirectoryName(scenePrefabPath).Replace("\\" , "/");
rootPath = rootPath.Replace(Application.dataPath, "Assets");
string relativePath = outputPath.Replace(BuildGlobal.EXPORT_BUNDLE_ROOT, "");
string bundleName = relativePath + "/" + sceneName + "_" + curBuildConfig.AssetType;
foreach (string defAsset in depAssetArr)
{
string suffix = Path.GetExtension(defAsset);
if(BuildGlobal.FilterAsset.Contains(suffix)) continue;
if (defAsset.StartsWith(rootPath))
{
AssetBundleUtil.AssignBundle(defAsset , bundleName);
}
else
{
//记录引用,避免公共集合打包时,把不必要的资源也打要进来
AssetBuildEditor.Instance.AddDependencie(curBuildConfig.BundleName, defAsset);
// //如果依赖是资源处于公共资源目录
// //检查资源是否被分配,如果没有则依据目录进行分配
// BuildConfig buildConf = BuildConfigManager.Instance.FindAssetBuildConfig(defAsset);
// if (buildConf == null)
// {
// Debug.LogWarning("<<SceneStrategy , assignBundle>> Cant find build config ! asset path is " + defAsset);
// continue;
// }
//
// string dirName = buildConf.InputDir.Substring(buildConf.InputDir.LastIndexOf("/") + 1);
// if (string.IsNullOrEmpty(dirName))
// {
// if(buildConf.InputDir.IndexOf("/") < 0)
// dirName = buildConf.InputDir;
// }
// AssetBundleUtil.AssignBundle(defAsset , dirName);
}
}
//分配自身的Bundle
AssetBundleUtil.AssignBundle(scenePrefabPath , bundleName);
}
public void EndProcess(BuildConfig buildConfig)
{
}
}
<file_sep>/Assets/GameScript/Lua/Test/init.lua
-- @Author: <EMAIL>
-- @Desc: 测试
import (".UIPageTest")
<file_sep>/Assets/GameScript/Lua/Net/Protocol/Api.lua
--local NetREQ_ = NetREQ
NetProtoApi = {}
NetProto.NetModule[201] = NetProtoApi
NetProtoApi.st = {
['ProtocolFileVO'] = function(T)
if not(T:result()) then return end
T:vstring('content') --content
T:vstring('fileName') --fileName
end,
['CppProtoCodesResultObject'] = function(T)
if not(T:result()) then return end
T:vint32('result') --result
T:array('value', NetProtoApi.st.ProtocolFileVO) --value
end,
['LuaProtoCodesResultObject'] = function(T)
if not(T:result()) then return end
T:vint32('result') --result
T:array('value', NetProtoApi.st.ProtocolFileVO) --value
end,
}
NetProtoApi.send = {
['ModuleInfo'] = function(T)
if not(T:result()) then return end
end,
['CmdInfo'] = function(T)
if not(T:result()) then return end
T:vint32('module') --
end,
['VoStruce'] = function(T)
if not(T:result()) then return end
T:vstring('className') --类型全名
end,
['CppProtoCodes'] = function(T)
if not(T:result()) then return end
T:vint32('module') --模块号
end,
['LuaProtoCodes'] = function(T)
if not(T:result()) then return end
T:vint32('module') --模块号
end,
}
-- ***自动提示帮助***
NetProtoApi.ProtocolFileVO = {
['content'] = nil, --content
['fileName'] = nil, --fileName
}
NetProtoApi.CppProtoCodesResultObject = {
['result'] = nil, --result
['value'] = nil, --value
}
NetProtoApi.LuaProtoCodesResultObject = {
['result'] = nil, --result
['value'] = nil, --value
}
local T = NetProto.st
-- ***请求处理***
--模块信息
NetProtoApi.SendModuleInfo = {
['new'] = NetProto.new,
['_MOD_'] = 201,
['_MED_'] = 1,
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoApi.send.ModuleInfo, NetProtoApi.st.ModuleInfoList, fnRespond)
end,
}
--命令信息
NetProtoApi.SendCmdInfo = {
['new'] = NetProto.new,
['_MOD_'] = 201,
['_MED_'] = 2,
['module'] = nil, --
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoApi.send.CmdInfo, NetProtoApi.st.CmdInfoList, fnRespond)
end,
}
--VO的结构
NetProtoApi.SendVoStruce = {
['new'] = NetProto.new,
['_MOD_'] = 201,
['_MED_'] = 3,
['className'] = nil, --类型全名
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoApi.send.VoStruce, NetProtoApi.st.VoStruceMap, fnRespond)
end,
}
--c++协议代码
NetProtoApi.SendCppProtoCodes = {
['new'] = NetProto.new,
['_MOD_'] = 201,
['_MED_'] = 4,
['module'] = nil, --模块号
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoApi.send.CppProtoCodes, NetProtoApi.st.CppProtoCodesResultObject, fnRespond)
end,
}
--lua协议代码
NetProtoApi.SendLuaProtoCodes = {
['new'] = NetProto.new,
['_MOD_'] = 201,
['_MED_'] = 5,
['module'] = nil, --模块号
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoApi.send.LuaProtoCodes, NetProtoApi.st.LuaProtoCodesResultObject, fnRespond)
end,
}
-- ***推送处理***
NetProtoApi.MesssagePush = {
}
DeclareInterface(NetProtoApi, 'msgPushInterface')
function NetProtoApi.listenMessagePush(listener)
ListenInterface(NetProtoApi, 'msgPushInterface', listener)
end
function NetProtoApi.removeMessagePush(listener)
RemoveInterface(NetProtoApi, 'msgPushInterface', listener)
end
<file_sep>/Assets/GEngineScript/Core/ResourceSystem/Watcher/TextureWatcher.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace GEX.Resource
{
public class TextureWatcher : MonoBehaviour {
public List<string> bundleNames = new List<string>();
private bool loaded = false;
public void AddBundleName(string bundleName)
{
bundleNames.Add(bundleName);
// 假如当前Go未激活,这里需要卸载一次,防止某些情况下Go一直是disable状态,在删除时不会执行OnDisable
if (!gameObject.activeSelf)
AssetBundleManager.Instance.UnloadAsset(bundleName);
}
private void OnEnable()
{
if (!loaded)
{
// 激活时增加一次refCount
for (int i = 0; i < bundleNames.Count; ++i)
{
AssetBundleManager.Instance.LoadAsset(bundleNames[i]);
}
}
loaded = true;
}
private void OnDisable()
{
loaded = false;
// 关闭激活时减小refCount
if (AssetBundleManager.Instance != null)
{
for (int i = 0; i < bundleNames.Count; ++i)
{
AssetBundleManager.Instance.UnloadAsset(bundleNames[i]);
}
}
}
}
}
<file_sep>/Assets/GEngineScript/Core/NetworkSystem/NetClient.cs
using UnityEngine;
using System.Collections;
namespace GEX.Network
{
/// <summary>
/// 客户端网络层主入口操作
/// </summary>
public sealed class NetClient
{
private SocketTcp socket;
private PacketMsg packetConvert;
private ConnectObservice connectObserver;
private HeartBeatService heartBeatService;
#region ---Public Attributes-----
public PacketMsg PacketConvert
{
get { return packetConvert; }
}
public ConnectObservice ConnectObserver
{
get { return connectObserver; }
}
/// <summary>
/// 是否进入省电模式
/// </summary>
public bool IsPowerSaveMode { get; set; }
#endregion
public NetClient()
{
socket = new SocketTcp();
socket.OnReceivedMsg += onReceiveMsg;
packetConvert = new PacketMsg();
packetConvert.OnBroadcastPacket += onBrodcastPacket;
connectObserver = new ConnectObservice();
heartBeatService = new HeartBeatService(this);
}
public void Connect(string serverIp, ushort port)
{
socket.Connect(serverIp, port);
}
public void Disconnect()
{
}
private void onReceiveMsg(byte[] msgs)
{
packetConvert.ParsePacketMsg(msgs);
heartBeatService.ResetTimeout();
}
/// <summary>
/// 协议包广播
/// </summary>
/// <param name="packet"></param>
private void onBrodcastPacket(byte[] packet)
{
ByteArray buffer = new ByteArray(packet);
//读取特殊协议号,比如心跳
// short pbId = buffer.ReadShort();
// if (pbId == 10000)
// {
// //假如心跳ID是10000,这里要改成变量
// heartBeatService.OnPingUpdate();
// }
}
public void OnUpdate()
{
//heartBeatService.OnUpdate();
}
/// <summary>
/// 发送请求信息
/// </summary>
/// <param name="msgs"></param>
public void Send(byte[] msgs)
{
socket.Send(msgs);
}
}
}
<file_sep>/Assets/GameScript/Lua/Localization/CN/LTUser.lua
--多语言配置表
--避免key冲突,key命名规则:模块名+key 如:['LTCommon_Name'] = "商业大亨"
local LTUser = {}
LTUser.LTUser_HaHa = "哈哈"
return LTUser<file_sep>/Assets/GameScript/Lua/Common/functions.lua
--输出日志--
function log(str)
Util.Log(str);
end
--错误日志--
function logError(str)
Util.LogError(str);
end
--警告日志--
function logWarn(str)
Util.LogWarning(str);
end
--查找对象--
function find(str)
return GameObject.Find(str);
end
function destroy(obj)
GameObject.Destroy(obj);
end
function newObject(prefab)
return GameObject.Instantiate(prefab);
end
--创建面板--
function createPanel(name)
PanelManager:CreatePanel(name);
end
function child(str)
return transform:FindChild(str);
end
function subGet(childNode, typeName)
return child(childNode):GetComponent(typeName);
end
function findPanel(str)
local obj = find(str);
if obj == nil then
error(str.." is null");
return nil;
end
return obj:GetComponent("BaseLua");
end
--[[--
提供一组常用函数,以及对 Lua 标准库的扩展
]]
--[[--
输出格式化字符串
~~~ lua
printf("The value = %d", 100)
~~~
@param string fmt 输出格式
@param [mixed ...] 更多参数
]]
function printf(fmt, ...)
print(string.format(tostring(fmt), ...))
end
--[[--
检查并尝试转换为数值,如果无法转换则返回 0
@param mixed value 要检查的值
@param [integer base] 进制,默认为十进制
@return number
]]
function checknumber(value, base)
return tonumber(value, base) or 0
end
--[[--
检查并尝试转换为整数,如果无法转换则返回 0
@param mixed value 要检查的值
@return integer
]]
function checkint(value)
return math.round(checknumber(value))
end
--[[--
检查并尝试转换为布尔值,除了 nil 和 false,其他任何值都会返回 true
@param mixed value 要检查的值
@return boolean
]]
function checkbool(value)
return (value ~= nil and value ~= false)
end
--[[--
检查值是否是一个表格,如果不是则返回一个空表格
@param mixed value 要检查的值
@return table
]]
function checktable(value)
if type(value) ~= "table" then value = {} end
return value
end
--[[--
如果表格中指定 key 的值为 nil,或者输入值不是表格,返回 false,否则返回 true
@param table hashtable 要检查的表格
@param mixed key 要检查的键名
@return boolean
]]
function isset(hashtable, key)
local t = type(hashtable)
return (t == "table" or t == "userdata") and hashtable[key] ~= nil
end
--[[--
深度克隆一个值
~~~ lua
-- 下面的代码,t2 是 t1 的引用,修改 t2 的属性时,t1 的内容也会发生变化
local t1 = {a = 1, b = 2}
local t2 = t1
t2.b = 3 -- t1 = {a = 1, b = 3} <-- t1.b 发生变化
-- clone() 返回 t1 的副本,修改 t2 不会影响 t1
local t1 = {a = 1, b = 2}
local t2 = clone(t1)
t2.b = 3 -- t1 = {a = 1, b = 2} <-- t1.b 不受影响
~~~
@param mixed object 要克隆的值
@return mixed
]]
function clone(object)
local lookup_table = {}
local function _copy(object)
if type(object) ~= "table" then
return object
elseif lookup_table[object] then
return lookup_table[object]
end
local new_table = {}
lookup_table[object] = new_table
for key, value in pairs(object) do
new_table[_copy(key)] = _copy(value)
end
return setmetatable(new_table, getmetatable(object))
end
return _copy(object)
end
function internale(lua_table,indent,depth,isLimit)
local str = {}
local prefix = string.rep(" ", indent)
table.insert(str,"\n"..prefix.."{\n")
for k, v in pairs(lua_table) do
if type(k) == "string" then
k = string.format("%q", k)
else
k = string.format("%s", tostring(k))
end
local szSuffix = ""
if type(v) == "string" then
szSuffix = string.format("%q", v)
elseif type(v) == "number" or type(v) == "userdata" then
szSuffix = tostring(v)
elseif type(v) == "table" then
if isLimit then
if (depth > 0) then
szSuffix = internale(v,indent + 1,depth - 1,isLimit)
else
szSuffix = tostring(v)
end
else
szSuffix = print_lua_table(v,indent + 1,depth - 1)
end
else
szSuffix = tostring(v)
end
local szPrefix = string.rep(" ", indent+1)
table.insert(str,szPrefix.."["..k.."]".." = "..szSuffix..",\n")
end
table.insert(str,prefix.."}\n")
return table.concat(str, '')
end
--輸出信息,缩进,遍历深度,不设置上限
function print_lua_table(lua_table, indent,depth,isLimit)
indent = indent or 0
depth = depth or 1
isLimit = isLimit or false
local str = ""
if lua_table == nil then
str = tostring(lua_table)
end
if type(lua_table) == "string" then
str = string.format("%q", lua_table)
end
if type(lua_table) == "userdata" or type(lua_table) == "number" or type(lua_table) == "function" or type(lua_table) == "boolean" then
str = tostring(lua_table)
end
if type(lua_table) == "table" then
str = internale(lua_table,indent,depth,isLimit)
end
return str
end
--[[--
根据系统时间初始化随机数种子,让后续的 math.random() 返回更随机的值
]]
function math.newrandomseed()
local ok, socket = pcall(function()
return require("socket")
end)
if ok then
-- 如果集成了 socket 模块,则使用 socket.gettime() 获取随机数种子
math.randomseed(socket.gettime())
else
math.randomseed(os.time())
end
math.random()
math.random()
math.random()
math.random()
end
--[[--
对数值进行四舍五入,如果不是数值则返回 0
@param number value 输入值
@return number
]]
function math.round(value)
return math.floor(value + 0.5)
end
function math.angle2radian(angle)
return angle*math.pi/180
end
function math.radian2angle(radian)
return radian/math.pi*180
end
--[[--
检查指定的文件或目录是否存在,如果存在返回 true,否则返回 false
可以使用 CCFileUtils:fullPathForFilename() 函数查找特定文件的完整路径,例如:
~~~ lua
local path = CCFileUtils:sharedFileUtils():fullPathForFilename("gamedata.txt")
if io.exists(path) then
....
end
~~~
@param string path 要检查的文件或目录的完全路径
@return boolean
]]
function io.exists(path)
local file = io.open(path, "r")
if file then
io.close(file)
return true
end
return false
end
--[[--
读取文件内容,返回包含文件内容的字符串,如果失败返回 nil
io.readfile() 会一次性读取整个文件的内容,并返回一个字符串,因此该函数不适宜读取太大的文件。
@param string path 文件完全路径
@return string
]]
function io.readfile(path)
local file = io.open(path, "r")
if file then
local content = file:read("*a")
io.close(file)
return content
end
return nil
end
--[[--
以字符串内容写入文件,成功返回 true,失败返回 false
"mode 写入模式" 参数决定 io.writefile() 如何写入内容,可用的值如下:
- "w+" : 覆盖文件已有内容,如果文件不存在则创建新文件
- "a+" : 追加内容到文件尾部,如果文件不存在则创建文件
此外,还可以在 "写入模式" 参数最后追加字符 "b" ,表示以二进制方式写入数据,这样可以避免内容写入不完整。
**Android 特别提示:** 在 Android 平台上,文件只能写入存储卡所在路径,assets 和 data 等目录都是无法写入的。
@param string path 文件完全路径
@param string content 要写入的内容
@param [string mode] 写入模式,默认值为 "w+b"
@return boolean
]]
function io.writefile(path, content, mode)
mode = mode or "w+b"
local file = io.open(path, mode)
if file then
if file:write(content) == nil then return false end
io.close(file)
return true
else
return false
end
end
--[[--
拆分一个路径字符串,返回组成路径的各个部分
~~~ lua
local pathinfo = io.pathinfo("/var/app/test/abc.png")
-- 结果:
-- pathinfo.dirname = "/var/app/test/"
-- pathinfo.filename = "abc.png"
-- pathinfo.basename = "abc"
-- pathinfo.extname = ".png"
~~~
@param string path 要分拆的路径字符串
@return table
]]
function io.pathinfo(path)
local pos = string.len(path)
local extpos = pos + 1
while pos > 0 do
local b = string.byte(path, pos)
if b == 46 then -- 46 = char "."
extpos = pos
elseif b == 47 then -- 47 = char "/"
break
end
pos = pos - 1
end
local dirname = string.sub(path, 1, pos)
local filename = string.sub(path, pos + 1)
extpos = extpos - pos
local basename = string.sub(filename, 1, extpos - 1)
local extname = string.sub(filename, extpos)
return {
dirname = dirname,
filename = filename,
basename = basename,
extname = extname
}
end
--[[--
返回指定文件的大小,如果失败返回 false
@param string path 文件完全路径
@return integer
]]
function io.filesize(path)
local size = false
local file = io.open(path, "r")
if file then
local current = file:seek()
size = file:seek("end")
file:seek("set", current)
io.close(file)
end
return size
end
<file_sep>/README.md
# GEX
Game Engine Extendsion
<file_sep>/Assets/GameScript/Lua/Util/Timer.lua
--[[
Author: LiangZG
Desc : 计时器
]]
local UpdateBeat = UpdateBeat
local Timer = class("Timer")
local m = Timer
function m:ctor( )
self:clear()
end
--设置计时器的开始时间和结束时间
--@param beginTime [number] 启始时间,单位秒
--@param totalTime [number] 计时量,单位秒
--@param timeUnit [eTimeUnit] 计时器单位间隔
function m:setBeginTime( beginTime , totalTime , interval )
self:setTime(beginTime , beginTime + totalTime , interval)
end
--设置计时器的开始时间和结束时间
--@param beginTime [number] 启始时间,单位秒
--@param endTime [number] 结束时间,单位秒
--@param timeUnit [eTimeUnit] 计时器单位间隔
function m:setEndTime( endTime , totalTime , interval )
self:setTime(endTime - totalTime , endTime , interval)
end
--设置计时器的开始时间和结束时间
--@param beginTime [number] 启始时间,单位秒
--@param totalTime [number] 计时量,单位秒
--@param timeUnit [eTimeUnit] 计时器单位间隔
function m:setTime( beginTime , endTime , interval )
self.beginTime = beginTime
self.endTime = endTime
self.totalTime = self.endTime - self.beginTime
self.interval = interval
end
--是否忽略时间的缩放
--@param ignore bool true表示忽略缩放(默认)
function m:ignoreTimeScale( ignore )
self.ignoreScale = ignore
return self
end
--启动计时器
-- delay 延迟时间
function m:start(delay)
if self.runHandler then
UpdateBeat:Remove(self.runHandler)
end
local curTime = TimeService.ins:totalMillisecondNow() / 1000
self.elapseDeltaTime = Mathf.Max(0 , curTime - self.beginTime)
self.lastElapseTime = self.elapseDeltaTime
self.runHandler = handler(self , self._run)
Scheduler.ins:startDelay(function ( )
UpdateBeat:Add(self.runHandler)
end , delay , true)
self:_changeInvoke(self.elapseDeltaTime / self.totalTime)
end
function m:_run()
if self.pause then return end
if self.elapseDeltaTime > self.totalTime then
self:_changeInvoke(1)
self:onDestroy()
return
end
self.elapseDeltaTime = self.elapseDeltaTime + self:_detalTime()
if self.elapseDeltaTime - self.lastElapseTime > self.interval then
self.lastElapseTime = self.elapseDeltaTime
self:_changeInvoke(self.elapseDeltaTime / self.totalTime)
end
end
function m:_detalTime()
if self.ignoreScale then
return Time.unscaledDeltaTime
end
return Time.deltaTime
end
function m:pause( )
self.pause = true
end
function m:resume( )
self.pause = false
end
function m:_changeInvoke( process )
if not self.changeFunc then return end
self.changeFunc(process)
end
function m:clear( )
self.changeFunc = nil
self.elapseDeltaTime = 0
self.lastElapseTime = 0
self.pause = false
self.ignoreTimeScale = false
end
function m:onDestroy()
if self.runHandler then
UpdateBeat:Remove(self.runHandler)
self.runHandler = nil
end
self:clear()
end
return Timer<file_sep>/Assets/GEngineScript/Core/SceneManager/ASceneLoader.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace GOE.Scene
{
/// <summary>
/// 描述:场景加载器基类,提供统一的加载入口
/// <para>创建时间:2016-06-15</para>
/// </summary>
public abstract class ASceneLoader
{
/// <summary>
/// 是否进行异步加载
/// </summary>
public bool IsLoadAsync = true;
private List<Action> finishCallback;
/// <summary>
/// 加载进度, (每次的变化值,总的变化值)
/// </summary>
protected Action<float, float> progress;
/// <summary>
/// 加载场景资源
/// </summary>
/// <param name="sceneName">场景名称</param>
/// <param name="delay">延迟时间</param>
/// <returns></returns>
public IEnumerator OnLoad(string sceneName)
{
IEnumerator loadLevel = onLoadLevel(sceneName);
while (loadLevel.MoveNext())
yield return 0;
OnFinish();
}
/// <summary>
/// 具体的加载逻辑
/// </summary>
/// <returns></returns>
protected abstract IEnumerator onLoadLevel(string sceneName);
/// <summary>
/// 添加完成后的回调
/// </summary>
/// <param name="callback"></param>
public void AddFinish(Action callback)
{
if (callback == null) return;
if (finishCallback == null)
finishCallback = new List<Action>();
//防止重复添加
if (finishCallback.Contains(callback)) return;
finishCallback.Add(callback);
}
/// <summary>
/// 删除完成时的回调
/// </summary>
/// <param name="callback"></param>
public void RemoveFinish(Action callback)
{
if (finishCallback == null) return;
finishCallback.Remove(callback);
}
/// <summary>
/// 清理全部完成时的回调
/// </summary>
public void ClearFinish()
{
if(finishCallback != null)
finishCallback.Clear();
finishCallback = null;
}
public void OnFinish()
{
if (finishCallback != null)
{
foreach (Action action in finishCallback)
{
action.Invoke();
}
finishCallback.Clear();
}
}
/// <summary>
/// 加载场景
/// </summary>
/// <param name="sceneName"></param>
/// <param name="mode"></param>
/// <returns></returns>
protected IEnumerator load(string sceneName , UnityEngine.SceneManagement.LoadSceneMode mode)
{
if (IsLoadAsync)
{
WWW _www = new WWW("");
//进度数据传递
int totalProgress = 0 , curTotalProgress;
int offset = 0;
while (!_www.isDone)
{
curTotalProgress = (int)(_www.progress * 100);
offset = curTotalProgress - totalProgress;
totalProgress = curTotalProgress;
InvokeProgress(offset, totalProgress);
yield return null;
}
curTotalProgress = totalProgress == 0 ? (int)(_www.progress * 100) : totalProgress;
offset = 100 - curTotalProgress;
totalProgress = 100;
InvokeProgress(offset, totalProgress);
while (curTotalProgress < totalProgress)
{
curTotalProgress++;
yield return null;
}
//清空进度委托
this.SetProgress(null);
}
else
{
UnityEngine.SceneManagement.SceneManager.LoadScene(sceneName , mode);
yield return 0;
}
}
/// <summary>
/// 设置进度监听
/// </summary>
/// <param name="callback"></param>
public void SetProgress(Action<float, float> callback)
{
progress = callback;
}
/// <summary>
/// 执行进度监听
/// </summary>
/// <param name="progressOffset"></param>
/// <param name="totalPress"></param>
public void InvokeProgress(float progressOffset, float totalPress)
{
if (progress == null) return;
progress.Invoke(progressOffset , totalPress);
}
}
}
<file_sep>/Assets/GameScript/Lua/Util/init.lua
--[[
常用模块初始化
]]
local UTIL_MODEL_NAME = ...
eUtil = import(".eUtil")
utils = import(".utils")
goHelper = import(".goHelper")
Scheduler = import (".Scheduler")
TimeService = import(".TimeService")
Timer = import(".Timer")
import(".EventManager")
import(".TaskRunner.init")
<file_sep>/Assets/Libs/LuaDataBind/Foundation/Setter/SingleSetter.cs
using System;
namespace LuaDataBind
{
public abstract class SingleSetter<T> : Setter
{
public override void OnObjectChanged(object value)
{
object val = getValue(value);
T newVal = val is T ? (T)val : default(T);
this.OnValueChanged(newVal);
}
protected abstract void OnValueChanged(T newValue);
private object getValue(object value)
{
object val = Convert.ChangeType(value, typeof(T));
switch (Type)
{
case DataBindingType.Provider:
if (Provider != null)
{
Provider.OnObjectChanged(val);
return Provider.Value;
}
break;
case DataBindingType.Constant:
break;
}
return value;
}
}
}<file_sep>/Assets/GameScript/Lua/Common/Fsm.lua
--[[
Author: LiangZG
Email : <EMAIL>
]]
--[[
有限状态机
]]
local Fsm = class("Fsm")
local UpdateBeat = UpdateBeat
function Fsm:ctor()
self.state = nil
self.globalState = nil
UpdateBeat:Add(self.OnUpdate , self)
end
--[[
状态切换
FsmState nextState 下一个状态
]]
function Fsm:OnEnter(nextState)
if self.state ~= nil then
self.state:OnExit()
end
nextState:OnEnter()
self.state = nextState
end
function Fsm:OnUpdate()
if self.globalState ~= nil then
self.globalState:OnUpdate()
end
if self.state ~= nil then
self.state:OnUpdate()
end
end
function Fsm:OnExit()
if self.state ~= nil then
self.state:OnExit()
end
end
return Fsm
<file_sep>/Assets/GameScript/Lua/UI/TopToolbarPanel.lua
-- @Author: <EMAIL>
-- @Last Modified time: 2017-01-01 00:00:00
-- @Desc: 顶部工具栏
TopToolbarPanel = {}
local this = TopToolbarPanel
local curUiId = 0
--- 由LuaBehaviour自动调用
function TopToolbarPanel.Awake(gameObject)
this.widgets = {
{field="root", path ="", src=LuaCanvas},
{field="BtnBack",path="BtnBack",src=LuaButton, onClick = this._onBackClick },
{field="HelpInfo",path="HelpInfo",src=LuaButton, onClick = this._onClickHelpInfo },
{field="barText",path="barText",src=LuaText},
}
LuaUIHelper.bind(this.gameObject , TopToolbarPanel )
end
function TopToolbarPanel.Show( func )
UIManager:Show("Prefab/GUI/TopToolbarPanel", nil)
this.closeFunc = func
end
--- 由LuaBehaviour自动调用
function TopToolbarPanel.OnInit(basePage)
this.basePage = basePage
this.basePage:SetFixPage(2200 , EShowMode.None , ECollider.None)
--每次显示自动修改UI中所有Panel的depth
--LuaUIHelper.addUIDepth(this.gameObject , TopToolbarPanel)
this._registeEvents(this.event)
end
-- 注册界面事件监听
function TopToolbarPanel._registeEvents(event)
end
function TopToolbarPanel._onBackClick()
print("Back Button Click")
UIManager:AutoBackPage()
end
function TopToolbarPanel._onClickHelpInfo()
NoticePanel.Show("Notice" , nil)
end
--- 关闭界面
function TopToolbarPanel._onClickClose( )
--panelMgr:ClosePanel("TopToolbarPanel")
UIManager.Hide(this.basePage.assetPath)
if this.closeFunc ~= nil then
this.closeFunc()
this.closeFunc = nil
end
end
--- 由LuaBehaviour自动调用
function TopToolbarPanel.OnClose()
--LuaUIHelper.removeUIDepth(this.gameObject) --还原全局深度
end
--- 由LuaBehaviour自动调用--
function TopToolbarPanel.OnDestroy()
this.gameObject = nil
this.transform = nil
this.widgets = nil
end<file_sep>/Assets/GameScript/UISystem/PageContext.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using UnityEngine;
using System.Collections;
/// <summary>
/// 描述:页面运行环境的配置
/// </summary>
public class PageContext
{
/// <summary>
/// 匹配的显示状态
/// </summary>
public EUIState uiState = EUIState.Normal;
/// <summary>
/// 界面类型
/// </summary>
public EPageType pageType = EPageType.Normal;
/// <summary>
/// 显示交互模式
/// </summary>
public EShowMode showMode = EShowMode.HideOther;
/// <summary>
/// 背景碰撞方式
/// </summary>
public ECollider collider = ECollider.Normal;
/// <summary>
/// 界面显示序列
/// </summary>
public int order;
/// <summary>
/// 界面名称
/// </summary>
public string pageName;
/// <summary>
/// 资源路径
/// </summary>
public string assetPath;
/// <summary>
/// Lua逻辑
/// </summary>
public LuaPageBehaviour luaPage;
}
<file_sep>/Assets/GameScript/Lua/Test/UIPageTest.lua
--[[
Author: LiangZG
Email : <EMAIL>
]]
UIPageTest = {}
local this = UIPageTest
--Update挂点, UpdateBeat:Add(luaFunc)
local UpdateBeat = UpdateBeat
function UIPageTest.Awake()
AssetLoader.isBundle = false
print("UIPageTest.Awake")
end
function UIPageTest.Start()
LuaAssetLoader.OnInitPreload(function()
print("Load Finish ---->")
end)
end
function UIPageTest.OnGUI()
if this.Tag then
return
end
if GUILayout.Button("Show" , GUILayout.Height(30)) then
TopToolbarPanel.Show()
MainPanel.Show()
this.Tag = true
end
if GUILayout.Button("Show TopToolbar" , GUILayout.Height(30)) then
TopToolbarPanel.Show()
this.Tag = true
end
if GUILayout.Button("Show MainUI" , GUILayout.Height(30)) then
MainPanel.Show()
this.Tag = true
end
end
function UIPageTest.OnDestroy()
end
<file_sep>/Assets/GameScript/Lua/Net/Protocol/Mail.lua
--local NetREQ_ = NetREQ
NetProtoMail = {}
NetProto.NetModule[18] = NetProtoMail
NetProtoMail.st = {
['RewardVO'] = function(T)
if not(T:result()) then return end
T:vint32('baseId') --[道具和装备有效]物品基础id
T:vint32('count') --奖励物品的数量
T:vint32('goodsType') --奖励的类型(详看GoodsType)
T:vint32('starLevel') --[装备有效]强化等级
end,
['MailVO'] = function(T)
if not(T:result()) then return end
T:vstring('content') --内容(是否提供,依据来源)
T:vint64('expirationTime') --有效期满时间
T:vint64('id') --邮件主键id
T:array('rewardVOs', NetProtoMail.st.RewardVO) --附件内容
T:vint64('sendTime') --发送时间
T:vint64('senderId') --发送者id,来源为系统邮件时必为0
T:vstring('senderName') --发送者名字,来源为系统邮件时必为空
T:vint8('state') --状态组合(二进制按位与,定义于MailViewState);0x01:已阅读,0x02:已领奖
T:vstring('theme') --主题(是否提供,依据来源)
T:vint32('themeId') --主题ID(依据来源使用)
end,
}
NetProtoMail.send = {
['MailList'] = function(T)
if not(T:result()) then return end
T:vint8('mailType') --邮件类型:0系统邮件,1个人邮件
end,
['QueryMails'] = function(T)
if not(T:result()) then return end
T:vint64('divideMailId') --分界ID(最新已加载邮件的ID)
T:vint8('mailType') --邮件类型:0系统邮件,1个人邮件
end,
['SendMail'] = function(T)
if not(T:result()) then return end
T:vint64('friendId') --好友Id
T:vint8('themeId') --主题
T:vstring('content') --内容
end,
['MarkMailRead'] = function(T)
if not(T:result()) then return end
T:vint64('mailId') --邮件主键id
T:vint8('mailType') --邮件类型:0系统邮件,1个人邮件
end,
['ReceiveMailRewards'] = function(T)
if not(T:result()) then return end
T:vint64('mailId') --邮件主键id
T:vint8('mailType') --邮件类型:0系统邮件,1个人邮件
end,
['ReceiveAllMailRewards'] = function(T)
if not(T:result()) then return end
T:vint8('mailType') --邮件类型:0系统邮件,1个人邮件
end,
}
-- ***自动提示帮助***
NetProtoMail.RewardVO = {
['baseId'] = nil, --[道具和装备有效]物品基础id
['count'] = nil, --奖励物品的数量
['goodsType'] = nil, --奖励的类型(详看GoodsType)
['starLevel'] = nil, --[装备有效]强化等级
}
NetProtoMail.MailVO = {
['content'] = nil, --内容(是否提供,依据来源)
['expirationTime'] = nil, --有效期满时间
['id'] = nil, --邮件主键id
['rewardVOs'] = nil, --附件内容
['sendTime'] = nil, --发送时间
['senderId'] = nil, --发送者id,来源为系统邮件时必为0
['senderName'] = nil, --发送者名字,来源为系统邮件时必为空
['state'] = nil, --状态组合(二进制按位与,定义于MailViewState);0x01:已阅读,0x02:已领奖
['theme'] = nil, --主题(是否提供,依据来源)
['themeId'] = nil, --主题ID(依据来源使用)
}
local T = NetProto.st
-- ***请求处理***
--邮件列表
NetProtoMail.SendMailList = {
['new'] = NetProto.new,
['_MOD_'] = 18,
['_MED_'] = 1,
['mailType'] = nil, --邮件类型:0系统邮件,1个人邮件
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoMail.send.MailList, NetProto.st.array(NetProtoMail.st.MailVO), fnRespond)
end,
}
--查询刚收到的最新邮件
NetProtoMail.SendQueryMails = {
['new'] = NetProto.new,
['_MOD_'] = 18,
['_MED_'] = 2,
['divideMailId'] = nil, --分界ID(最新已加载邮件的ID)
['mailType'] = nil, --邮件类型:0系统邮件,1个人邮件
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoMail.send.QueryMails, NetProto.st.array(NetProtoMail.st.MailVO), fnRespond)
end,
}
--发送邮件 --返回:状态码
NetProtoMail.SendSendMail = {
['new'] = NetProto.new,
['_MOD_'] = 18,
['_MED_'] = 4,
['friendId'] = nil, --好友Id
['themeId'] = nil, --主题
['content'] = nil, --内容
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoMail.send.SendMail, T.vint32, fnRespond)
end,
}
--标记邮件已读取 --返回:状态码
NetProtoMail.SendMarkMailRead = {
['new'] = NetProto.new,
['_MOD_'] = 18,
['_MED_'] = 5,
['mailId'] = nil, --邮件主键id
['mailType'] = nil, --邮件类型:0系统邮件,1个人邮件
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoMail.send.MarkMailRead, T.vint32, fnRespond)
end,
}
--领取邮件附件 --返回:状态码
NetProtoMail.SendReceiveMailRewards = {
['new'] = NetProto.new,
['_MOD_'] = 18,
['_MED_'] = 6,
['mailId'] = nil, --邮件主键id
['mailType'] = nil, --邮件类型:0系统邮件,1个人邮件
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoMail.send.ReceiveMailRewards, T.vint32, fnRespond)
end,
}
--领取全部邮件附件 --返回:状态码
NetProtoMail.SendReceiveAllMailRewards = {
['new'] = NetProto.new,
['_MOD_'] = 18,
['_MED_'] = 7,
['mailType'] = nil, --邮件类型:0系统邮件,1个人邮件
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoMail.send.ReceiveAllMailRewards, T.vint32, fnRespond)
end,
}
-- ***推送处理***
NetProtoMail.MesssagePush = {
}
DeclareInterface(NetProtoMail, 'msgPushInterface')
function NetProtoMail.listenMessagePush(listener)
ListenInterface(NetProtoMail, 'msgPushInterface', listener)
end
function NetProtoMail.removeMessagePush(listener)
RemoveInterface(NetProtoMail, 'msgPushInterface', listener)
end
<file_sep>/Assets/GameScript/Lua/GameState/MainState.lua
--[[
Author: LiangZG
Email : <EMAIL>
]]
local BaseState = require "Common.BaseState"
--[[
主场景状态,游戏登录后的场景状态
]]
local MainState = class("MainState" , BaseState)
function MainState:OnEnter()
print("MainState ---> OnEnter")
--local obj = AssetLoader.LoadGameObject()
end
function MainState:OnExit()
print("MainState <---- OnExit")
end
return MainState<file_sep>/Assets/GEngineScript/Utility/AppInter.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using System;
using System.Collections;
using UnityEngine;
/// <summary>
/// 描述:应用中转脚本,一直存在于场景
/// 用处说明:
/// 1.用于启动一个不会销毁的协同
/// 2.用于跨平台业务中转,比如SDK接入后的数据交互
/// <para>创建时间:</para>
/// </summary>
public class AppInter
{
private static AppInterMono mInstance;
public static AppInterMono Instance
{
get
{
if(mInstance != null) return mInstance;
GameObject gObj = new GameObject("_App");
mInstance = gObj.AddComponent<AppInterMono>();
return mInstance;
}
}
/// <summary>
/// 启动协程,该协程不会随场景的切换而停止
/// </summary>
/// <param name="method"></param>
public static Coroutine StartCoroutine(IEnumerator method)
{
AppInterMono app = AppInter.Instance;
return app.StartCoroutine(method);
}
public static void WWWBundle(string url, Action<AssetBundle> finish)
{
StartCoroutine(wwwUtil<AssetBundle>(url , (obj)=> finish.Invoke((AssetBundle)obj)));
}
private static IEnumerator wwwUtil<T>(string url, Action<object> finish)
{
WWW _www = new WWW(url);
yield return _www;
if (_www.error != null)
{
Debug.LogError(_www.error + ",url:" + url);
yield break;
}
Type type = typeof (T);
if (type == typeof (AssetBundle))
{
AssetBundle bundle = _www.assetBundle;
finish.Invoke(bundle);
}else if (type == typeof (TextAsset))
{
finish.Invoke(_www.text);
}
}
public class AppInterMono : MonoBehaviour
{
private void Awake()
{
GameObject.DontDestroyOnLoad(this.gameObject);
this.gameObject.name = "_App";
this.gameObject.hideFlags = HideFlags.HideInHierarchy;
}
}
}<file_sep>/Assets/GameScript/Lua/Common/init.lua
--[[
公共模块初始化
]]
local COMMON_MODE = ...
import(".functions")
BaseState = import(".BaseState")
Fsm = import(".Fsm")
<file_sep>/Assets/GameScript/Lua/UI/init.lua
-- @Author: <EMAIL>
-- @Desc: UI模板
import (".BattlePanel")
import (".MainPanel")
import (".TopToolbarPanel")
import (".Common.init")
import (".Skill.init")<file_sep>/Assets/GameScript/Lua/Net/Dequeue.lua
local Dequeue = {}
Dequeue = class('Dequeue')
function Dequeue:ctor()
self.first = 0
self.last = -1
self.data = {}
end
function Dequeue:clone()
local o = Dequeue:new()
o.first = self.first
o.last = self.last
for i=o.first,o.last do
o.data[i] = self.data[i]
end
return o
end
function Dequeue:endIndex()
return self.last + 1
end
function Dequeue:removeAll()
self.first = 0
self.last = -1
self.data = {}
end
function Dequeue:clear()
self:removeAll()
end
function Dequeue:removeIndex(index)
local currentIndex = index
assert(self:inRange(currentIndex),'index is not in range')
self.data[currentIndex] = nil
while currentIndex < self.last do
self.data[currentIndex] = self.data[currentIndex + 1]
currentIndex = currentIndex + 1
end
self.data[currentIndex] = nil
self.last = self.last - 1
end
function Dequeue:insert(o)
if self:containObject(o) then
return
end
self:pushBack(o)
end
function Dequeue:remove(o)
local enum = self:enum()
while (not enum:enumEnd()) do
local o2 = enum:get()
if o2 == nil then break end
if o == o2 then
self:removeIndex(enum.enumIndex)
else
enum:toNext()
end
end
end
function Dequeue:removeList(list)
for i, v in ipairs(list) do
self:remove(v)
end
end
function Dequeue:removeFromTo(from,to)
assert(self:inRange(from),"invalid 'from' index")
local t = from
local removeToEnd = not self:inRange(to)
if removeToEnd then
while from <= self.last do
self.data[from] = nil
from = from + 1
end
self.last = t - 1
else
local i = 0
while from <= to do
if (to + i) <= self.last then
self.data[from] = self.data[to + i]
i = i + 1
else
self.data[from] = nil
end
from = from + 1
end
self.last = t - 1 + i
end
end
function Dequeue:front()
return self.data[self.first]
end
function Dequeue:back()
return self.data[self.last]
end
function Dequeue:pushFront(value)
assert(value ~= nil,'value can not be nil')
local first= self.first-1
self.data[first] = value
self.first = first
end
function Dequeue:pushBack(value)
assert(value ~= nil,'value can not be nil')
local last = self.last + 1
self.data[last]= value
self.last=last
end
function Dequeue:popFront()
local last = self.last
local first = self.first
if(last<first) then
error("list is empty")
end
local value= self.data[first]
self.data[first] = nil
self.first = first + 1
return value
end
function Dequeue:popBack()
local last = self.last
local first = self.first
if last<first then
error("the list is empty")
end
local value = self.data[last]
self.data[last]= nil
self.last= last-1
return value
end
function Dequeue:size()
if self.last < self.first then
return 0
end
return (self.last - self.first) + 1
end
function Dequeue:empty()
local last = self.last
local first = self.first
if first > last then
return true
end
return false
end
function Dequeue:travel(func)
local last = self.last
local first = self.first
if first < last then
if not func(self.data[first]) then
return
end
first = first + 1
else
func(nil)
end
end
local Enumtor = {}
Enumtor.__index = Enumtor
function Enumtor:enumNext()
local last = self.dq.last
if self.enumIndex <= last then
local rst = self.dq.data[self.enumIndex]
self.enumIndex = self.enumIndex + 1
return rst
else
return nil
end
end
function Enumtor:get()
assert(not self:enumEnd(),"invalid enumrator.")
return self.dq:at(self.enumIndex)
end
function Enumtor:toNext()
self.enumIndex = self.enumIndex + 1
end
function Enumtor:EQ(o2)
assert((self.dq == o2.dq),"invalid EQ.")
if self.enumIndex ~= o2.enumIndex then
return false
end
return true
end
function Enumtor:enumEnd()
return (not self.dq:inRange(self.enumIndex))
end
function Enumtor:endIndex()
return self.dq:endIndex()
end
function Enumtor:clone()
local o = {}
setmetatable(o,Enumtor)
o.enumIndex = self.enumIndex
o.dq = self.dq
return o
end
function Dequeue:enum()
local o = {}
setmetatable(o,Enumtor)
o.enumIndex = self.first
o.dq = self
return o
end
function Dequeue:inRange(index)
if self:empty() then
return false
end
index = index + self.first
if index < self.first or index > self.last then
return false
end
return true
end
function Dequeue:findObject(o)
self:enum()
while true do
local rst = self:enumNext()
if rst == nil then break end
if o == o2 then return self.enumIndex - 1 end
end
return self.last + 1
end
function Dequeue:containObject(o)
self:enum()
while true do
local o2 = self:enumNext()
if o2 == nil then break end
if o == o2 then return true end
end
return false
end
function Dequeue:at(index)
if self:inRange(index) == false then
error("access dequeue out of rang.")
end
index = index + self.first
local o = self.data[index]
assert(o ~= nil)
return o
end
return Dequeue<file_sep>/Assets/GameScript/Lua/GameScript.lua
--[[
此脚本用来导入游戏具体功能模块生成的Wrap映射对象
]]
ByteArray = NetCore.ByteArray
ByteArrayQueue = NetCore.ByteArrayQueue
--当前使用的协议类型--
TestProtoType = ProtocalType.BINARY;
Util = LuaFramework.Util;
--AppConst = LuaFramework.AppConst
LuaHelper = LuaFramework.LuaHelper
--ByteBuffer = LuaFramework.ByteBuffer
resMgr = LuaHelper.GetResManager()
panelMgr = LuaHelper.GetPanelManager()
soundMgr = LuaHelper.GetSoundManager()
--networkMgr = LuaHelper.GetNetManager()
UIManager = UIManager.Instance<file_sep>/Assets/GameScript/Lua/Engines/table.lua
--[[--
计算表格包含的字段数量
Lua table 的 "#" 操作只对依次排序的数值下标数组有效,table.nums() 则计算 table 中所有不为 nil 的值的个数。
@param table t 要检查的表格
@return integer
]]
function table.nums(t)
local count = 0
for k, v in pairs(t) do
count = count + 1
end
return count
end
--[[--
返回指定表格中的所有键
~~~ lua
local hashtable = {a = 1, b = 2, c = 3}
local keys = table.keys(hashtable)
-- keys = {"a", "b", "c"}
~~~
@param table hashtable 要检查的表格
@return table
]]
function table.keys(hashtable)
local keys = {}
for k, v in pairs(hashtable) do
keys[#keys + 1] = k
end
return keys
end
--[[--
返回指定表格中的所有值
~~~ lua
local hashtable = {a = 1, b = 2, c = 3}
local values = table.values(hashtable)
-- values = {1, 2, 3}
~~~
@param table hashtable 要检查的表格
@return table
]]
function table.values(hashtable)
local values = {}
for k, v in pairs(hashtable) do
values[#values + 1] = v
end
return values
end
--[[--
将来源表格中所有键及其值复制到目标表格对象中,如果存在同名键,则覆盖其值
~~~ lua
local dest = {a = 1, b = 2}
local src = {c = 3, d = 4}
table.merge(dest, src)
-- dest = {a = 1, b = 2, c = 3, d = 4}
~~~
@param table dest 目标表格
@param table src 来源表格
]]
function table.merge(dest, src)
for k, v in pairs(src) do
dest[k] = v
end
end
--[[--
在目标表格的指定位置插入来源表格,如果没有指定位置则连接两个表格
~~~ lua
local dest = {1, 2, 3}
local src = {4, 5, 6}
table.insertto(dest, src)
-- dest = {1, 2, 3, 4, 5, 6}
dest = {1, 2, 3}
table.insertto(dest, src, 5)
-- dest = {1, 2, 3, nil, 4, 5, 6}
~~~
@param table dest 目标表格
@param table src 来源表格
@param [integer begin] 插入位置
]]
function table.insertto(dest, src, begin)
begin = checkint(begin)
if begin <= 0 then
begin = #dest + 1
end
local len = #src
for i = 0, len - 1 do
dest[i + begin] = src[i + 1]
end
end
--[[
从表格中查找指定值,返回其索引,如果没找到返回 false
~~~ lua
local array = {"a", "b", "c"}
print(table.indexof(array, "b")) -- 输出 2
~~~
@param table array 表格
@param mixed value 要查找的值
@param [integer begin] 起始索引值
@return integer
]]
function table.indexof(array, value, begin)
for i = begin or 1, #array do
if array[i] == value then return i end
end
return false
end
--[[--
从表格中查找指定值,返回其 key,如果没找到返回 nil
~~~ lua
local hashtable = {name = "dualface", comp = "chukong"}
print(table.keyof(hashtable, "chukong")) -- 输出 comp
~~~
@param table hashtable 表格
@param mixed value 要查找的值
@return string 该值对应的 key
]]
function table.keyof(hashtable, value)
for k, v in pairs(hashtable) do
if v == value then return k end
end
return nil
end
--[[--
从表格中删除指定值,返回删除的值的个数
~~~ lua
local array = {"a", "b", "c", "c"}
print(table.removebyvalue(array, "c", true)) -- 输出 2
~~~
@param table array 表格
@param mixed value 要删除的值
@param [boolean removeall] 是否删除所有相同的值
@return integer
]]
function table.removebyvalue(array, value, removeall)
local c, i, max = 0, 1, #array
while i <= max do
if array[i] == value then
table.remove(array, i)
c = c + 1
i = i - 1
max = max - 1
if not removeall then break end
end
i = i + 1
end
return c
end
--[[--
对表格中每一个值执行一次指定的函数,并用函数返回值更新表格内容
~~~ lua
local t = {name = "dualface", comp = "chukong"}
table.map(t, function(v, k)
-- 在每一个值前后添加括号
return "[" .. v .. "]"
end)
-- 输出修改后的表格内容
for k, v in pairs(t) do
print(k, v)
end
-- 输出
-- name [dualface]
-- comp [chukong]
~~~
fn 参数指定的函数具有两个参数,并且返回一个值。原型如下:
~~~ lua
function map_function(value, key)
return value
end
~~~
@param table t 表格
@param function fn 函数
]]
function table.map(t, fn)
for k, v in pairs(t) do
t[k] = fn(v, k)
end
end
--[[--
将参数里面的keylist合成一个deep map
~~~比如传入 'a','b','c','d'则会return 一个map {a={b={c='d'}}}
]]
function table.keymap(map, ...)
map = map or {}
if arg['n'] <= 1 then
return map
end
local tmp = map
for k,v in ipairs(arg) do
if k >= arg['n'] - 1 then
tmp[v] = arg[k+1]
break
end
tmp[v] = tmp[v] or {}
tmp = tmp[v]
end
return map
end
--[[--
对表格中每一个值执行一次指定的函数,但不改变表格内容
~~~ lua
local t = {name = "dualface", comp = "chukong"}
table.walk(t, function(v, k)
-- 输出每一个值
print(v)
end)
~~~
fn 参数指定的函数具有两个参数,没有返回值。原型如下:
~~~ lua
function map_function(value, key)
end
~~~
@param table t 表格
@param function fn 函数
]]
function table.walk(t, fn)
for k,v in pairs(t) do
fn(v, k)
end
end
--[[--
对表格中每一个值执行一次指定的函数,如果该函数返回 false,则对应的值会从表格中删除
~~~ lua
local t = {name = "dualface", comp = "chukong"}
table.filter(t, function(v, k)
return v ~= "dualface" -- 当值等于 dualface 时过滤掉该值
end)
-- 输出修改后的表格内容
for k, v in pairs(t) do
print(k, v)
end
-- 输出
-- comp chukong
~~~
fn 参数指定的函数具有两个参数,并且返回一个 boolean 值。原型如下:
~~~ lua
function map_function(value, key)
return true or false
end
~~~
@param table t 表格
@param function fn 函数
]]
function table.filter(t, fn)
for k, v in pairs(t) do
if not fn(v, k) then t[k] = nil end
end
end
--[[--
遍历表格,确保其中的值唯一
~~~ lua
local t = {"a", "a", "b", "c"} -- 重复的 a 会被过滤掉
local n = table.unique(t)
for k, v in pairs(n) do
print(v)
end
-- 输出
-- a
-- b
-- c
~~~
@param table t 表格
@return table 包含所有唯一值的新表格
]]
function table.unique(t)
local check = {}
local n = {}
for k, v in pairs(t) do
if not check[v] then
n[k] = v
check[v] = true
end
end
return n
end
--[[--
指定表是否为空
@param table t 表格
@return 不为空返回true , 否则false
]]
function table.empty(t)
-- for k,v in pairs(tbl) do
-- return false
-- end
-- return true
return next(t)==nil
end
--[[--
清空表数据
@param table t 表格
]]
function table.clear(t)
if not t then return end
for k,v in pairs(t) do
t[k] = nil
end
end
--[[--
两个表是否相同
@param table t1 表格
@param table t2 表格
@return 相同返回true , 否则false
]]
function table.equal(t1, t2)
if not t1 or not t2 then
return false
end
if t1 == t2 then
return true
end
if table.nums(t1) ~= table.nums(t2) then
return false
end
for k,v in pairs(t1) do
if t2[k] ~= v then
return false
end
end
return true
end
--[[--
深度拷贝表
@param table src 源表
]]
function table.deepcopy(src)
if type(src) ~= "table" then
return src
end
local cache = {}
local function clone_table(t, level)
if not level then
level = 0
end
if level > 100 then
return t
end
local k, v
local rel = {}
for k, v in pairs(t) do
if type(v) == "table" then
if cache[v] then
rel[k] = cache[v]
else
rel[k] = clone_table(v, level+1)
cache[v] = rel[k]
end
else
rel[k] = v
end
end
setmetatable(rel, getmetatable(t))
return rel
end
return clone_table(src)
end
--[[--
目标表中指定Key是否有值
@param table t 目标表
@param key 键值
@return 如果有值,返回对应的value,否则返回nil,
]]
function table.hasvalue(t, key)
for k,v in pairs(t) do
if v == key then
return k
end
end
return nil
end
--[[--
返回Array中的最大值
--注意:不是Hash-table
@param table arr 有序表(array)
]]
function table.max(arr)
return math.max (unpack(arr))
end
--[[--
--返回Array中的最小值
--注意:不是Hash-table
@param table arr 有序表(array)
]]
function table.min(Array)
return math.min (unpack(Array))
end
--[[--
从table中随机返回n个k,v的table
]]
function table.randoms(t)
local Keys = table.keys(t)
local n = #Keys
local ret = {}
for i=1, n do
local R = math.random(1, #Keys)
local key = Keys[R]
local value = t[key]
ret[key]=value
table.remove(Keys, R)
end
return ret
end
--[[--
根据表中的某个key的值进行排序
@param table tbl 需要排序的表
@param Key key 指定键
@return 返回{k=key,v=data}的数组
]]
function table.sortbykey(tbl,key)
local Keys = table.keys(tbl)
local Size = #Keys
for i=1, Size do
for j=i, Size do
if tbl[Keys[i]][key] and tbl[Keys[j]][key] then
if tbl[Keys[i]][key] > tbl[Keys[j]][key] then
--交换
local Tmp = Keys[i]
Keys[i] = Keys[j]
Keys[j] = Tmp
end
end
end
end
local ret = {}
for i,key in ipairs(Keys) do
table.insert(ret,{k=key,v=tbl[key]})
end
return ret
end
--[[--
根据表中的值进行排序
@param table tbl 需要排序的表
@return 排序完成的keys映射表
]]
function table.sortbyvalue(tbl)
--传说中的选择排序
local Keys = table.keys(tbl)
local Size = #Keys
for i=1, Size do
for j=i, Size do
if tbl[Keys[i]] > tbl[Keys[j]] then
--交换
local Tmp = Keys[i]
Keys[i] = Keys[j]
Keys[j] = Tmp
end
end
end
return Keys
end
--[[--
自定义排序
@param table arr 需要排序的有序(array)表
@param function func 排序方法
]]
function table.insertsort(arr, func)
if #arr<=1 then return end
for i = 2,#arr do
local temp = arr[i]
local j = i-1
while j>=1 do
local _is =false
if func then
_is =func(temp, arr[j])
else
_is = temp > arr[j]
end
if _is then
arr[j+1] = arr[j]
j = j-1
else
break
end
end
arr[j+1] = temp
end
end
--[[--
反转一个有序array
@param table Array 有序表
]]
function table.reverse(Array)
local size = #Array
for i=1, math.floor(size/2) do
local tmp = Array[i]
Array[i] = Array[size+1-i]
Array[size+1-i] = tmp
end
end
--Returns a new tbl that is n copies of the tbl.
function table.rep(Tbl, n)
if n < 1 then
return nil
end
local Tmp = {}
for k=1, n do
table.insert(Tmp, Tbl)
end
end
--[[--
判断包含关系(array only)
]]
function table.contain(Big, Small)
for _, Each in pairs(Small) do
if not table.member_key(Big, Each) then
return false, Each
end
end
return true
end
--[[--
将array1与array2里面对应位置合成mapping的一个pair
]]
function table.mapping(array1, array2)
local ret = {}
for k,v in ipairs(array1) do
ret[v] = array2[k]
end
return ret
end
--// table.binsert( table, value [, comp] )
-- LUA 5.x ADD-On for the table library
-- Inserts a given value through BinaryInsert into the table sorted by [,comp]
-- If comp is given, then it must be a function that receives two table elements,
-- and returns true when the first is less than the second or reverse
-- e.g. comp = function( a, b ) return a > b end , will give a sorted table, with the biggest value on position 1
-- [, comp] behaves as in table.sort( table, value [, comp] )
-- This method is faster than a regular table.insert( table, value ) and a table.sort( table [, comp] )
function table.binsert( t, value, fcomp )
-- Initialise Compare function
fcomp = fcomp or function( a, b ) return a < b end
-- Initialise Numbers
local iStart, iEnd, iMid, iState = 1, table.getn( t ), 1, 0
-- Get Insertposition
while iStart <= iEnd do
-- calculate middle
iMid = math.floor( ( iStart + iEnd )/2 )
-- compare
if fcomp( value , t[iMid] ) then
iEnd = iMid - 1
iState = 0
else
iStart = iMid + 1
iState = 1
end
end
table.insert( t, ( iMid+iState ), value )
end
--// table.bfind( table, value [, compvalue] [, reverse] )
-- LUA 5.x ADD-On for the table library
-- Searches the table through BinarySearch for value, if the value is found it returns the index
-- and the value of the table where it was found
-- If compvalue is given then it must be a function that takes one value and returns a second value2
-- to be compared with the input value, e.g. compvalue = function( value ) return value[1] end
-- If reverse is given then the search assumes that the table is sorted with the biggest value on position 1
function table.bfind( t, value, fcompval, reverse )
-- initialise Functions
fcompval = fcompval or function( value ) return value end
fcomp = function( a, b ) return a < b end
if reverse then
fcomp = function( a, b ) return a > b end
end
-- Initialise Numbers
local iStart, iEnd, iMid = 1, table.getn( t ), 1
-- Binary Search
while (iStart <= iEnd) do
-- calculate middle
iMid = math.floor( ( iStart + iEnd )/2 )
-- get compare value
local value2 = fcompval( t[iMid] )
if value == value2 then
return iMid, t[iMid]
end
if fcomp( value , value2 ) then
iEnd = iMid - 1
else
iStart = iMid + 1
end
end
end
--传入一个类似这样的table:{[1] = {Odds = 50}, [2] = {Odds = 50}}
--根据随机取到key返回
function table.get_key_by_odds(Tbl, FullOdds)
if Tbl == nil then
return nil
end
--兼容某些传入的是小数的情况
local Ext=100
if not FullOdds then
FullOdds = 0
for k,v in pairs(Tbl) do
FullOdds = FullOdds + v.Odds*Ext
end
else
FullOdds = FullOdds*Ext
end
--注意,nil和无参数是不一样的
local Ran = math.random(FullOdds)
local TotalRan = 0
for key, subTbl in pairs(Tbl) do
TotalRan = TotalRan + subTbl.Odds*Ext
if Ran <= TotalRan then
return key
end
end
end<file_sep>/Assets/GEngineScript/Core/NetworkSystem/Socket/SocketTcp.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace GEX.Network
{
/// <summary>
/// Socket TCP协议操作
/// </summary>
public sealed class SocketTcp
{
private SocketState socketState = SocketState.Disconnected;
private string serverAddress;
private int serverPort;
private Socket socket;
private Thread socketThread;
private const int MAX_TIMEOUT = 15000;
private const int MAX_BYTE_BUFFER = 4096;
private byte[] byteBuffer = new byte[MAX_BYTE_BUFFER];
private readonly object _syncer = new object();
public Action<byte[]> OnReceivedMsg;
#region ------Public Attributes---------
public SocketState SocketState
{
get { return socketState; }
}
/// <summary>
/// 是否已成功连接,true表示已连接
/// </summary>
public bool IsConnected
{
get { return socketState == SocketState.Connected; }
}
#endregion
/// <summary>
/// 连接
/// </summary>
/// <returns></returns>
public bool Connect(string serverIp , ushort port)
{
if (this.socketState != SocketState.Disconnected)
{
Debugger.LogError("Calling connect when the socket is not disconnected");
return true;
}
this.socketState = SocketState.Connecting;
this.serverAddress = serverIp;
this.serverPort = port;
this.onConnectStart();
return false;
}
/// <summary>
/// 执行启动Socket连接
/// </summary>
private void onConnectStart()
{
try
{
IPAddress ipAddress = getIpAddress(this.serverAddress);
socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.SendTimeout = MAX_TIMEOUT;
socket.NoDelay = true;
this.socket.Connect(ipAddress, this.serverPort);
this.socketState = SocketState.Connected;
}
catch (Exception)
{
throw;
}
//启动socket连接线程
socketThread = new Thread(new ThreadStart(this.onThread));
socketThread.IsBackground = true;
socketThread.Start();
}
/// <summary>
/// 获得IP Address的类型
/// </summary>
/// <param name="serverIp"></param>
/// <returns></returns>
protected IPAddress getIpAddress(string serverIp)
{
IPAddress address = (IPAddress)null;
IPAddress ipAddress;
if (IPAddress.TryParse(serverIp, out address))
{
ipAddress = address;
}
else
{
IPAddress[] addressList = Dns.GetHostEntry(serverIp).AddressList;
foreach (IPAddress ipAddress2 in addressList)
{
if (ipAddress2.AddressFamily == AddressFamily.InterNetwork)
return ipAddress2;
}
foreach (IPAddress ipAddress2 in addressList)
{
if (ipAddress2.AddressFamily == AddressFamily.InterNetworkV6)
return ipAddress2;
}
ipAddress = (IPAddress)null;
}
return ipAddress;
}
/// <summary>
/// 主动断开连接
/// </summary>
/// <returns></returns>
public bool Disconnect()
{
if (this.socketState == SocketState.Disconnected)
return false;
this.socketState = SocketState.Disconnecting;
lock (_syncer)
{
if (this.socketThread != null)
this.socketThread.Abort();
this.socketThread = null;
if (this.socket != null)
{
try
{
this.socket.Close();
}
catch (Exception e)
{
Debugger.LogException("Socket Tcp disconnect error " , e);
}
socket = null;
}
this.socketState = SocketState.Disconnected;
}
return true;
}
/// <summary>
/// 发送请求到服务器
/// </summary>
/// <param name="msgs"></param>
/// <returns></returns>
public bool Send(byte[] msgs)
{
if (this.socketState != SocketState.Connected)
{
Debugger.LogError("Trying to write to disconnected socket");
return false;
}
try
{
socket.Send(msgs);
}
catch (Exception)
{
throw;
}
return true;
}
private void onThread()
{
int size = 0;
try
{
while (socketState == SocketState.Connected)
{
size = this.socket.Receive(this.byteBuffer, 0, MAX_BYTE_BUFFER, SocketFlags.None);
if (size <= 0)
throw new SocketException(10054);
byte[] msgs = new byte[size];
Buffer.BlockCopy(byteBuffer, 0, msgs, 0, size);
this.onReceiveMsgs(msgs);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// 接收读取数据
/// </summary>
/// <param name="msgs"></param>
private void onReceiveMsgs(byte[] msgs)
{
//传递到数据解析层
OnReceivedMsg.Invoke(msgs);
}
}
}
<file_sep>/Assets/GameScript/Lua/Test/Util/SingleTaskTest.lua
local SingleTaskTest = class("SingleTaskTest")
function SingleTaskTest:Start ()
--StartCoroutine(DoSomethingAsynchonously());
--//TaskRunner.Instance.Run(new SingleTask(DoSomethingAsynchonously())); //use this if you are not in a monobehaviour
TaskRunner.run(SingleTask.new(handler(self , self.DoSomethingAsynchonously)))
end
function SingleTaskTest:TestCoroutine( )
print("TestCoroutine")
coroutine.start(handler(self , self.DoSomethingAsynchonously))
--coroutine.create(self.DoSomethingAsynchonously)
end
function SingleTaskTest:DoSomethingAsynchonously()
self.variableThatCouldHaveBeenUseful = false
coroutine.next(handler(self , self.SomethingAsyncHappens))
--coroutine.resume(curCo)
self.variableThatCouldHaveBeenUseful = true
print("index is: " .. tostring(self.i))
end
function SingleTaskTest:SomethingAsyncHappens()
for i = 1 , 3 do
self.i = i
print("i:" .. i)
coroutine.step()
end
coroutine.next(handler(self , self.SomethingAsyncHappensB))
print("SomethingAsyncHappens end")
end
function SingleTaskTest:SomethingAsyncHappensB()
for i = 21 , 23 do
self.i = i
print("i:" .. i)
coroutine.step()
end
print("Happen B end")
end
test = SingleTaskTest.new()
test:Start()
--test:TestCoroutine()
return SingleTask<file_sep>/Assets/GameScript/Lua/Net/NetClient.lua
require('Net/Socket')
NetClient = {}
NetClient.SokcetError = {
['eSendError'] = 0, -- /*发送数据错误 */
['eRecvError'] = 1, -- /*接受数据错误*/
['eTransError'] = 2, -- /*事务错误*/
}
--/*网络IO状态*/
NetClient.NetWorkState = {
['eDisConnected'] = 0, -- /*断开连接的*/
['eLoging'] = 1, -- /*登录中*/
['eReactiving'] = 2, -- /*激活中*/
['eWorking'] = 3 -- /*运行中*/
}
NetClient.KickCode = {
['eDUPLICATE_LOGIN'] = 0, -- /** 0 - 重复登录 */
['eBLOCK_LOGIN'] = 1, -- /** 1 - 玩家被封禁 */
['eLOGIN_TIMEOUT'] = 2, -- /** 2 - 登录超时 */
['eSERVER_CLOSED'] = 3, -- /** 3 - 服务器维护 */
}
NetClient.NetErrorType = {
['eNoError'] = 0,
['eConnectError'] = 6, --/*网络连接错误 -(有限次重试)*/
['eBuildNetError'] = 1, --/*建立网络错误 -(重登录)*/
['eLoginError'] = 7, --/*登录错误 -(重登录)*/
['eReactiveError'] = 8, --/*激活错误 -(重登录)*/
['eTransError'] = 4, --/*事务传输错误 -(重登录)*/
['eSendError'] = 2, --/*发送事务数据错误 -(重激活)*/
['eRecvTimeout'] = 5, --/*网络接收超时错误 -(重登录)*/
['eDisConnectError'] = 3, --/*网络断开错误 -(重激活)*/
['eKickError'] = 9 --/*服务器主动踢掉错误 -(重登录)*/
}
function NetClient:init()
self.socket = NetCore.Net.New()
self.netPackProtocol = NetCore.PackProtocol.New()
self.netSendPackVStream = NetCore.VarintStream.New()
self.netRespPackVStream = NetCore.VarintStream.New()
self.sendPackQueue = Dequeue.new()
self.netWorkState = NetClient.NetWorkState.eDisConnected
self.netErrorType = NetClient.NetErrorType.eNoError
self.beatTimeCount = 15.0
self.lastBeatTime = 0
self.flag_heart_beat = false
self.flag_trans_timeout_tip = false
self.flag_trans_lock = false
self.flag_do_building = false
self.flag_ready_notify = false
self.netPacket = nil
self.fnNetError = nil
-- self.serverId = ''
end
function NetClient:setIp( ip,port )
self.socket:setIp(ip,port)
end
function NetClient:setErrorCB(fn)
self.fnNetError = fn
end
function NetClient:_notifyMessage(msg,...)
if not self.msgListeners then
return
end
for listener,l in pairs(self.msgListeners) do
listener(msg,...)
end
end
function NetClient:registerNetMessage(listener)
if not self.msgListeners then
self.msgListeners = {}
end
self.msgListeners[listener] = listener
end
function NetClient:removeNetMessage(listener)
self.msgListeners[listener] = nil
end
function NetClient:sendRequest(req,tSend,tResp,fnRespond)
-- 构造一个包
local packet = {}
packet['MOD'] = req['_MOD_']
packet['MED'] = req['_MED_']
packet.req = req
packet.tSend = tSend
packet.tResp = tResp
packet.fnRespond = fnRespond
--发送请求包
--log("packet - ok")
self:sendPacket(packet)
end
function NetClient:serializePacket(packet)
-- 构建缓冲
--log("sendRequest-ByteBuffer:new")
local netPackBuffer = NetCore.ByteArray.New()
--log("attachBuffer")
self.netSendPackVStream:attachBuffer(netPackBuffer)
--log("attachBuffer - ok")
-- 处理发送包头
--log("hanlde head")
log("req module = " ..packet.req['_MOD_'] .. " req mothed = " ..packet.req['_MED_'] )
self.netSendPackVStream:writeInt8(packet.req['_MOD_'])
self.netSendPackVStream:writeInt8(packet.req['_MED_'])
self.netSendPackVStream:writeInt32(0)--预留六字节
self.netSendPackVStream:writeInt16(0)
--log("hanlde head - ok")
-- 请求处理回调(请求序列化)
local T = NetProto.TE.create(NetProto.WT,self.netSendPackVStream,packet.req)
packet.tSend(T)
-- 写签名缓冲
netPackBuffer = self.netPackProtocol:signByteStream(netPackBuffer)
self.netSendPackVStream:detachBuffer()
packet.sendBuffer = netPackBuffer
end
---
--@param byteBuffer ByteBuffer
function NetClient.signByteStream(byteBuffer)
--local moduleNumber = byteBuffer:
end
--推送玩家下线,0:重登,1:封禁,2:登录超时,3:服务器维护
function NetClient:msgPushPlayerKickoff(code)
self:onNetKickError(code.vint32)
end
function NetClient:startNetClient()
self.socket:startNet()
--self:resetNet()
-- self.socket:setErrorNotify(function(error)
-- self:onSocketError(error)
-- end)
LateUpdateBeat:Add(function()self:onUpdate()end,nil)
end
function NetClient:shutdownNet()
--self:freeWork()
self.socket:shutdownNet()
self.sendPackQueue:removeAll()
LateUpdateBeat:Remove(function()self:onUpdate()end,nil)
--self.socket:setErrorNotify(nil)
end
function NetClient:onSocketError(error)
log("onSocketError#############################################")
if error == NetClient.SokcetError.eSendError then
self:onNetSendError()
elseif error == NetClient.SokcetError.eRecvError then
self:onNetRecvError()
elseif error == NetClient.SokcetError.eTransError then
self:onNetTransError()
end
end
function NetClient:reactiveGame()
if not self.socket:isConnected() then
self.netWorkState = NetClient.NetWorkState.eReactiving
self:connectNetAsyc(
function(rst)
if rst == true then
local req = NetProtoUser.SendReconnect:new()
req.username = modulePlayer.username
req.validKey = modulePlayer.validKey
req.selectPlayerId = modulePlayer.role.id
req.firstBindTime = modulePlayer.bindTime
req:send(
-- UserProtocol::BindPlayerVO vo
function(vo)
if vo.result then
--modulePlayer.bindTime = vo.bindTime
TimeService:adjustServerTime(math.floor(vo.bindTime / 1000))
TimeService:setServerTimeZoneDiff(vo.timeZone)
--登录成功(更新状态为-正常工作)
self.netWorkState = NetClient.NetWorkState.eWorking
self:hearBeatON()
self:_notifyMessage('reactive_game')
else
self:onNetReactiveError()
end
end)
end
end)
else
assert(false,"网络已连接中.")
end
end
function NetClient:onUpdate()
--self:handleHeartBeatTime()
self:handleRevQueue()
self:handleSendTimeOut()
--log("network ok!")
end
function NetClient:sendNext()
if self.netPacket then
return
end
if self.sendPackQueue:empty() then
return
end
local netPacket = self.sendPackQueue:popFront()
self.netPacket = netPacket
self:serializePacket(netPacket)
self.socket:sendBytes(netPacket.sendBuffer)
--log("ByteBuffer:releaseownership")
-- local rst = tolua.releaseownership(netPacket.sendBuffer)
-- assert(rst,"send WTF!")
--log("send attach")
local module = netPacket['MOD']
local method = netPacket['MED']
log("发送网络消息:Module:"..module.." Method:"..method)
self.sendClock = os.clock()
--self.socket:sendNext()
end
function NetClient:handleRevQueue()
local revBuffer = self.socket:pickRevQueue()
if nil == revBuffer then
return
end
local varStream = self.netRespPackVStream
--log("rev attach")
varStream:attachBuffer(revBuffer)
-- 处理响应包头 --读包头
--local len = varStream:readInt32()
local sn = varStream:readInt8()
local module = varStream:readVarint8()
local method = varStream:readVarint8()
if method < 100 then
local sendPacket = self.netPacket
self.netPacket = nil
--断言回应方法与之对应
assert(module == sendPacket['MOD'],'respond module number no match! .. module = ' ..module .. " ### sendPacket['MOD'] = "..sendPacket['MOD'] )
assert(method == sendPacket['MED'],'respond module number no match!')
local nowClock = os.clock()
local diffTick = nowClock- self.sendClock
self:sendNext()
local o = {}
local T = NetProto.TE.create(NetProto.RT,varStream,o)
sendPacket.tResp(T)-- 数据包回调
if (o._result_ == nil) or (o._result_ == true) then
if not(sendPacket.fnRespond == nil) then
local startClock = os.clock()
sendPacket.fnRespond(o)
local nowClock = os.clock()
local diffTick = nowClock- startClock
log("响应处理时间"..diffTick..".2f):Module:"..module.." Method:"..method)
end
else
log("服务器返回了错误响应!")
end
else
log("收到一个推送消息:Module:%d Method:%d",module,method)
local startClock = os.clock()
local netModule = NetProto.NetModule[module]
local netProto = netModule.MesssagePush[method]
local msgName = netProto.msg
local st = netProto.st
local listeners = netModule.msgPushInterface
local vo = {}
local T = NetProto.TE.create(NetProto.RT,varStream,vo)
st(T)
NotifyEvent(netModule,'msgPushInterface',msgName,vo)
local nowClock = os.clock()
local diffTick = nowClock- startClock
log("处理时间(%.2f)",diffTick)
--log("MakeFightActionOnce cost:%.2f",diffTick)
end
varStream:detachBuffer()
if self.sendPackQueue:empty() and self.flag_trans_lock then
self:freeTrans()
end
end
function NetClient:sendPacket(netPacket)
local mod = netPacket['MOD']
local med = netPacket['MED']
if self.flag_do_building and
--如果是登录或者重连,则请求包放在队列前.
mod == NetProtoUser.SendLogin._MOD_ and(
med == NetProtoUser.SendLogin._MED_ or
med == NetProtoUser.SendReconnect._MED_) then
self.sendPackQueue:pushFront(netPacket)
--self.socket:sendBytesFront(netPacket.sendBuffer)
--log("sendBytesFront - ok")
else
self.sendPackQueue:pushBack(netPacket)
--self.socket:sendBytes(netPacket.sendBuffer)
--log("sendBytes - ok")
end
if mod == NetProtoUser.SendHeartBeat._MOD_ and
med == NetProtoUser.SendHeartBeat._MED_ then
self:sendNext()
return --心跳不锁屏
end
-- 为什么 要返回?? (因为断网继续发请求会引起锁屏,无法点击重连按钮)
-- if not(self.socket:isWorking()) or
-- not(self.socket:isConnected()) then
-- return
-- end
-- if not self.flag_trans_lock then
-- self.flag_trans_lock = true
-- --锁屏
-- UI:lockInteraction()
-- self:TransTimeOutON()
-- end
self:sendNext()
end
function NetClient:TransTimeOutON()
self.flag_trans_timeout_on = true
self.nTimeOutCount = 0
end
function NetClient:TransTimeOutOFF()
self.flag_trans_timeout_on = false
self.nTimeOutCount = 0
end
function NetClient:handleSendTimeOut(dt)
if not self.flag_trans_timeout_on then
return
end
self.nTimeOutCount = self.nTimeOutCount + Time.deltaTime
--可以配表,暂时写死
local sendTimeout = 0.25
local transTimeOut = 25
if not self.flag_trans_timeout_tip and
self.nTimeOutCount >= sendTimeout then
self:onTransTimeOutTip()
elseif self.nTimeOutCount >= transTimeOut then
self:onRecvTimeout()
end
end
function NetClient:onTransTimeOutTip()
self.flag_trans_timeout_tip = true
UI:showNetWaitREQ()
end
function NetClient:hearBeatONTimeUpdate()
self.lastBeatTime = os.clock()
end
function NetClient:hearBeatON()
self.flag_heart_beat = true
end
function NetClient:handleHeartBeatTime()
-- if not(self.socket:isWorking()) or
-- not(self.socket:isConnected()) or
-- not self.flag_heart_beat then
-- return
-- end
local now = os.clock()
if (now - self.lastBeatTime) > self.beatTimeCount then
self:hearBeatONTimeUpdate()
if not (self.sendPackQueue:empty()) then
return
end
self:heartBeatOFF()
local req = NetProtoUser.SendHeartBeat:new()
req:send(function(vo)
self:hearBeatON()
--log("hearBeatON!")
end)
end
end
function NetClient:heartBeatOFF()
self.flag_heart_beat = false
end
function NetClient:freeTrans()
if self.flag_trans_lock == true then
self.flag_trans_lock = false
--请求事务发送中断-解锁屏
UI:delayUnlockInteraction()
self:TransTimeOutOFF()
if self.flag_trans_timeout_tip == true then
-- /*请求事务发送中断 - 解除请求提示*/
UI:stopNetTip()
self.flag_trans_timeout_tip = false
end
end
end
function NetClient:onRecvTimeout()
self:freeWork()
self:relogin('数据传输超时,\n请保持网络环境顺畅')
self.netErrorType = NetClient.NetErrorType.eRecvTimeout
self:notifyError()
end
function NetClient:onNetRecvError()
log("onNetRecvError")
--处理完所有的剩下的包.
while not self.socket:isRecvQueueEmpty() do
self:handleRevQueue()
end
--判断是否是KICK错误
if self.kickCode then
--已在KICK中处理.
return
end
--判断是否传输错误
if self.netPacket then
local netPacket = self.netPacket
log("NetRecvError:self.netPacket not nil.(it's a TransError)")
log("ERROR - MOD:%d,MED:%d",netPacket['MOD'],netPacket['MED'])
self:onNetTransError()
return
end
--只是连接断开,自动重连.
self:freeWork()
--自动重连
if self.netWorkState == NetClient.NetWorkState.eWorking then
self:reactiveGame()
end
self.netErrorType = NetClient.NetErrorType.eReactiveError
self:notifyError()
end
function NetClient:onNetSendError()
log("onNetSendError")
self:freeWork()
self:relogin('数据发送失败,\n请保持网络环境顺畅')
self.netErrorType = NetClient.NetErrorType.eSendError
self:notifyError()
end
function NetClient:onNetTransError()
log("onNetTransError")
self:freeWork()
self:relogin('数据传输错误,\n请保持网络环境顺畅')
self.netErrorType = NetClient.NetErrorType.eTransError
self:notifyError()
end
function NetClient:onNetConnectError()
log("onNetConnectError")
UI:stopNetTip()
self:retry("网络无法连接,\n请检查网络是否正确")
self.netErrorType = NetClient.NetErrorType.eConnectError
self:notifyError()
end
function NetClient:onNetKickError(kickCode)
log("onNetKickError")
self:freeWork()
self.kickCode = kickCode
if kickCode == NetClient.KickCode.eDUPLICATE_LOGIN then
self:relogin('当前账号已在其他设备上登录')
elseif kickCode == NetClient.KickCode.eLOGIN_TIMEOUT then
self:relogin('登陆过期')
elseif kickCode == NetClient.KickCode.eBLOCK_LOGIN then
self:relogin('账号已被锁定')
elseif kickCode == NetClient.KickCode.eSERVER_CLOSED then
self:relogin('服务器维护中')
else
self:relogin('网络连接错误')
end
self.netErrorType = NetClient.NetErrorType.eKickError
self:notifyError()
end
function NetClient:onNetLoginError()
log("onNetLoginError")
self:freeWork()
self:relogin('登录验证失败,\n请保持网络环境顺畅')
self.netErrorType = NetClient.NetErrorType.eLoginError
self:notifyError()
end
function NetClient:onNetReactiveError()
log("onNetReactiveError")
self:freeWork()
self:relogin('验证失效')
self.netErrorType = NetClient.NetErrorType.eLoginError
self:notifyError()
end
function NetClient:connectNetAsyc(cb)
if self.socket:isConnected() then
cb(true)
end
--/* 建立网络 - 锁屏*/
UI:showNetWaitForConnect()
UI:lockInteraction()
assert(not self.flag_do_building,"正在连接状态中,重复连接.")
self.flag_do_building = true
self.socket:connectNetScript(function(rst)
self.netPackProtocol:resetSN()
UI:unlockInteraction()
UI:stopNetTip()
if not rst then
-- /*连接失败 - 解锁屏*/
self.flag_do_building = false
self:onNetConnectError()
else
self:startWork()
end
cb(rst)
self.flag_do_building = false
end)
end
function NetClient:startWork()
if self.flag_start_work then
assert(false)
return
end
self.flag_start_work = true
self.socket:working()
NetProtoUser.listenMessagePush(self)
end
function NetClient:freeWork()
if not self.flag_start_work then
return
end
self.flag_start_work = false
self:heartBeatOFF()
self:freeTrans()
UI:stopNetTip()
NetProtoUser.removeMessagePush(self)
end
function NetClient:notifyError()
if (self.fnNetError) and (not self.flag_ready_notify) then
self.flag_ready_notify = true
self.fnNetError(self.netErrorType)
end
end
function NetClient:resetNet(cleanQueue)
self.kickCode = nil
self.netErrorType = NetClient.NetErrorType.eNoError
self.netWorkState = NetClient.NetWorkState.eDisConnected
self.flag_ready_notify = nil
self.flag_do_building = nil
self.netPacket = nil
self.socket:closeConnect()
self.netPackProtocol:resetSN()
if cleanQueue then
self.socket:clearDataQueue()
end
end
function NetClient:loginGame(lfn)
if not self.socket:isConnected() then
self.netWorkState = NetClient.NetWorkState.eLoging
self:connectNetAsyc(
function(rst)
if rst == true then
self.socket:clearDataQueue()
lfn(function(result)
if result then
--登录成功(更新状态为-正常工作)
self.netWorkState = NetClient.NetWorkState.eWorking
self:hearBeatON()
else
self:onNetLoginError()
end
end)
end
end)
else
assert(false,"网络已连接中.")
end
end
function NetClient:retry(msg)
UI:forceUnlock()
local board = require("Views/Common/NetTipBoard2Btn"):create()
board:setText(msg)
--board:setButtonText('重试')
board:setClickCB(function(name)
UI:freeForce()
if name == "left" then
UI:closeSysBoard()
local netWorkState = self.netWorkState
if netWorkState == NetClient.NetWorkState.eLoging then
--GameNet:resetNet(true)
--PSDK.User:loginGame()
APP.restart()
elseif netWorkState == NetClient.NetWorkState.eReactiving then
GameNet:resetNet(false)
GameNet:reactiveGame()
else
assert(false)
end
else
APP.restart()
end
end)
UI:pushSysBoard(board,false,nil,true)
end
function NetClient:relogin(msg)
UI:forceUnlock()
local board = require("Views/Common/NetTipBoard"):create()
board:setText(msg)
board:setButtonText("重新登录")
board:setClickCB(function()
UI:freeForce()
UI:closeSysBoard()
GlobalScheduler.delayCallOnce(function()
APP.restart()
end)
end)
moduleGuider:stopGuider()
UI:pushSysBoard(board,false,nil,true)
end
function NetClient:onNetError(code)
local error = code
local NetErrorType = NetClient.NetErrorType
end<file_sep>/Assets/GameScript/Lua/UI/Skill/SkillUpdatePanel.lua
-- @Author:
-- @Last Modified time: 2017-01-01 00:00:00
-- @Desc:
SkillUpdatePanel = {}
local this = SkillUpdatePanel
local curUiId = 0
--- 由LuaBehaviour自动调用
function SkillUpdatePanel.Awake(gameObject)
this.widgets = {
{field="root", path ="", src=LuaCanvas},
{field="btn_Confirm",path="desc.btn_Confirm",src=LuaButton, onClick = this._onClickConfirm },
}
LuaUIHelper.bind(this.gameObject , SkillUpdatePanel )
end
function SkillUpdatePanel.Show( func )
UIManager:Show("Prefab/GUI/Skill/SkillUpdatePanel", nil)
this.closeFunc = func
end
--- 由LuaBehaviour自动调用
function SkillUpdatePanel.OnInit(basePage)
this.basePage = basePage
this.basePage:SetPage(EPageType.Normal , EShowMode.HideOther , ECollider.None)
--每次显示自动修改UI中所有Panel的depth
--LuaUIHelper.addUIDepth(this.gameObject , SkillUpdatePanel)
this._registeEvents(this.event)
end
-- 注册界面事件监听
function SkillUpdatePanel._registeEvents(event)
end
function SkillUpdatePanel._onClickConfirm()
UIManager:Hide(basePage.assetPath)
end
--- 关闭界面
function SkillUpdatePanel._onClickClose( )
--panelMgr:ClosePanel("SkillUpdatePanel")
if this.closeFunc ~= nil then
this.closeFunc()
this.closeFunc = nil
end
end
--- 由LuaBehaviour自动调用
function SkillUpdatePanel.OnClose()
--LuaUIHelper.removeUIDepth(this.gameObject) --还原全局深度
end
--- 由LuaBehaviour自动调用--
function SkillUpdatePanel.OnDestroy()
this.gameObject = nil
this.transform = nil
this.widgets = nil
end<file_sep>/Assets/GameScript/Lua/Collections/Stack.lua
--[[
Author: LiangZG
Email : <EMAIL>
]]
local Stack = class("Stack")
function Stack:ctor( initCapactity )
self._capactity = initCapactity
self._array = Array.new()
self._size = 0
end
function Stack:push( item )
if self._size == self._capactity then
self._capactity = self._capactity * 2
local newArr = Array.new()
Array.copy(self._array , 1 , newArr , 1 , self._capactity)
self._array = newArr
end
self._size = self._size + 1
self._array:insert(self._size , item)
end
function Stack:pop( )
if self._size == 0 then return nil end
local obj = self._array[self._size]
self._array[self._size] = false
self._size = self._size - 1
return obj
end
function Stack:peek( )
if self._size == 0 then return nil end
return self._array[self._size]
end
function Stack:contains( obj )
return self._array:indexOf(obj) ~= -1
end
function Stack:size( )
return self._size
end
function Stack:clear( )
self._array:clear()
self._size = 0
end
function Stack:enumerator( )
local i = self._size + 1
return function ( )
i = i - 1
return self._array[i]
end
end
function Stack:getEnumerator( )
return Enumerator.new(self._size + 1, -1 , function ( i )
return self._array[i]
end)
end
function Stack:toString( )
return self._array:toString()
end
return Stack
<file_sep>/Assets/GameScript/Lua/Collections/Enumerator.lua
--[[
Author: LiangZG
Email : <EMAIL>
Desc : 容器迭代器 , 列表的下标从1开始
]]
local Enumerator = class("Enumerator")
function Enumerator:ctor( init, offset, func )
self._pairs = func
self._index = init
self._nextOffset = offset
end
function Enumerator:current( )
return self._current
end
function Enumerator:moveNext( )
return self:enumerator()
end
function Enumerator:enumerator()
self._index = self._index + self._nextOffset
self._current = self._pairs(self._index)
return self._current
end
return Enumerator<file_sep>/Assets/GameScript/Lua/Net/Protocol/Chat.lua
--local NetREQ_ = NetREQ
NetProtoChat = {}
NetProto.NetModule[7] = NetProtoChat
NetProtoChat.st = {
['SkIvVO'] = function(T)
if not(T:result()) then return end
T:vstring('key') --字符串型键名
T:vint32('value') --整形键值
end,
['ChatInfo'] = function(T)
if not(T:result()) then return end
T:vint32('channel') --channel
T:vstring('content') --content
T:vint64('playerId') --playerId
T:vstring('playerName') --playerName
T:vint64('targetId') --targetId
T:vstring('targetName') --targetName
end,
}
NetProtoChat.send = {
['CommonChat'] = function(T)
if not(T:result()) then return end
T:vstring('content') --聊天的信息
T:vint32('channel') --0系统,1世界,2帮派,3私聊
T:vstring('targetName') --私聊目标的名字(私聊需要)
end,
['InputGMCode'] = function(T)
if not(T:result()) then return end
T:vstring('content') --命令内容
end,
['Bgm'] = function(T)
if not(T:result()) then return end
T:vstring('content') --命令内容,用英文逗号','隔开
end,
['WordChatOpen'] = function(T)
if not(T:result()) then return end
end,
['WordChatClose'] = function(T)
if not(T:result()) then return end
end,
}
-- ***自动提示帮助***
NetProtoChat.SkIvVO = {
['key'] = nil, --字符串型键名
['value'] = nil, --整形键值
}
NetProtoChat.ChatInfo = {
['channel'] = nil, --channel
['content'] = nil, --content
['playerId'] = nil, --playerId
['playerName'] = nil, --playerName
['targetId'] = nil, --targetId
['targetName'] = nil, --targetName
}
local T = NetProto.st
-- ***请求处理***
--角色聊天
NetProtoChat.SendCommonChat = {
['new'] = NetProto.new,
['_MOD_'] = 7,
['_MED_'] = 1,
['content'] = nil, --聊天的信息
['channel'] = nil, --0系统,1世界,2帮派,3私聊
['targetName'] = nil, --私聊目标的名字(私聊需要)
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoChat.send.CommonChat, T.vint32, fnRespond)
end,
}
--GM命令
NetProtoChat.SendInputGMCode = {
['new'] = NetProto.new,
['_MOD_'] = 7,
['_MED_'] = 2,
['content'] = nil, --命令内容
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoChat.send.InputGMCode, T.vint32, fnRespond)
end,
}
--批量GM命令 --返回:key=>命令内容,value=>返回结果
NetProtoChat.SendBgm = {
['new'] = NetProto.new,
['_MOD_'] = 7,
['_MED_'] = 3,
['content'] = nil, --命令内容,用英文逗号','隔开
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoChat.send.Bgm, NetProto.st.array(NetProtoChat.st.SkIvVO), fnRespond)
end,
}
--开启世界聊天 --返回:聊天信息数组
NetProtoChat.SendWordChatOpen = {
['new'] = NetProto.new,
['_MOD_'] = 7,
['_MED_'] = 4,
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoChat.send.WordChatOpen, NetProto.st.array(NetProtoChat.st.ChatInfo), fnRespond)
end,
}
--关闭世界聊天
NetProtoChat.SendWordChatClose = {
['new'] = NetProto.new,
['_MOD_'] = 7,
['_MED_'] = 5,
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoChat.send.WordChatClose, T.vint32, fnRespond)
end,
}
-- ***推送处理***
NetProtoChat.MesssagePush = {
[101] = {['msg']='msgPushToOnline' ,['st'] = NetProtoChat.st.ChatInfo}, --世界聊天(推送给在线的)
[102] = {['msg']='msgPushToPlayers' ,['st'] = NetProtoChat.st.ChatInfo}, --推送给指定玩家
}
DeclareInterface(NetProtoChat, 'msgPushInterface')
function NetProtoChat.listenMessagePush(listener)
ListenInterface(NetProtoChat, 'msgPushInterface', listener)
end
function NetProtoChat.removeMessagePush(listener)
RemoveInterface(NetProtoChat, 'msgPushInterface', listener)
end
<file_sep>/Assets/GameScript/Lua/Test/Collection/QueueTest.lua
require "test"
test("enqueue should return a table with a , b , c ,size is 3" , function ( )
local queue = Queue.new()
queue:enqueue("a")
queue:enqueue("b")
queue:enqueue("c")
assertEqual(queue:size() , 3)
end)
test("dequeue should return a string" , function ( )
local queue = Queue.new()
queue:enqueue("a")
queue:enqueue("b")
queue:enqueue("c")
assertEqual(queue:dequeue() , "a")
assertEqual(queue:dequeue() , "b")
assertEqual(queue:dequeue() , "c")
end)
test("dequeue should return a nil when queue is empty" , function ( )
local queue = Queue.new()
assertEqual(queue:dequeue() , nil)
queue:enqueue(1)
assertEqual(queue:dequeue() , 1)
assertEqual(queue:dequeue() , nil)
end)
-- test("return size is zero when enqueue value is nil " , function ( )
-- local queue = Queue.new()
-- queue:enqueue()
-- assertEqual(queue:size() , 0)
-- end)
-- test("return size is zero when enqueue value is nil " , function ( )
-- local queue = Queue.new()
-- print("-----> set value nil----------- ")
-- queue["_size"] = nil
-- queue["_size"] = 999
-- print("-----> set value nil , size:" .. tostring(queue:size()))
-- end)
test("enqueue over init capactity will work !" , function ( )
local queue = Queue.new(2)
queue:enqueue("a")
queue:enqueue("b")
assertEqual(queue:dequeue() , "a")
assertEqual(queue:dequeue() , "b")
assertEqual(queue:dequeue() , nil)
queue:enqueue("c")
queue:enqueue("d")
queue:enqueue("e")
queue:enqueue("f")
queue:enqueue("g")
queue:enqueue("h")
assertEqual(queue:dequeue() , "c")
assertEqual(queue:dequeue() , "d")
assertEqual(queue:dequeue() , "e")
assertEqual(queue:dequeue() , "f")
assertEqual(queue:dequeue() , "g")
assertEqual(queue:dequeue() , "h")
assertEqual(queue:dequeue() , nil)
end)
test("peek dont change queue index !" , function ( )
local queue = Queue.new()
queue:enqueue("a")
queue:enqueue("b")
assertEqual(queue:peek() , "a")
assertEqual(queue:dequeue() , "a")
assertEqual(queue:peek() , "b")
assertEqual(queue:dequeue() , "b")
assertEqual(queue:dequeue() , nil)
end)
test('contains should returns correct position of value in the table', function()
local queue = Queue.new()
queue:enqueue("a")
queue:enqueue(1)
assertEqual(queue:contains('a'), true)
assertEqual(queue:contains(1), true)
end)
test('contains should returns false when the value is not in the table', function()
local queue = Queue.new()
queue:enqueue("a")
queue:enqueue(1)
assertEqual(queue:contains("b"), false)
assertEqual(queue:contains(2), false)
queue:clear()
assertEqual(queue:contains(1), false)
end)
test('getEnumerator should returns all element ', function()
local queue = Queue.new()
queue:enqueue("a")
queue:enqueue(1)
queue:enqueue("b")
queue:enqueue("false")
local str = {}
local rator = queue:getEnumerator()
while rator:moveNext() do
table.insert(str , rator:current())
end
str = table.concat( str, ",")
print("allValue:" .. str)
assertEqual(str , "a,1,b,false")
end)
<file_sep>/Assets/GameScript/Lua/AppMain.lua
--[[
Author: LiangZG
Email : <EMAIL>
应用Main入口
]]
AppMain = {}
--主入口
function AppMain.Main()
local machine = Fsm.new()
AppMain.Fsm = machine
machine:OnEnter(MainState.new())
end
--主应用释放
function AppMain.Destroy()
end
<file_sep>/Assets/GameScript/ConstDefine/LuaConst.cs
using System.IO;
using LuaInterface;
using UnityEngine;
public static class LuaConst
{
//lua逻辑代码目录
public static string[] luaDirs =
{
// Application.dataPath + "/GEngineScript/Lua" ,
Application.dataPath + "/GameScript/Lua"
};
public static string toluaDir = Application.dataPath + "/Libs/ToLua/Lua"; //tolua lua文件目录
#if UNITY_STANDALONE
public static string osDir = "Runtime";
#elif UNITY_ANDROID
public static string osDir = "Android";
#elif UNITY_IPHONE
public static string osDir = "iOS";
#else
public static string osDir = "";
#endif
public static string luaResDir = string.Format("{0}/{1}/Lua", AppPathUtils.PersistentDataRootPath, osDir); //手机运行时lua文件下载目录
#if UNITY_EDITOR_WIN || NITY_STANDALONE_WIN
public static string zbsDir = "D:/ZeroBraneStudio/lualibs/mobdebug"; //ZeroBraneStudio目录
#elif UNITY_EDITOR_OSX || UNITY_STANDALONE_OSX
public static string zbsDir = "/Applications/ZeroBraneStudio.app/Contents/ZeroBraneStudio/lualibs/mobdebug";
#else
public static string zbsDir = luaResDir + "/mobdebug/";
#endif
public static bool openLuaSocket = true; //是否打开Lua Socket库
public static bool openZbsDebugger = false; //是否连接ZeroBraneStudio调试
/// <summary>
/// 添加Lua文件搜索目录
/// </summary>
public static void AddSearchDir()
{
if (!Directory.Exists(LuaConst.toluaDir))
{
string msg = string.Format("toluaDir path not exists: {0}, configer it in LuaConst.cs", LuaConst.toluaDir);
throw new LuaException(msg);
}
LuaState.AddSearchPathStatic(LuaConst.toluaDir);
//添加项目Lua文件路径
foreach (string luaDir in luaDirs)
{
addAllDir(luaDir);
}
}
/// <summary>
/// 添加所有子目录路径
/// </summary>
/// <param name="rootDir"></param>
private static void addAllDir(string rootDir)
{
if (!Directory.Exists(rootDir))
{
string msg = string.Format("luaDir path not exists: {0}, configer it in LuaConst.cs", rootDir);
throw new LuaException(msg);
}
string[] subDirs = Directory.GetDirectories(rootDir, "*", SearchOption.AllDirectories);
foreach (string subDir in subDirs)
{
string dir = subDir.Replace("\\", "/");
LuaState.AddSearchPathStatic(dir);
}
LuaState.AddSearchPathStatic(rootDir);
}
}<file_sep>/Assets/GameScript/Lua/Util/goHelper.lua
-- Author: LiangZG
-- Email : <EMAIL>
-- GameObject 帮助工具集
local m = {}
local this = m
--交换一个组件对象,如果不存在,将添加对应的组件
function m.SwapComponent(gObj , typeCom )
local comIns = gObj:GetComponent(typeCom)
if not comIns then
comIns = gObj:AddComponent(typeCom)
end
return comIns
end
--设置结点的图层
-- depath 是否遍历
function m.setLayer( root , layerName , depath )
root.layer = LayerMask.NameToLayer(layerName)
if not depath then return end
local rootTrans = root.transform
for i=1,rootTrans.childCount do
this.setLayer(rootTrans:GetChild(i -1).gameObject , layerName , depath)
end
end
return m
<file_sep>/Assets/GEngineScript/Core/NetworkSystem/HeartBeatService.cs
using System;
using UnityEngine;
using System.Collections;
using System.Threading;
namespace GEX.Network
{
/// <summary>
/// 心跳服务
/// </summary>
public class HeartBeatService
{
private int interval = 5000; //5秒
private int timeout; //超时临界值
private float elaspedTime;
private Timer timer; //计时器
private DateTime lastTime;
private const float HEARTBEAT_DURATION = 150; //
private static readonly byte[] m_lockObject = new byte[0] {};
private NetClient netClient;
public Action OnLostConnect;
#region ---Public Attributes---
/// <summary>
/// 是否正在进行心跳
/// <returns>true表示心跳服务正在执行</returns>
/// </summary>
public bool IsBeating
{
get { return timer != null; }
}
#endregion
public HeartBeatService(NetClient net)
{
this.netClient = net;
}
// Use this for initialization
public void OnStart()
{
this.timer = new Timer(checkHeartBeat, null, 0, interval);
timeout = 0;
elaspedTime = HEARTBEAT_DURATION;
lastTime = DateTime.Now;
}
/// <summary>
/// 重置超时
/// </summary>
public void ResetTimeout()
{
lock (m_lockObject)
{
timeout = 0;
lastTime = DateTime.Now;
}
}
private void checkHeartBeat(object obj)
{
lock (m_lockObject)
{
TimeSpan span = DateTime.Now - lastTime;
timeout = (int)span.TotalMilliseconds;
//check timeout
if (timeout > interval * (netClient.IsPowerSaveMode ? 60 : 6))
{
if (OnLostConnect != null) OnLostConnect.Invoke();
}
}
}
// Update is called once per frame
public void OnUpdate()
{
elaspedTime -= Time.deltaTime;
if (elaspedTime <= 0)
{
elaspedTime = HEARTBEAT_DURATION;
netClient.ConnectObserver.NotifyEvent(ProtocalEvent.HeartBeat2Server , null);
}
}
public void OnPingUpdate()
{
ushort protocal = ProtocalEvent.PingUpdate;
ByteArray buffer = new ByteArray();
buffer.WriteShort((short)protocal);
netClient.ConnectObserver.NotifyEvent(protocal , buffer);
}
public void Stop()
{
if (timer != null)
timer.Dispose();
timer = null;
elaspedTime = 0;
}
}
}
<file_sep>/Assets/GameScript/Lua/GameState/init.lua
--[[
@Author: <EMAIL>
游戏状态机
]]
local GAMESTATE_MODE = ...
LoginState = import(".LoginState")
FightState = import(".FightState")
MainState = import(".MainState")
UpdateState = import(".UpdateState")
<file_sep>/Assets/GameScript/Lua/Collections/Array.lua
--[[
Author: LiangZG
Email : <EMAIL>
Desc : 有序Array容器 , 列表的下标从1开始
]]
local rawget = rawget
local Array = {}
Array.__index = function ( t , k )
local var = rawget(Array, k)
if var == nil then
var = t._array_[k]
end
return var
end
Array.__newindex = function ( t , k ,v )
if nil == t._array_[k] then
error(string.format("%s index out of range ." , k))
return
end
if nil == v then
print("cant not remove element by use 'nil' . ")
return
end
rawset(t._array_ ,k, v)
end
-- Array.__call = function ( t , ... )
-- return Array.new( unpack{...})
-- end
function Array.new( ... )
local args = {...}
local newArray = { typeof = "Array"}
--print("args:" .. print_lua_table(args) .. " , args[1] :" .. type(args[1]))
if type(args[1]) == "table" and #args == 1 then
newArray._array_ = {}
if Array.isArray(args[1]) then
for _,v in ipairs(args[1]) do
table.insert(newArray._array_ , v)
end
--print("args:" .. print_lua_table(args[1]) .. ", arrayLenth:" .. #newArray._array_)
end
else
newArray._array_ = args
end
setmetatable(newArray , Array)
return newArray
end
function Array:removeAt( index )
table.remove(self._array_ , index)
end
function Array:insert( index , item )
index = Mathf.Min(index , #self._array_ + 1)
table.insert(self._array_ , index , item)
end
function Array:length()
return #self._array_
end
--对象是否是数组
function Array.isArray(obj)
if type(obj) ~= "table" then return false end
if obj.typeof == "Array" then return true end
local i = 0
for _ in pairs(obj) do
i = i + 1
if obj[i] == nil then return false end
end
return true
end
--是否为空,true为空
function Array.isEmpty( obj )
return Array.isArray(obj) and obj:length() == 0
end
--切割数组,返回一个新的数组句柄,不影响原数组
-- @ [number] startIndex > 0 下标从1开始
function Array.slice( array , startIndex , endIndex )
if Array.isEmpty(array) then return nil end
local newArr = Array.new()
endIndex = endIndex or array:length()
for i=startIndex,endIndex do
newArr:insert(newArr:length() + 1, array[i])
end
return newArr
end
--添加多个元素
function Array:append( ... )
local elements = {...}
if #elements == 1 and type(elements[1]) == "table" then
elements = elements[1]
end
for i=1,#elements do
table.insert(self._array_ , #self._array_ + 1, elements[i])
end
end
function Array:indexOf( value )
for i,v in ipairs(self._array_) do
if v == value then return i end
end
return -1
end
--反转
function Array:reverse()
local newArr = Array.new()
for i=self:length() , 1 , -1 do
newArr:insert(newArr:length() + 1, self._array_[i])
end
return newArr
end
function Array:first()
return self._array_[1]
end
function Array:last( )
return self._array_[#self._array_]
end
--删除第一个元素,并返回删除元素
function Array:shift( )
local v = self._array_[1]
self:removeAt(1)
return v
end
--在第一个位置处插入指定元素,并返回当前数组大小
function Array:unshift( v )
self:insert(1 , v)
return self:length()
end
function Array:clear( )
self._array_ = {}
end
function Array.copy( srcArray , srcIndex , destArray , destIndex , length )
local j = destIndex
for i=srcIndex,srcIndex + length - 1 do
destArray:insert(j, srcArray[i])
j = j + 1
end
end
--将当前一维 Array 的所有元素复制到指定的一维 Array 中(从指定的目标 Array 索引开始)
function Array:copyTo( array , startIndex )
local j = 0
for i=startIndex,#self._array_ do
j = j + 1
array:insert(array:length() + j , self._array_[i])
end
end
--迭代器
function Array:enumerator()
local i = 0
return function ( )
i = i + 1
return self._array_[i]
end
end
function Array:toString( )
local str = {}
for k,v in ipairs(self._array_) do
table.insert(str , tostring(v))
end
return table.concat( str, ", ")
end
return Array<file_sep>/Assets/Libs/LuaDataBind/Core/DataBindingType.cs
namespace LuaDataBind
{
/// <summary>
/// Type of data binding.
/// </summary>
public enum DataBindingType
{
/// <summary>
/// Data is fetched from a data context.
/// </summary>
Context,
/// <summary>
/// Data is taken from a specific provider.
/// </summary>
Provider,
/// <summary>
/// Data is a constant value.
/// </summary>
Constant
}
}<file_sep>/Assets/GEngineScript/Core/ResourceSystem/GResource.cs
using UnityEngine;
using System.IO;
using System;
using System.Collections.Generic;
using LuaInterface;
using RSG;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace GEX.Resource
{
public static class GResource
{
public static string RuntimeAssetsRoot = "Assets/RuntimeAssets/";
#if UNITY_EDITOR
private static Dictionary<string, UIAtlasCache> atlasMap = new Dictionary<string, UIAtlasCache>();
#endif
#region 异步加载Bundle资源
/// <summary>
/// 异步加载Prefab
/// </summary>
/// <param name="assetPath">资源的项目相对路径</param>
/// <returns></returns>
public static LoadOperation LoadAssetAsync(string assetPath)
{
if (AppConst.AssetBundleMode)
{
return new LoadBundleAsync(null, assetPath);
}
assetPath = string.Concat(RuntimeAssetsRoot, assetPath);
return new LoadEditorAssetAsync(assetPath);
}
/// <summary>
/// 异步加载Prefab
/// </summary>
/// <param name="owner">资源关联的场景gameobject</param>
/// <param name="assetPath">资源的路径</param>
/// <returns></returns>
public static LoadOperation LoadAssetAsync(GameObject owner, string assetPath)
{
if (AppConst.AssetBundleMode)
{
return new LoadBundleAsync(owner, assetPath);
}
assetPath = string.Concat(RuntimeAssetsRoot, assetPath);
return new LoadEditorAssetAsync(assetPath);
}
/// <summary>
/// 从指定缓存池(poolA)中加载资源,如果缓存池中不存在资源,就从磁盘加载
/// <para>[[重要]]:加载完成后,需要使用指定的缓存池(poolA)进行实例(spawn)</para>
/// </summary>
/// <param name="cachePool">CachePoolAsync缓存池</param>
/// <param name="assetName">无后缀的资源路径</param>
/// <param name="owner">资源关联的场景gameobject(prefab类型资源可传空,其他类型资源必须有值)</param>
/// <param name="extension">文件后缀</param>
/// <returns></returns>
// public static LoadOperation LoadCacheBundleAsync(CachePoolAsync cachePool, string assetName, string extension = ".prefab")
// {
// string prefabName = assetName;
// string[] tempArr = assetName.Split('/');
// if(tempArr.Length > 0)
// prefabName = tempArr[tempArr.Length - 1];
// GameObject prefab = cachePool.GetCachePrefab(prefabName);
// if (prefab != null)
// {
// string assetPath = string.Concat(RuntimeAssetsRoot, assetName, extension);
// return new LoadAssetAsync(prefab , assetPath);
// }
// return LoadBundleAsync(null, assetName, extension);
// }
/// <summary>
/// 从指定缓存池(poolA)中加载资源,如果缓存池中不存在资源,就从磁盘加载
/// <para>[[重要]]:加载完成后,需要使用指定的缓存池(poolA)进行实例(spawn)</para>
/// </summary>
/// <param name="cachePool">CachePoolAsync缓存池</param>
/// <param name="owner">资源关联的场景gameobject(prefab类型资源可传空,其他类型资源必须有值)</param>
/// <param name="assetName">无后缀的资源路径</param>
/// <param name="extension">文件后缀</param>
/// <returns></returns>
// public static LoadOperation LoadCacheBundleAsync(CachePoolAsync cachePool, GameObject owner, string assetName, string extension = ".prefab")
// {
// string prefabName = assetName;
// string[] tempArr = assetName.Split('/');
// if (tempArr.Length > 0)
// prefabName = tempArr[tempArr.Length - 1];
// GameObject prefab = cachePool.GetCachePrefab(prefabName);
// if (prefab != null)
// {
// string assetPath = string.Concat(RuntimeAssetsRoot, assetName, extension);
// return new LoadAssetAsync(prefab, assetPath);
// }
// return LoadBundleAsync(owner, assetName, extension);
// }
#endregion
#region -------------------同步加载资源-------------------
/// <summary>
/// 加载Resources目录资源
/// </summary>
/// <param name="assetName"></param>
/// <returns></returns>
private static T loadResources<T>(string assetName) where T : UnityEngine.Object
{
string resAssetPath = assetName;
string ext = Path.GetExtension(assetName);
if (!string.IsNullOrEmpty(ext)) resAssetPath = assetName.Replace(ext, "");
T res = Resources.Load<T>(resAssetPath);
if (res == null)
Debug.LogError(string.Format("Cant find resource: ", assetName));
return res;
}
/// <summary>
/// 加载Resources目录资源
/// </summary>
/// <param name="assetName"></param>
/// <returns></returns>
public static UnityEngine.Object LoadResource(string assetName, Type type)
{
string resAssetPath = assetName;
string ext = Path.GetExtension(assetName);
if (!string.IsNullOrEmpty(ext)) resAssetPath = assetName.Replace(ext, "");
UnityEngine.Object res = Resources.Load(resAssetPath, type);
if (res == null)
Debug.LogError(string.Format("Cant find resource: ", assetName));
return res;
}
/// <summary>
/// 加载Resources目录文本资源
/// </summary>
/// <param name="assetName"></param>
/// <returns></returns>
public static TextAsset LoadTextAssets(string assetName)
{
return loadResources<TextAsset>(assetName);
}
/// <summary>
/// 加载Resources目录Sprite资源
/// </summary>
/// <param name="assetName"></param>
/// <returns></returns>
public static Sprite LoadSpriteAssets(string assetName)
{
return loadResources<Sprite>(assetName);
}
/// <summary>
/// 加载Resources目录GameObject资源
/// </summary>
/// <param name="assetName"></param>
/// <returns></returns>
public static GameObject LoadGameObjectAssets(string assetName)
{
return loadResources<GameObject>(assetName);
}
#region Bundle加载
/// <summary>
/// 加载Prefab资源, Bundle类型资源
/// </summary>
/// <param name="assetName"></param>
/// <returns></returns>
public static GameObject LoadPrefabBundle(string assetName)
{
GameObject go = null;
if (AppConst.AssetBundleMode)
go = AssetBundleManager.Instance.LoadPrefab(assetName);
#if UNITY_EDITOR
else
go = AssetDatabase.LoadAssetAtPath<GameObject>(string.Format("{0}{1}.prefab", RuntimeAssetsRoot, assetName));
#endif
return go;
}
/// <summary>
/// 加载Prefab资源, Bundle类型资源
/// </summary>
/// <param name="assetName"></param>
/// <returns></returns>
// public static GameObject LoadCachePrefabBundle(CachePoolAsync cachePool, string assetName)
// {
// string prefabName = assetName;
// string[] tempArr = assetName.Split('/');
// if (tempArr.Length > 0)
// prefabName = tempArr[tempArr.Length - 1];
// GameObject prefab = cachePool.GetCachePrefab(assetName);
// if (prefab != null)
// {
// return prefab;
// }
// else return LoadPrefabBundle(assetName);
// }
/// <summary>
/// 加载二进制数据, Bundle类型资源
/// </summary>
/// <param name="assetName"></param>
/// <returns></returns>
public static byte[] LoadBytesBundle(string assetName)
{
if (AppConst.AssetBundleMode)
return AssetBundleManager.Instance.LoadBytes(assetName);
#if UNITY_EDITOR
string extension = Path.GetExtension(assetName);
if (!string.IsNullOrEmpty(extension))
assetName = assetName.Replace(extension, "");
TextAsset textAss = AssetDatabase.LoadAssetAtPath<TextAsset>(string.Format("{0}{1}.bytes", RuntimeAssetsRoot, assetName));
return textAss.bytes;
#endif
return null;
}
/// <summary>
/// 加载贴图, Bundle类型资源
/// </summary>
/// <param name="assetPath">相对路径(带后缀)</param>
/// <returns></returns>
public static Texture LoadTextureBundle(GameObject owner, string assetPath)
{
if (AppConst.AssetBundleMode)
return AssetBundleManager.Instance.LoadTexture(owner, assetPath);
#if UNITY_EDITOR
string fullPath = string.Concat(RuntimeAssetsRoot, assetPath);
if (!File.Exists(fullPath))
{
Debug.LogError(string.Format("无法找到指定的图片资源! 路径:{0}", assetPath));
return null;
}
Texture textureAss = AssetDatabase.LoadAssetAtPath<Texture>(fullPath);
return textureAss;
#endif
return null;
}
/// <summary>
/// 加载Scriptable类型的.asset文件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="assetName"></param>
/// <returns></returns>
[NoToLua]
public static T LoadAssetBundle<T>(string assetName) where T : ScriptableObject
{
if (AppConst.AssetBundleMode)
return AssetBundleManager.Instance.LoadAssets<T>(assetName);
#if UNITY_EDITOR
string extension = Path.GetExtension(assetName);
if (!string.IsNullOrEmpty(extension))
assetName = assetName.Replace(extension, "");
T obj = AssetDatabase.LoadAssetAtPath<T>(string.Concat(RuntimeAssetsRoot ,assetName , ".asset"));
return obj;
#endif
return null;
}
/// <summary>
/// 从Atlas集合中加载Sprite对象
/// </summary>
/// <param name="spriteName">精灵图片名称</param>
/// <param name="atlasName">图集名称:Atlas/common/common-0</param>
/// <returns></returns>
public static Sprite LoadSpriteFromAtlasBundle(GameObject owener, string spriteName, string atlasName)
{
if (AppConst.AssetBundleMode)
return AssetBundleManager.Instance.LoadSprite(owener, spriteName, atlasName);
#if UNITY_EDITOR
using (zstring.Block())
{
if (atlasName.Contains("-"))
Debug.LogErrorFormat("atlas name contains \'-\', please check your code: [sprite]{0}, [atlas]{1}", spriteName, atlasName);
zstring dir = Path.GetDirectoryName(atlasName);
zstring extension = Path.GetExtension(spriteName);
if (!zstring.IsNullOrEmpty(extension))
spriteName = spriteName.Replace(extension, "");
UIAtlasCache atlas = null;
if (!atlasMap.TryGetValue(dir, out atlas))
{
zstring rootDir = RuntimeAssetsRoot + dir;
string[] textureGuids = AssetDatabase.FindAssets("t:Texture", new string[] { rootDir });
List<Sprite> sprites = new List<Sprite>();
for (int i = 0; i < textureGuids.Length; i++)
{
zstring relativePath = AssetDatabase.GUIDToAssetPath(textureGuids[i]);
zstring childDir = Path.GetDirectoryName(relativePath);
if (!childDir.Equals(rootDir)) continue; //只遍历顶层目录
var assets = AssetDatabase.LoadAllAssetsAtPath(relativePath);
foreach (var asset in assets)
{
if (asset is Sprite)
sprites.Add(asset as Sprite);
}
}
atlas = new UIAtlasCache(sprites.ToArray());
atlasMap[dir] = atlas;
}
return atlas.GetSprite(spriteName);
}
#endif
return null;
}
#endregion
#endregion
#region -------------------加载音频数据-------------------
public static IPromise<AudioClip> LoadAudioClipBundleAsync(GameObject owner, string name, string extension)
{
if (AppConst.AssetBundleMode)
{
return AssetBundleManager.Instance.LoadAudioClipBundleAsync(owner, name, extension);
}
AudioClip clip = null;
#if UNITY_EDITOR
string path = string.Format("{0}{1}.{2}",RuntimeAssetsRoot, name, extension);
clip = AssetDatabase.LoadAssetAtPath<AudioClip>(path);
#endif
return Promise<AudioClip>.Resolved(clip);
}
#endregion
}
}<file_sep>/Assets/GameScript/Manager/TestLuaManager.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using System;
using UnityEngine;
using System.Collections;
using System.IO;
using LuaFramework;
using LuaInterface;
/// <summary>
/// 描述:用于测试Lua脚本
/// <para>创建时间:2016-08-04</para>
/// </summary>
public class TestLuaManager : MonoBehaviour
{
public string LuaPath;
public string Function;
private BaseLuaManager mLuaMgr;
private LuaFunction onGUIFunc;
private string tableName;
void Awake()
{
mLuaMgr = AppFacade.Instance.AddManager<BaseLuaManager>();
}
// Use this for initialization
void Start()
{
mLuaMgr.InitStart();
if (!string.IsNullOrEmpty(LuaPath))
{
if (!LuaPath.EndsWith(".lua")) LuaPath += ".lua";
mLuaMgr.DoFile(LuaPath);
tableName = Path.GetFileNameWithoutExtension(LuaPath);
mLuaMgr.LuaMachine[tableName + ".Test"] = this;
}
callFunction(tableName, "Awake");
onGUIFunc = getFunction(tableName, "OnGUI");
callFunction(tableName, "Start");
}
// Update is called once per frame
void Update()
{
}
void OnGUI()
{
if (!string.IsNullOrEmpty(Function) && GUILayout.Button("Call Function"))
{
mLuaMgr.CallFunction(Function);
}
if (onGUIFunc != null)
onGUIFunc.Call();
}
private void OnDestroy()
{
callFunction(tableName, "OnDestroy");
}
private LuaFunction getFunction(string tableName, string funcName)
{
LuaFunction func = mLuaMgr.GetFunction(tableName + "." + funcName);
if (func == null)
func = mLuaMgr.GetFunction(tableName + ":" + funcName);
return func;
}
private void callFunction(string tableName, string funcName)
{
LuaFunction func = getFunction(tableName, funcName);
if (func == null) return;
func.Call();
}
}
<file_sep>/Assets/GameScript/Lua/Util/TaskRunner/AsyncTask.lua
local AsyncTask = class("AsyncTask")
function AsyncTask:ctor( task )
self._task = task
end
function AsyncTask:current( )
return self
end
function AsyncTask:moveNext()
return self:execute()
end
function AsyncTask:execute()
self._task:execute()
while self._task.isDone == false do
coroutine.step()
end
end
function AsyncTask:reset( )
-- body
end
function AsyncTask:toString()
return self._task:toString()
end
return AsyncTask<file_sep>/Assets/GameScript/UISystem/UIPage.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using UnityEngine;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// 描述:UIPage基础抽象层
/// <para>创建时间:2016-08-08</para>
/// </summary>
public class UIPage
{
protected GameObject cacheGameObj;
protected Transform cacheTrans;
protected PageContext context;
private bool active = true;
/// <summary>
/// 返回列表
/// </summary>
public List<string> BackQueue = new List<string>();
protected UIPageRoot pageRoot;
protected LuaPageBehaviour luaBehaviour;
public GameObject gameObject
{
get { return this.cacheGameObj; }
}
#region -----------Page 生命周期-----------------
public UIPage(LuaPageBehaviour luaBehaviour , string pagePath)
{
pageRoot = UIPageRoot.Instance;
context = new PageContext();
this.luaBehaviour = luaBehaviour;
context.assetPath = pagePath;
context.pageName = Path.GetFileNameWithoutExtension(pagePath);
cacheGameObj = luaBehaviour.gameObject;
cacheTrans = cacheGameObj.transform;
}
/// <summary>
/// 每次显示时调用
/// </summary>
public void OnShow(object param)
{
Active = true;
this.luaBehaviour.OnShow(this, param);
Canvas canvas = cacheGameObj.GetComponent<Canvas>();
if (AttributePage.pageType != EPageType.Fixed)
canvas.sortingOrder = pageRoot.AddOrder(AttributePage.pageType);
else
canvas.sortingOrder = AttributePage.order;
}
public virtual void OnHide()
{
Active = false;
if (AttributePage.pageType != EPageType.Fixed)
pageRoot.SubOrder(AttributePage.pageType);
this.luaBehaviour.OnHide();
}
#endregion
public Transform CacheTrans
{
get { return cacheTrans; }
}
/// <summary>
/// 页面显示时配置属性
/// </summary>
public PageContext AttributePage
{
get { return context;}
}
/// <summary>
/// 是否激活当前页面
/// </summary>
public bool Active
{
get { return active && cacheGameObj.activeInHierarchy;}
set
{
active = value;
cacheGameObj.SetActive(active);
}
}
/// <summary>
/// 设置界面显示配置属性
/// </summary>
/// <param name="type">类型</param>
/// <param name="mode">显示模式</param>
/// <param name="collider">碰撞模式</param>
public void SetPage(EPageType type, EShowMode mode, ECollider collider)
{
context.pageType = type;
context.showMode = mode;
context.collider = collider;
}
/// <summary>
/// 设置固定界面的属性
/// </summary>
/// <param name="order"></param>
/// <param name="mode"></param>
/// <param name="collider"></param>
public void SetFixPage(int order, EShowMode mode, ECollider collider)
{
context = new PageContext();
context.pageType = EPageType.Fixed;
context.order = order;
context.showMode = mode;
context.collider = collider;
}
public string Name { get { return cacheGameObj.name; } }
}
<file_sep>/Assets/Editor/SceneManagerEditor/Strategy/AllInOneStrategy.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// 描述:多个文件打包成一个集合
/// <para>创建时间:2016-06-28</para>
/// </summary>
public class AllInOneStrategy : IStrategy {
public void BeginProcess(BuildConfig buildConfig)
{
string absolutionPath = Path.Combine(Application.dataPath, buildConfig.InputDir);
string[] findFile = buildConfig.FileSuffixs.Split('|');
List<string> files = new List<string>();
foreach (string fileSuffix in findFile)
{
string[] fileArr = Directory.GetFiles(absolutionPath, fileSuffix, buildConfig.OptionSerach);
files.AddRange(fileArr);
}
//为文件分配到指定Bundle
List<string> allBundleFile = new List<string>();
string bundleName = buildConfig.BundleName + "_" + buildConfig.AssetType;
foreach (string filePath in files)
{
string relativePath = filePath.Replace("\\", "/");
relativePath = relativePath.Replace(Application.dataPath, "Assets");
List<string> bundleFiles = AssetBuildEditor.Instance.AssignBundle(bundleName, relativePath , buildConfig.BundleName);
allBundleFile.AddRange(bundleFiles);
}
//如果存在PreBuild , 则有可能是公共目录资源,同时检查资源冗余
if (string.IsNullOrEmpty(buildConfig.PreBuild) || buildConfig.PreBuild == "None") return;
List<string> refAssets = AssetBuildEditor.Instance.GetBundleRefList(buildConfig.BundleName);
foreach (string asset in refAssets)
allBundleFile.Remove(asset);
//清理多余的资源
foreach (string asset in allBundleFile)
{
AssetBundleUtil.ClearBundle(asset);
}
}
public void EndProcess(BuildConfig buildConfig)
{
}
}
<file_sep>/Assets/GameScript/Lua/Net/Protocol/Notice.lua
--local NetREQ_ = NetREQ
NetProtoNotice = {}
NetProto.NetModule[20] = NetProtoNotice
NetProtoNotice.st = {
['NoticeVO'] = function(T)
if not(T:result()) then return end
T:vint64('endTime') --截至时间
T:vint64('id') --公告id
T:vint32('intervlTime') --间隔时间
T:vstring('message') --公告内容
T:vint32('priority') --优先级
T:vint64('startTime') --开始时间
T:vstring('title') --公告标题
T:vint32('type') --公告类型:1 聊天栏公告;2 跑马灯公告;3 活动公告;4 更新公告
end,
}
NetProtoNotice.send = {
['GetNotices'] = function(T)
if not(T:result()) then return end
end,
}
-- ***自动提示帮助***
NetProtoNotice.NoticeVO = {
['endTime'] = nil, --截至时间
['id'] = nil, --公告id
['intervlTime'] = nil, --间隔时间
['message'] = nil, --公告内容
['priority'] = nil, --优先级
['startTime'] = nil, --开始时间
['title'] = nil, --公告标题
['type'] = nil, --公告类型:1 聊天栏公告;2 跑马灯公告;3 活动公告;4 更新公告
}
local T = NetProto.st
-- ***请求处理***
--获取公告
NetProtoNotice.SendGetNotices = {
['new'] = NetProto.new,
['_MOD_'] = 20,
['_MED_'] = 1,
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoNotice.send.GetNotices, NetProto.st.array(NetProtoNotice.st.NoticeVO), fnRespond)
end,
}
-- ***推送处理***
NetProtoNotice.MesssagePush = {
[101] = {['msg']='msgPushAddToPlayers' ,['st'] = NetProtoNotice.st.NoticeVO}, --推送添加公告
[102] = {['msg']='msgPushDeleteToPlayers' ,['st'] = T.vint64}, --推送删除公告
[103] = {['msg']='msgPushUpdateToPlayers' ,['st'] = NetProtoNotice.st.NoticeVO}, --推送修改公告
}
DeclareInterface(NetProtoNotice, 'msgPushInterface')
function NetProtoNotice.listenMessagePush(listener)
ListenInterface(NetProtoNotice, 'msgPushInterface', listener)
end
function NetProtoNotice.removeMessagePush(listener)
RemoveInterface(NetProtoNotice, 'msgPushInterface', listener)
end
<file_sep>/Assets/GameScript/Lua/Util/TimeService.lua
--[[
Author: LiangZG
Desc : 服务器时间
]]
local TimeService = class("TimeService")
local m = TimeService
local orgintime = os.time({year=1970 , month=1 , day = 1 , hour = 8 , min = 0 , sec = 1})
function m:ctor()
self.serverTimeZoneDiff = 0
self.lastTimeval = 0
end
function m:adjustServerTime(time)
self.serverTime = time
self.localTime = os.time()
self.lastTimeval = os.time()
end
function m:setServerTimeZoneDiff(zoneDiffTime)
self.serverTimeZoneDiff = zoneDiffTime * 3600
end
--/** 获取服务器当前UTC时间 */
function m:getServerUtcTimeNow()
local nowTimeval = os.time()
local serverNowUtcTime = self.serverTime + os.difftime(nowTimeval,self.lastTimeval)
return serverNowUtcTime
end
--获得当前服务器时间,累加指定毫秒数后的时间
function m:addTimeNow(hour , min , sec)
return self:addTime(self:getServerUtcTimeNow() , hour , min , sec)
end
--获得一个累加的新time时间
function m:addTime(orginTime , hour , min , sec)
local curTime = os.date('*t' , orginTime)
curTime.hour = curTime.hour + hour
curTime.min = curTime.min + (min or 0)
curTime.sec = curTime.sec + (sec or 0)
return os.time(curTime)
end
--获得当前服务器时间,累加指定毫秒数后的时间
function m:addMillisecondNow(millisecond)
return self:addMillisecond(self:getServerUtcTimeNow() , millisecond)
end
--获得指定时间,累加指定毫秒数后的时间
function m:addMillisecond(orginTime , millisecond)
local sec = millisecond / 1000
local hour = Mathf.ToInt(sec / 3600)
local min = Mathf.ToInt((sec - hour * 3600) / 60)
sec = sec % 60
local curTime = os.date('*t' , orginTime)
curTime.hour = curTime.hour + hour
curTime.min = curTime.min + min
curTime.sec = curTime.sec + sec
return os.time(curTime)
end
--获取总的毫秒数,基于1970.1.1 0:0:0
function m:totalMillisecondNow()
local curTime = self:getServerUtcTimeNow()
return self:totalMillisecond(curTime)
end
--获取总的毫秒数,基于1970.1.1 0:0:0
function m:totalMillisecond(time)
return os.difftime(time , orgintime) * 1000
end
--获取相对于服务器当前时间的总秒数
function m:totalSecondServerNow( time )
return os.difftime(time , self:getServerUtcTimeNow())
end
--计算两个时间的时间差,startTime 和 endTime 单位为秒
function m:totalSeconds(startTime , endTime)
if startTime ~= "number" then
startTime = convert2num(startTime)
end
if endTime ~= "number" then
endTime = convert2num(endTime)
end
return os.difftime(endTime , startTime)
end
--/** 获取服务器当前时区时间 */
function m:getServerZoneTimeNow()
local t = self:getServerUtcTimeNow()
t = t + self.serverTimeZoneDiff
return t
end
--/** 获取服务器当前UTC日期 */
function m:getServerUtcDateNow()
local t = self:getServerUtcTimeNow()
return os.date('*t',t)
end
--/** 获取服务器当前时区日期 */
function m:getServerZoneDateNow()
local t = self:getServerUtcTimeNow()
t = t + self.serverTimeZoneDiff
return os.date('*t',t)
end
--/**转换服务器时间戳 */
function m:changeTimeStampToOs(time)
local tm = os.date('*t',time)
return tm
end
--/**转换时间戳 */
function m:changeTimeStampToStr(time)
local tm = os.date('*t',time)
local yearStr = ''
local dayStr = ''
local monthStr = ''
local hourStr = ''
local minStr = ''
yearStr = tostring(tm.year)
monthStr = string.format("%2d" , tm.month)
dayStr = string.format("%2d" , tm.day)
hourStr = string.format("%2d" , tm.hour)
minStr = string.format("%2d" , tm.min)
secStr = string.format("%2d" , tm.sec)
return yearStr.."."..monthStr.."."..dayStr.." "..hourStr..":"..minStr
end
--/**转换时间戳 */
function m:timeToStrOnly()
local tm = os.date("*t", os.time());
local yearStr = ''
local dayStr = ''
local monthStr = ''
local hourStr = ''
local minStr = ''
local secStr = ''
yearStr = tostring(tm.year)
monthStr = string.format("%2d" , tm.month)
dayStr = string.format("%2d" , tm.day)
hourStr = string.format("%2d" , tm.hour)
minStr = string.format("%2d" , tm.min)
secStr = string.format("%2d" , tm.sec)
return yearStr..monthStr..dayStr..hourStr..minStr..secStr
end
--格式化总秒数为时、分、钞的值
function m:formatHMS(seconds)
local hour = Mathf.ToInt(seconds / 3600)
local min = Mathf.ToInt((seconds % 3600) / 60)
local sec = seconds % 60
return hour , min , sec
end
TimeService.ins = TimeService.new()
return TimeService<file_sep>/Assets/Editor/SceneManagerEditor/AssetToolMenus.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using System;
using UnityEngine;
using System.Collections;
using UnityEditor;
/// <summary>
/// 描述:资源工具集的菜单目录
/// <para>创建时间:2016-06-30</para>
/// </summary>
public class AssetToolsMenu {
[MenuItem("AssetTools/Asset Build Editor")]
public static void ShowEditor()
{
AssetBuildEditor abEditor = EditorWindow.GetWindow<AssetBuildEditor>();
abEditor.Initialize();
abEditor.Show();
}
[MenuItem("AssetTools/Copy Assets To Install")]
public static void CopyInstallAsset()
{
AssetBuildEditor.CopyFileTo(Application.streamingAssetsPath);
AssetDatabase.Refresh();
EditorUtility.DisplayDialog("提示", "文件已拷贝完成", "确定");
}
[MenuItem("AssetTools/Copy Assets To RunBin")]
public static void CopyRunBinAsset()
{
AssetBuildEditor.CopyFileTo(AppPathUtils.PersistentDataRootPath);
EditorUtility.DisplayDialog("提示", "文件已拷贝完成", "确定");
}
[MenuItem("AssetTools/Lightmap/Gen Lightmap Prefab")]
public static void GenLightmap()
{
LightMapEditor.GenLightmap();
}
[MenuItem("AssetTools/Lightmap/Update Scene Prefab Lightmaps")]
public static void UpdateLightmaps()
{
LightMapEditor.UpdateLightmaps();
}
[MenuItem("AssetTools/Lightmap/Gen Lightmap Prefab All")]
public static void GenLightmapPrefabAll()
{
LightMapEditor.GenLightmapPrefabAll();
}
}
<file_sep>/Assets/Tests/Scripts/TestAssetLoader.cs
using System.Collections;
using System.Collections.Generic;
using GEX.Resource;
using UnityEngine;
public class TestAssetLoader : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnGUI()
{
GUILayout.Label("Parllerl Or Serial Loader:");
if (GUILayout.Button("SerialLoader"))
{
TestSerialLoader();
}
if (GUILayout.Button("ParllerlLoader"))
{
TestParallelLoader();
}
}
private void TestSerialLoader()
{
SerialLoader loader = new SerialLoader();
loader.AddLoader("Models/GO1.prefab").OnFinish = InstanceGameObject;
loader.AddLoader(new LoadDelayAsync(0.5f)).OnFinish = PrintTime;
loader.AddLoader("Models/GO2.prefab").OnFinish = InstanceGameObject;
loader.AddLoader(new LoadDelayAsync(1.0f)).OnFinish = PrintTime;
loader.AddLoader("Models/GO3.prefab").OnFinish = InstanceGameObject;
loader.AddLoader(new LoadDelayAsync(1.5f)).OnFinish = PrintTime;
loader.AddLoader("Models/GO4.prefab").OnFinish = InstanceGameObject;
this.StartCoroutine(loader);
}
private void TestParallelLoader()
{
ParallelLoader loader = new ParallelLoader();
loader.AddLoader("Models/GO1.prefab").OnFinish = InstanceGameObject;
loader.AddLoader(new LoadDelayAsync(0.5f)).OnFinish = PrintTime;
loader.AddLoader("Models/GO2.prefab").OnFinish = InstanceGameObject;
loader.AddLoader(new LoadDelayAsync(1.0f)).OnFinish = PrintTime;
loader.AddLoader("Models/GO3.prefab").OnFinish = InstanceGameObject;
loader.AddLoader(new LoadDelayAsync(1.5f)).OnFinish = PrintTime;
loader.AddLoader("Models/GO4.prefab").OnFinish = InstanceGameObject;
this.StartCoroutine(loader);
}
private void InstanceGameObject(LoadOperation loadOpt)
{
GameObject.Instantiate(loadOpt.GetAsset<GameObject>());
}
private void PrintTime(LoadOperation loadOpt)
{
Debug.Log("Time:" + Time.realtimeSinceStartup);
}
}
<file_sep>/Assets/GameScript/Lua/Net/Protocol/User.lua
--local NetREQ_ = NetREQ
NetProtoUser = {}
NetProto.NetModule[1] = NetProtoUser
NetProtoUser.st = {
['PlayerInfoVO'] = function(T)
if not(T:result()) then return end
T:vint32('heroId') --魔王Id
T:vint64('id') --角色ID
T:vint32('level') --角色等级
T:vstring('name') --角色名字
T:vint32('qualityIdentity') --魔王升品标识
T:vint32('star') --魔王星级
end,
['AccountVO'] = function(T)
if not(T:result()) then return end
T:vstring('accountName') --账号名
T:array('players', NetProtoUser.st.PlayerInfoVO) --角色列表
T:vint32('result') --返回结果
T:vint32('userType') --用户类型:1游客;2QQ;3微信;4爱苹果;5快用苹果助手;6PP助手;7同步推;8初见;9爱思
T:vstring('validKey') --验证密匙
end,
['CreatePlayerVO'] = function(T)
if not(T:result()) then return end
T:array('players', NetProtoUser.st.PlayerInfoVO) --角色列表
T:vint32('result') --返回结果
end,
['BindPlayerVO'] = function(T)
if not(T:result()) then return end
T:vint64('bindTime') --绑定时间
T:vint32('result') --返回结果
T:vint32('timeZone') --时区
end,
['IkIvVO'] = function(T)
if not(T:result()) then return end
T:vint32('key') --整形键名
T:vint32('value') --整形键值
end,
['IkLvVO'] = function(T)
if not(T:result()) then return end
T:vint32('key') --整形键名
T:vint64('value') --长整形键值
end,
['IkSvVO'] = function(T)
if not(T:result()) then return end
T:vint32('key') --整形键名
T:vstring('value') --字符串型键值
end,
['UnitId'] = function(T)
if not(T:result()) then return end
T:vint64('id') --id
T:vint32('unitType') --unitType
end,
['AttributesVO'] = function(T)
if not(T:result()) then return end
T:array('ikIvVOs', NetProtoUser.st.IkIvVO) --整形值属性VO数组
T:array('ikLvVOs', NetProtoUser.st.IkLvVO) --长整形值属性VO数组
T:array('ikSvVOs', NetProtoUser.st.IkSvVO) --字符串属性VO数组
T:struct('unitId', NetProtoUser.st.UnitId) --单位ID
end,
}
NetProtoUser.send = {
['HeartBeat'] = function(T)
if not(T:result()) then return end
end,
['VisitorLogin'] = function(T)
if not(T:result()) then return end
T:vstring('userName') --用户名
T:vstring('password') --密码
end,
['Create'] = function(T)
if not(T:result()) then return end
T:vstring('userName') --用户名
T:vstring('validKey') --验证码
T:vint32('heroId') --魔王id
T:vstring('name') --角色名
end,
['Select'] = function(T)
if not(T:result()) then return end
T:vstring('username') --用户名
T:vstring('validKey') --验证码
T:vint64('selectPlayerId') --所选的角色id
end,
['Reconnect'] = function(T)
if not(T:result()) then return end
T:vstring('username') --用户名
T:vstring('validKey') --验证码
T:vint64('selectPlayerId') --所选的角色id
T:vint64('firstBindTime') --首次绑定时间
end,
['LoginForOurpalm'] = function(T)
if not(T:result()) then return end
T:vstring('tokenId') --tokenId
T:vstring('channel') --channel
end,
}
-- ***自动提示帮助***
NetProtoUser.PlayerInfoVO = {
['heroId'] = nil, --魔王Id
['id'] = nil, --角色ID
['level'] = nil, --角色等级
['name'] = nil, --角色名字
['qualityIdentity'] = nil, --魔王升品标识
['star'] = nil, --魔王星级
}
NetProtoUser.AccountVO = {
['accountName'] = nil, --账号名
['players'] = nil, --角色列表
['result'] = nil, --返回结果
['userType'] = nil, --用户类型:1游客;2QQ;3微信;4爱苹果;5快用苹果助手;6PP助手;7同步推;8初见;9爱思
['validKey'] = nil, --验证密匙
}
NetProtoUser.CreatePlayerVO = {
['players'] = nil, --角色列表
['result'] = nil, --返回结果
}
NetProtoUser.BindPlayerVO = {
['bindTime'] = nil, --绑定时间
['result'] = nil, --返回结果
['timeZone'] = nil, --时区
}
NetProtoUser.IkIvVO = {
['key'] = nil, --整形键名
['value'] = nil, --整形键值
}
NetProtoUser.IkLvVO = {
['key'] = nil, --整形键名
['value'] = nil, --长整形键值
}
NetProtoUser.IkSvVO = {
['key'] = nil, --整形键名
['value'] = nil, --字符串型键值
}
NetProtoUser.UnitId = {
['id'] = nil, --id
['unitType'] = nil, --unitType
}
NetProtoUser.AttributesVO = {
['ikIvVOs'] = nil, --整形值属性VO数组
['ikLvVOs'] = nil, --长整形值属性VO数组
['ikSvVOs'] = nil, --字符串属性VO数组
['unitId'] = nil, --单位ID
}
local T = NetProto.st
-- ***请求处理***
--心跳 --返回:当前时间戳
NetProtoUser.SendHeartBeat = {
['new'] = NetProto.new,
['_MOD_'] = 1,
['_MED_'] = 0,
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoUser.send.HeartBeat, T.vint64, fnRespond)
end,
}
--游客登陆
NetProtoUser.SendVisitorLogin = {
['new'] = NetProto.new,
['_MOD_'] = 1,
['_MED_'] = 1,
['userName'] = nil, --用户名
['password'] = nil, --密码
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoUser.send.VisitorLogin, NetProtoUser.st.AccountVO, fnRespond)
end,
}
--创建角色
NetProtoUser.SendCreate = {
['new'] = NetProto.new,
['_MOD_'] = 1,
['_MED_'] = 2,
['userName'] = nil, --用户名
['validKey'] = nil, --验证码
['heroId'] = nil, --魔王id
['name'] = nil, --角色名
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoUser.send.Create, NetProtoUser.st.CreatePlayerVO, fnRespond)
end,
}
--选择角色登陆 --返回:绑定信息
NetProtoUser.SendSelect = {
['new'] = NetProto.new,
['_MOD_'] = 1,
['_MED_'] = 3,
['username'] = nil, --用户名
['validKey'] = nil, --验证码
['selectPlayerId'] = nil, --所选的角色id
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoUser.send.Select, NetProtoUser.st.BindPlayerVO, fnRespond)
end,
}
--断线重连 --返回:绑定信息
NetProtoUser.SendReconnect = {
['new'] = NetProto.new,
['_MOD_'] = 1,
['_MED_'] = 15,
['username'] = nil, --用户名
['validKey'] = nil, --验证码
['selectPlayerId'] = nil, --所选的角色id
['firstBindTime'] = nil, --首次绑定时间
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoUser.send.Reconnect, NetProtoUser.st.BindPlayerVO, fnRespond)
end,
}
--掌趣登录
NetProtoUser.SendLoginForOurpalm = {
['new'] = NetProto.new,
['_MOD_'] = 1,
['_MED_'] = 35,
['tokenId'] = nil, --tokenId
['channel'] = nil, --channel
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoUser.send.LoginForOurpalm, NetProtoUser.st.AccountVO, fnRespond)
end,
}
-- ***推送处理***
NetProtoUser.MesssagePush = {
[100] = {['msg']='msgPushPlayerKickoff' ,['st'] = T.vint32}, --推送玩家下线,0:重登,1:封禁,2:登录超时,3:服务器维护
[101] = {['msg']='msgPushPlayerAttribute' ,['st'] = NetProtoUser.st.AttributesVO}, --推送角色的属性
[103] = {['msg']='msgPushVisitor' ,['st'] = T.vstring}, --推送访问者的名字
[104] = {['msg']='msgPushPackageFull' ,['st'] = T.vint32}, --推送背包已满,清理后从邮件领取物品信息
}
DeclareInterface(NetProtoUser, 'msgPushInterface')
function NetProtoUser.listenMessagePush(listener)
ListenInterface(NetProtoUser, 'msgPushInterface', listener)
end
function NetProtoUser.removeMessagePush(listener)
RemoveInterface(NetProtoUser, 'msgPushInterface', listener)
end
<file_sep>/Assets/GameScript/Lua/Net/Protocol/Activity.lua
--local NetREQ_ = NetREQ
NetProtoActivity = {}
NetProto.NetModule[29] = NetProtoActivity
NetProtoActivity.st = {
['ActivityVO'] = function(T)
if not(T:result()) then return end
T:vstring('content') --活动内容
T:vstring('des') --描述
T:vint64('endTime') --结束时间
T:vint64('id') --活动id
T:vstring('name') --活动名称
T:vstring('param') --活动参数,有集体数据时才不为空
T:vint32('resultCode') --结果码
T:vint64('startTime') --开始时间
T:vstring('subDes') --子描述
T:vstring('title') --活动标签
T:vint32('type') --活动类型
T:vstring('userData') --用户数据
end,
['PlayerActivityDataVO'] = function(T)
if not(T:result()) then return end
T:vstring('param') --活动参数,有集体数据时才不为空
T:vint32('resultCode') --结果码
T:vstring('userData') --用户数据
end,
}
NetProtoActivity.send = {
['GetNowActivityIds'] = function(T)
if not(T:result()) then return end
end,
['GetNowActivities'] = function(T)
if not(T:result()) then return end
end,
['GetActivity'] = function(T)
if not(T:result()) then return end
T:vint64('activityId') --活动ID
end,
['GetUserActivityData'] = function(T)
if not(T:result()) then return end
T:vint64('activityId') --活动ID
end,
['ReceiveRewards'] = function(T)
if not(T:result()) then return end
T:vint64('activityId') --活动ID
T:vint32('subId') --子类ID
end,
}
-- ***自动提示帮助***
NetProtoActivity.ActivityVO = {
['content'] = nil, --活动内容
['des'] = nil, --描述
['endTime'] = nil, --结束时间
['id'] = nil, --活动id
['name'] = nil, --活动名称
['param'] = nil, --活动参数,有集体数据时才不为空
['resultCode'] = nil, --结果码
['startTime'] = nil, --开始时间
['subDes'] = nil, --子描述
['title'] = nil, --活动标签
['type'] = nil, --活动类型
['userData'] = nil, --用户数据
}
NetProtoActivity.PlayerActivityDataVO = {
['param'] = nil, --活动参数,有集体数据时才不为空
['resultCode'] = nil, --结果码
['userData'] = nil, --用户数据
}
local T = NetProto.st
-- ***请求处理***
--获取当前活动的id
NetProtoActivity.SendGetNowActivityIds = {
['new'] = NetProto.new,
['_MOD_'] = 29,
['_MED_'] = 1,
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoActivity.send.GetNowActivityIds, NetProto.st.array(T.vint64), fnRespond)
end,
}
--获取当前活动
NetProtoActivity.SendGetNowActivities = {
['new'] = NetProto.new,
['_MOD_'] = 29,
['_MED_'] = 2,
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoActivity.send.GetNowActivities, NetProtoActivity.st.GetNowActivitiesList, fnRespond)
end,
}
--获取活动
NetProtoActivity.SendGetActivity = {
['new'] = NetProto.new,
['_MOD_'] = 29,
['_MED_'] = 3,
['activityId'] = nil, --活动ID
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoActivity.send.GetActivity, NetProtoActivity.st.ActivityVO, fnRespond)
end,
}
--获取用户活动数据
NetProtoActivity.SendGetUserActivityData = {
['new'] = NetProto.new,
['_MOD_'] = 29,
['_MED_'] = 4,
['activityId'] = nil, --活动ID
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoActivity.send.GetUserActivityData, NetProtoActivity.st.PlayerActivityDataVO, fnRespond)
end,
}
--领取奖励
NetProtoActivity.SendReceiveRewards = {
['new'] = NetProto.new,
['_MOD_'] = 29,
['_MED_'] = 5,
['activityId'] = nil, --活动ID
['subId'] = nil, --子类ID
['send'] = function (self, fnRespond)
GameNet:sendRequest(self, NetProtoActivity.send.ReceiveRewards, NetProtoActivity.st.PlayerActivityDataVO, fnRespond)
end,
}
-- ***推送处理***
NetProtoActivity.MesssagePush = {
}
DeclareInterface(NetProtoActivity, 'msgPushInterface')
function NetProtoActivity.listenMessagePush(listener)
ListenInterface(NetProtoActivity, 'msgPushInterface', listener)
end
function NetProtoActivity.removeMessagePush(listener)
RemoveInterface(NetProtoActivity, 'msgPushInterface', listener)
end
<file_sep>/Assets/GameScript/Lua/UI/MainPanel.lua
-- @Author: <EMAIL>
-- @Last Modified time: 2017-01-01 00:00:00
-- @Desc:主界面逻辑处理
MainPanel = {}
local this = MainPanel
local curUiId = 0
--- 由LuaBehaviour自动调用
function MainPanel.Awake(gameObject)
this.widgets = {
{field="root", path ="", src=LuaCanvas},
{field="BtnRank",path="BtnRank",src=LuaButton, onClick = this._onClickRank },
{field="BtnSkill",path="BtnSkill",src=LuaButton, onClick = this._onClickSkill },
{field="BtnCombat",path="BtnCombat",src=LuaButton, onClick = this._onClickCombat },
{field="BtnChat",path="BtnChat.BtnChat",src=LuaButton, onClick = this._onClickChat },
}
LuaUIHelper.bind(this.gameObject , MainPanel )
end
function MainPanel.Show( func )
UIManager:Show("Prefab/GUI/MainPanel", nil)
this.closeFunc = func
end
--- 由LuaBehaviour自动调用
function MainPanel.OnInit(basePage)
this.basePage = basePage
this.basePage:SetPage(EPageType.Normal , EShowMode.HideOther , ECollider.None)
--每次显示自动修改UI中所有Panel的depth
--LuaUIHelper.addUIDepth(this.gameObject , MainPanel)
this._registeEvents(this.event)
end
-- 注册界面事件监听
function MainPanel._registeEvents(event)
--ps:事件列表每次关闭时会自动清空,所以显示时每次都需要注册
event:AddListener("gotoRank" , this.dispatchRankResultEvent)
event:AddListener("chatmsg" , this.dispatchChatMsgEvent)
end
--捕获gotoRank事件
function MainPanel.dispatchRankResultEvent()
print("Yes , I receive this msg")
EventManager.SendEvent("updateTopToolbar" , "hehe , Global Event")
end
--捕获聊天事件
function MainPanel.dispatchChatMsgEvent(msg)
print("msg :" .. msg)
end
function MainPanel._onClickRank()
print(" goto rank UI ")
EventManager.SendEvent("gotoRank")
end
function MainPanel._coClickSkill()
SkillPanel.Show()
end
function MainPanel._onClickCombat()
BattlePanel.Show()
end
function MainPanel.gotoChat()
print(" goto chat UI ")
EventManager.SendEvent("chatmsg" , "oh~ have a msg !")
end
--- 关闭界面
function MainPanel._onClickClose( )
UIManager.Hide(this.basePage.assetPath)
if this.closeFunc ~= nil then
this.closeFunc()
this.closeFunc = nil
end
end
--- 由LuaBehaviour自动调用
function MainPanel.OnClose()
--LuaUIHelper.removeUIDepth(this.gameObject) --还原全局深度
end
--- 由LuaBehaviour自动调用--
function MainPanel.OnDestroy()
this.gameObject = nil
this.transform = nil
this.widgets = nil
end<file_sep>/Assets/GameScript/Lua/Engines/init.lua
--[[
Lua基础引擎模块初始化
]]
local ENIGINE_MODE = ...
EventLib = import(".eventlib")
Event = import(".events")
--require "Text.string"
--stringBuffer = require "Text.StringBuffer"<file_sep>/Assets/Editor/ToLuaEditor/GameBindType.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using System;
using UnityEngine;
using System.Collections;
using NetCore;
using LuaFramework;
/// <summary>
/// 描述:具体游戏类型绑定
/// <para>创建时间:2016-08-03</para>
/// </summary>
public sealed class GameBindType
{
/// <summary>
/// 游戏功能脚本Wrap绑定块
/// </summary>
public static ToLuaMenu.BindType[] GameScripteBinds = new[]
{
//网络
_GT<ByteArray>(),
_GT<ByteArrayQueue>(),
_GT<ByteStream>(),
_GT<Net>(),
_GT<PackProtocol>(),
_GT<VarintStream>(),
//工具
_GT<Util>(),
};
/// <summary>
/// 游戏引擎脚本Wrap绑定块
/// </summary>
public static ToLuaMenu.BindType[] GameEngineBinds = new[]
{
_GT<AssetLoader>(),
_GT<LuaAssetLoader>(),
_GT<UIPage>(),
_GT<EPageType>(),
_GT<EShowMode>(),
_GT<ECollider>(),
_GT<UIManager>(),
};
/// <summary>
/// UnityEngine脚本绑定块
/// </summary>
public static ToLuaMenu.BindType[] UnityEngineBinds = new []
{
#if UNITY_EDITOR
_GT<GUILayout>(),
#endif
_GT<UnityEngine.UI.Text>(),
_GT<RectTransform>(),
};
public static ToLuaMenu.BindType _GT<T>()
{
return new ToLuaMenu.BindType(typeof(T));
}
public static ToLuaMenu.BindType _GT(Type type)
{
return new ToLuaMenu.BindType(type);
}
}
<file_sep>/Assets/GEngineScript/Core/ResourceSystem/Base/LoadSceneAsync.cs
using System.Collections;
using System.IO;
using LuaFramework;
using LuaInterface;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace GEX.Resource
{
/// <summary>
/// 场景资源加载器
/// </summary>
public class LoadSceneAsync : LoadOperation
{
private AsyncOperation loading;
private LoadSceneMode loadSceneMode;
private AssetBundleCreateRequest abcr;
public AsyncOperation AsyncSceneLoader
{
get { return loading; }
}
public LoadSceneAsync(string path)
{
this.assetPath = path;
loadSceneMode = LoadSceneMode.Single;
}
public LoadSceneAsync(string path, LoadSceneMode loadMode)
{
this.assetPath = path;
this.loadSceneMode = loadMode;
}
public override void OnLoad()
{
loading = UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(this.assetPath, loadSceneMode);
loading.allowSceneActivation = false;
}
private IEnumerator loadAsync()
{
if (AppConst.AssetBundleMode)
{
string bundleName = string.Empty;
AssetBundleManager bundleMgr = AssetBundleManager.Instance;
if (!bundleMgr.assetbundleMap.TryGetValue(assetPath.ToLower(), out bundleName))
{
bundleName = string.Format("scenes/{0}.ab", assetPath);
}
yield return bundleMgr.LoadSceneDependency(bundleName);
string scenePath = string.Format("{0}{1}", Util.DataPath, bundleName);
if (File.Exists(scenePath))
{
abcr = AssetBundle.LoadFromFileAsync(scenePath);
yield return abcr;
}
}
OnLoad();
yield return null;
}
public override bool MoveNext()
{
if (!hasLoaded)
{
hasLoaded = true;
AppInter.Instance.StartCoroutine(loadAsync());
}
if (loading != null)
{
progress = loading.progress;
if (progress >= 0.9f)
{
loading.allowSceneActivation = true;
}
}
bool result = IsDone();
if (result) this.onFinishEvent();
return !result;
}
public override bool IsDone()
{
if (loading != null && loading.isDone)
return true;
return false;
}
public override void Reset()
{
base.Reset();
if (AppConst.AssetBundleMode)
{
AssetBundleManager.Instance.UnloadSceneDependency();
if (abcr != null)
{
abcr.assetBundle.Unload(false);
abcr = null;
}
}
}
[NoToLua]
public override T GetAsset<T>()
{
return default(T);
}
}
}<file_sep>/Assets/GEngineScript/Core/NetworkSystem/ConnectObserver.cs
using System;
using UnityEngine;
using System.Collections;
namespace GEX.Network
{
/// <summary>
/// 网络连接状态观察广播处理
/// </summary>
public class ConnectObservice
{
public void RegistListener(ushort eventId , Action<ByteArray> listener)
{
}
public void NotifyEvent(ushort eventID , ByteArray msg)
{
}
}
}
<file_sep>/Assets/GEngineScript/Core/Asset/LuaAssetLoader.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using System;
using UnityEngine;
using System.Collections;
using LuaFramework;
using LuaInterface;
/// <summary>
/// 描述:Lua层资源加载
/// <para>创建时间:2016-08-04</para>
/// </summary>
public sealed class LuaAssetLoader{
/// <summary>
/// 通过指定资源名加载GameObject资源
/// </summary>
/// <param name="resName">资源名称</param>
/// <param name="luaCallback">加载实例完成后的回调</param>
public static void LoadGameObjectByName(string resName, AssetLoader.EAssetType assetType, LuaFunction luaCallback)
{
Action<GameObject> callback = null;
if(luaCallback != null)
callback = (Action<GameObject>)DelegateFactory.CreateDelegate(typeof (Action<GameObject>), luaCallback);
AssetLoader.LoadGameObjectByName(resName , assetType , callback);
}
public static void LoadGameObjectByName(string resName, AssetLoader.EAssetType assetType, string luaFuncName)
{
BaseLuaManager mgr = AppFacade.Instance.GetManager<BaseLuaManager>();
LuaFunction luaCallback = mgr.GetFunction(luaFuncName);
LoadGameObjectByName(resName , assetType , luaCallback);
}
/// <summary>
/// 通过指定的UI资源名加载实例GameObject对象
/// </summary>
/// <param name="resName">UI资源名</param>
/// <param name="luaCallback">加载实例完成后的回调</param>
public static void LoadUI(string resName, LuaFunction luaCallback)
{
LoadGameObjectByName(resName, AssetLoader.EAssetType.UI, luaCallback);
}
public static void LoadUI(string resName, string luaFuncName)
{
LoadGameObjectByName(resName, AssetLoader.EAssetType.UI, luaFuncName);
}
/// <summary>
/// 通过指定的特效资源名加载实例GameObject对象
/// </summary>
/// <param name="resName">特效资源名</param>
/// <param name="callback">加载实例完成后的回调</param>
public static void LoadEffect(string resName, LuaFunction callback)
{
LoadGameObjectByName(resName, AssetLoader.EAssetType.Effect, callback);
}
public static void LoadEffect(string resName, string luaFuncName)
{
LoadGameObjectByName(resName, AssetLoader.EAssetType.Effect, luaFuncName);
}
/// <summary>
/// 通过指定的模型资源名加载实例GameObject对象
/// </summary>
/// <param name="resName">模型资源名</param>
/// <param name="callback">加载实例完成后的回调</param>
public static void LoadModel(string resName, LuaFunction callback)
{
LoadGameObjectByName(resName, AssetLoader.EAssetType.Model, callback);
}
public static void LoadModel(string resName, string luaFuncName)
{
LoadGameObjectByName(resName, AssetLoader.EAssetType.Model, luaFuncName);
}
/// <summary>
/// 加载一个普通的GameObject对象
/// </summary>
/// <param name="resName">模型资源名</param>
/// <param name="callback">加载实例完成后的回调</param>
public static void LoadGameObject(string resName, LuaFunction callback)
{
LoadGameObjectByName(resName, AssetLoader.EAssetType.GameObject, callback);
}
public static void LoadGameObject(string resName, string luaFuncName)
{
LoadGameObjectByName(resName, AssetLoader.EAssetType.GameObject, luaFuncName);
}
/// <summary>
/// 执行资源预加载
/// </summary>
/// <param name="luaCallback"></param>
public static void OnInitPreload(LuaFunction luaCallback)
{
Action callback = null;
if (luaCallback != null)
callback = (Action)DelegateFactory.CreateDelegate(typeof(Action), luaCallback);
AppInter.StartCoroutine(AssetLoader.Instance.InitPreLoad(callback));
}
}
<file_sep>/Assets/GameScript/Lua/Util/Task.lua
--[[
Author: LiangZG
Desc : 任务
]]
local Task = class("Task")
local m = Task
function m:ctor( )
end
function m:start()
-- body
end
function m:exceute( )
end
function m:destroy()
-- body
end
return Task
<file_sep>/Assets/Libs/LuaDataBind/Foundation/Command.cs
using LuaInterface;
using UnityEngine;
namespace LuaDataBind
{
public abstract class Command : MonoBehaviour
{
public string Func;
[HideInInspector]
public LuaContext Context;
protected virtual void Awake()
{
if(Context == null)
Context = this.GetComponentInParent<LuaContext>();
}
protected virtual void OnDestroy()
{
}
protected abstract void invokeCommand();
}
}<file_sep>/Assets/GameScript/Lua/Util/Scheduler.lua
--[[
调度结点信息结构体
]]
local SchedulerNode = class("SchedulerNode")
function SchedulerNode:ctor()
self.delay = 0
self.interval = 0
self.listener = nil
self.once = false
self.elapseTime = 0
end
local UpdateBeat = UpdateBeat
local ilist = ilist
--[[--
全局计时器、计划任务
该模块在框架初始化时不会自动载入
]]
local Scheduler = class("Scheduler")
function Scheduler:ctor()
self.list = linkList:new()
self.rmList = linkList:new()
self.lock = false
self.updateHandler = handler(self , self._update)
UpdateBeat:Add(self.updateHandler)
end
--[[--
计划一个全局帧事件回调,并返回该计划的句柄。
全局帧事件在任何场景中都会执行,因此可以在整个应用程序范围内实现较为精确的全局计时器。
该函数返回的句柄用作 Scheduler.remove() 的参数,可以取消指定的计划。
@param function 回调函数
@param bool once 是否仅调用一次
@return mixed scheduleNode句柄
]]
function Scheduler:start(listener , once)
local node = SchedulerNode.new()
node.listener = listener
node.once = once
self.list:push(node)
return node
end
--[[--
计划一个以指定时间间隔执行的全局事件回调,并返回该计划的句柄。
@param function listener 回调函数
@param number interval 间隔时间
@return mixed scheduleNode句柄
]]
function Scheduler:startInterval(listener, interval)
local node = SchedulerNode.new()
node.listener = listener
node.interval = interval
self.list:push(node)
return node
end
--[[--
取消一个全局计划
@param mixed scheduleNode句柄
]]
function Scheduler:remove(handle)
for i, v in ilist(self.list) do
if v.listener == handle then
if self.lock then
self.rmList:push({listener = handle})
else
self.list:remove(i)
end
end
end
end
function Scheduler:clear( )
self.list = {}
self.rmList = {}
end
--[[--
计划一个全局延时回调,并返回该计划的句柄。
会在等待指定时间后执行一次回调函数,然后自动取消该计划。
@param function listener 回调函数
@param number time 延迟时间
@param bool once 是否仅调用一次
@return mixed scheduleNode句柄
]]
function Scheduler:startDelay(listener, time , once)
local node = SchedulerNode.new()
node.listener = listener
node.delay = time or 0
node.once = once or false
self.list:push(node)
return node
end
function Scheduler:_update( )
local _list = self.list
local _rmList = self.rmList
self.lock = true
local deltaTime = Time.deltaTime
for i, n in ilist(_list) do
n.elapseTime = n.elapseTime + deltaTime
if n.elapseTime >= n.interval + n.delay then
n.elapseTime = 0
n.delay = 0
n.listener()
if n.once then
_rmList:push(n)
end
end
end
for _, v in ilist(_rmList) do
for i, item in ilist(_list) do
if v.listener == item.listener then
_list:remove(i)
break
end
end
end
_rmList:clear()
self.lock = false
end
function Scheduler:destroy( )
UpdateBeat:Remove(self.updateHandler)
self:clear()
end
Scheduler.ins = Scheduler.new()
return Scheduler
<file_sep>/Assets/Libs/LuaDataBind/UI/Command/ToggleChangeCommand.cs
using System.Collections.Generic;
using UnityEngine;
namespace LuaDataBind
{
/// <summary>
/// Command which is triggered when the selected value of a toggle changed.
/// </summary>
[AddComponentMenu("Data Bind/Commands/[NGUI] Toggle Change Command")]
public class ToggleChangeCommand : NguiEventCommand<UIToggle>
{
/// <summary>
/// Storing toggle value for comparison, the onChange event is triggered
/// if the same value is selected again, too.
/// </summary>
private bool value;
/// <summary>
/// Only toggle value is true when the onChange event is triggered
/// </summary>
public bool EnableOnly = false;
protected override List<EventDelegate> GetEvent(UIToggle target)
{
return target.onChange;
}
protected override void OnEnable()
{
base.OnEnable();
if (this.Target != null)
{
this.value = this.Target.value;
}
}
protected override void OnEvent()
{
var newValue = this.Target.value;
if (newValue == this.value)
{
return;
}
this.value = newValue;
if (EnableOnly && !newValue)
return;
base.OnEvent();
}
}
}<file_sep>/Assets/GEngineScript/Core/SceneManager/LightMap/FilterSceneFlag.cs
/********************************************************************************
** Author: LiangZG
** Email : <EMAIL>
*********************************************************************************/
using UnityEngine;
using System.Collections;
/// <summary>
/// 描述:地景过滤组件标识,生成Prefab实体时,被脚本绑定的结点,将不会被生成到目标Prefab内
/// <para>创建时间:2016-06-21</para>
/// </summary>
public class FilterSceneFlag : MonoBehaviour {
public void SetActive(bool flag)
{
this.gameObject.SetActive(flag);
}
/// <summary>
/// 生成预设时删除自己
/// </summary>
public void ClearSelf()
{
DestroyImmediate(this.gameObject);
}
}
<file_sep>/Assets/GameScript/Lua/Test/LocalizationTest.lua
require "AppConst"
require "Localization/Localization"
LocalizationTest = {}
function LocalizationTest:OnStart()
Localization:InitLocalization()
end
function LocalizationTest:OnGUI()
local function printText(key ,value)
print("key= ".. key .." value = " .. value)
end
if GUILayout.Button("GetValueByKey" , GUILayout.Height(30)) then
local text = Localization:GetText("LTCommon_AppName")
printText("LTCommon_AppName",text)
text = Localization:GetText("LTCommon_HeHe")
printText("LTCommon_HeHe",text)
text = Localization:GetText("LTUser_HaHa")
printText("LTUser_HaHa",text)
text = Localization:ReplaceByKey("LTCommon_DongWang",2,text,text)
printText("LTCommon_DongWang",text)
end
end<file_sep>/Assets/GameScript/Lua/3rd/init.lua
--[[
@Anthor:<EMAIL>
公共模块初始化
]]
local THIRD_MODE_NAME = ...
import(".UISystem.init")
|
e1ca9bd845b140e11dce7c7696ceebe48fe50982
|
[
"Markdown",
"C#",
"Lua"
] | 148 |
C#
|
Liangzg/GEX_1.X
|
c94592208f5c1b154498a4842a923f18b4920e1d
|
cac9f38f93594297cba3950f697865c195641978
|
refs/heads/main
|
<repo_name>Darainn/ReactJS-Project<file_sep>/Project Files/Footer.jsx
import React from 'react';
const Footer = () => {
return(
<>
<div className="bottom-0" >
<footer className="bg-aqua text-center">
<p>
© All Rights Are Reserved || Darain Technical
</p>
</footer>
</div>
</>
)
}
export default Footer;<file_sep>/Project Files/About.jsx
import React from 'react';
import { NavLink } from 'react-router-dom';
import about from "../src/images/about.jpg"
import Common from "./Common";
const About = () => {
return (
<>
< Common name='Welcome To About Page' imgsrc={about} visit='/contact' btname="Contact Now" />
<div style={{color : 'red'}} className="text-center h-25 my-3">
<p>We are the team of developers who are eager to do something for the world of computer</p>
</div>
</>
);
}
export default About;
|
2cbe14c60d113ed91db33dd921b5fac9c753e310
|
[
"JavaScript"
] | 2 |
JavaScript
|
Darainn/ReactJS-Project
|
50bb3e43267cc6d1f871eddd7fd005885b9736d7
|
07332eafc8cc17830a607e7a434e2d60311c7ed5
|
refs/heads/master
|
<file_sep>(function () {
'use strict';
window.com_incowia_demo_elections = {
// assume the given value in associated connection is an url. Build an axios confirm config object using thie url.
buildAjaxRequestConfig: function (url, next) {
next({
url: url,
method: 'get',
responseType: 'json'
});
}
};
})();
<file_sep>## Cubbles <federal-state-elections> demo
<hr/>
This is a small Cubbles demo showing the creation of a compound Cubble using existing Cubbles. In directory `webpackages/com.incowia.demo.elections` you can find compound component `federal-state-elections` and it's corresponding `manifest.webpackage`.
Basically the `federal-state-elections` Cubble has the following structure:
```
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
| <federal-state-elections> |
| _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ |
| | request-election-results | | results-bar-chart | |
| | <ajax-request> status O O xLabels <bar-chart> | |
url O---->O config | | | |
| | result O-----> O dataColumns | |
| |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| |_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _| |
|_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _|
```
Want to get to know more about Cubbles Platform? Visit [cubbles.github.io](http://cubbles.github.io/)
|
fba3590ed23e7d6b0110e374935db0bb820ae064
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
iCubbles/demo.elections
|
f6d57e67a76ae91c6f20fa89356f4026d66749ca
|
171ef21ac2f5a6b66f083e2d9675265b024217a9
|
refs/heads/master
|
<file_sep># Домашнее задание №1 к лекции «TypeScript»
[](https://ci.appveyor.com/project/yuriyvyatkin/ajs-hw-12-1-new-types)
## Новые типы
### Описание
На лекции мы написали классы для книг и аудио-альбомов. Но этого недостаточно, т.к. владельцы портала решили добавить возможность поддержки продажи фильмов.
Реализуйте класс `Movie`, который позволяет отобразить информацию, указанную на скриншоте (скриншот с сайта КиноПоиск):

Удостоверьтесь, что добавление объектов вашего класса в корзину работает.
<file_sep>import Cart from '../service/Cart';
import Movie from '../domain/Movie';
const cart = new Cart();
test('adding a Movie object to the cart works correctly', () => {
const expected = {
id: 1009,
name: 'Мстители',
originalName: '<NAME>',
format: 'IMAX',
year: 2012,
country: 'США',
motto: 'Avengers Assemble!',
genres: ['фантастика', 'боевик', 'фэнтези', 'приключения'],
time: '137 мин. / 02:17',
price: 2000,
};
cart.add(
new Movie(
1009,
'Мстители',
'<NAME>',
'IMAX',
2012,
'США',
'Avengers Assemble!',
['фантастика', 'боевик', 'фэнтези', 'приключения'],
'137 мин. / 02:17',
2000,
),
);
expect(cart.items[0]).toEqual(expected);
expect(cart.items[0]).toBeInstanceOf(Movie);
});
|
3259da60525f5d732d42507d680a3853ae69d7af
|
[
"Markdown",
"TypeScript"
] | 2 |
Markdown
|
Lizaveta04/ajs-hw-12.1-new-types
|
d0acd6caaa963f04c0290142dedaea0da625d9b3
|
3fbef757a08569229551256087a600a5ed026611
|
refs/heads/master
|
<repo_name>anjalihp/systeminfo<file_sep>/systeminfo/main.py
'''Created on 20 FEB 2018
@author: Anjali
'''
import platform
def main():
return(platform.platform())
if __name__=='__main__':
main()
print(main())
|
a89e4974d209157078c7a6e7fb9a9ef2ea2fb231
|
[
"Python"
] | 1 |
Python
|
anjalihp/systeminfo
|
4222663e6081274e3c60b98bf164369c7944bedb
|
cf93699ec2ee156683a03b2fe15c13a29f1d6281
|
refs/heads/master
|
<repo_name>ShaopengHe/push-demo<file_sep>/lib/leancloud.js
var _ = require('underscore');
var request = require('request');
/**
* LeanCloud
* @class LeanCloud
* @param {Object} options
* @param {String} options.appId
* @param {String} options.appKey
*/
function LeanCloud(options) {
this.appId = options.appId;
this.appKey = options.appKey;
this.host = 'https://leancloud.cn';
this.v = '1.1';
this.baseUrl = this.host + '/' + this.v;
}
/**
* 推送消息
* https://leancloud.cn/docs/push_guide.html#推送消息
* @param {Object} data
* @param {Function} callback (err, body)
*/
LeanCloud.prototype.push = function(data, callback) {
var url = this.baseUrl + '/push';
this.__post(url, data, {}, callback);
};
LeanCloud.prototype.__post = function(url, data, options, callback) {
options = _.defaults(options || {}, {});
var headers = {
'X-LC-Id': this.appId,
'X-LC-Key': this.appKey,
'Content-Type': options['Content-Type'] || 'application/json'
};
request({
method: 'post',
url: url,
headers: headers,
json: true,
body: data
}, function(err, res, body) {
if (err) {
return callback(err);
}
if (!body) {
return callback(new Error('NO RESPONSE'));
}
if (body.error) {
var e = new Error(body.error);
e.code = body.code;
return callback(e);
}
return callback(null, body);
});
};
module.exports = LeanCloud;
<file_sep>/lib/xinge.js
var _ = require('underscore');
var crypto = require('crypto');
var request = require('request');
/**
* XinGe
* @class XinGe
* @param {Object} options
* @param {String} options.accessId
* @param {String} options.appKey
*/
function XinGe(options) {
this.accessId = options.accessId;
this.secretKey = options.secretKey;
this.host = 'http://openapi.xg.qq.com';
this.v = 'v2';
this.baseUrl = this.host + '/' + this.v;
}
/**
* 推送消息
* http://developer.qq.com/wiki/xg/
* @param {Object} data
* @param {Function} callback (err, body)
*/
XinGe.prototype.push = function(data, callback) {
var method = data.method || 'all_device';
var url = this.baseUrl + '/push/' + method;
this.__post(url, data, {}, callback);
};
var sign = function(method, url, postBody, secretKey) {
var str = method.toUpperCase() + url.replace('http://', '').replace('https://', '');
var keys = _.keys(postBody);
keys.sort().forEach(function(k) {
str += k + '=' + postBody[k];
});
str += secretKey;
var md5sum = crypto.createHash('md5');
md5sum.update(str, 'utf8');
return md5sum.digest('hex');
};
XinGe.prototype.__post = function(url, data, options, callback) {
options = _.defaults(options || {}, {});
var headers = {
'Content-Type': options['Content-Type'] || 'application/x-www-form-urlencoded'
};
data = _.defaults(data || {}, {
'access_id': this.accessId,
timestamp: Math.floor(Date.now() / 1000)
});
var s = sign('POST', url, data, this.secretKey);
data.sign = s;
request({
method: 'post',
url: url,
headers: headers,
form: data
}, function(err, res, body) {
if (err) {
return callback(err);
}
if (!body) {
return callback(new Error('NO RESPONSE'));
}
try {
body = JSON.parse(body);
} catch (e) {
return callback(new Error('RESPONSE NOT JSON'));
}
if (body['ret_code']) {
var e = new Error(body['err_msg']);
e.code = body['ret_code'];
return callback(e);
}
return callback(null, body);
});
};
module.exports = XinGe;
<file_sep>/test/umeng.js
var config = require('../config').uMeng;
var umeng = new (require('../index').UMeng)(config);
require('should');
describe('UMeng', function() {
describe('#push', function() {
this.timeout('5000');
it('should be success', function(done) {
umeng.push({
type: umeng.TYPE.BROADCAST,
payload: {
'display_type': umeng.MESSAGE_TYPE.NOTIFICATION,
body: {
ticker: 'Hello, UMeng',
title: '你好,友盟',
text: 'UMeng Demo',
'after_open': umeng.AFTER_OPEN.GO_APP
}
}
}, function(err, body) {
if (err) {
console.error(err);
return done(err);
}
body.ret.should.be.equal('SUCCESS');
console.log(body);
done();
});
});
});
});
<file_sep>/test/jpush.js
var config = require('../config').jPush;
var jPush = new (require('../index').JPush)(config);
require('should');
describe('JPush', function() {
describe('POST /push', function() {
it('should be ok', function(done) {
jPush.push({
platform: jPush.PLATFORM.ALL,
audience: jPush.AUDIENCE.ALL,
notification: {
alert: 'Hello, JPush'
}
}, function(err, body) {
if (err) {
console.error(err);
return done(err);
}
body['msg_id'].should.be.a.String;
done();
});
});
});
});
<file_sep>/lib/baidu.js
var BaiduPush = require('baidu-push');
/**
* Baidu
* @class Baidu
* @param {Object} options
* @param {String} options.apiKey
* @param {String} options.secretKey
*/
function Baidu(options) {
this.apiKey = options.apiKey;
this.secretKey = options.secretKey;
this.timeout = options.timeout || 5000;
this.client = BaiduPush.createClient({
apiKey: this.apiKey,
secretKey: this.secretKey,
timeout: this.timeout
});
}
/**
* 推送消息
* http://developer.baidu.com/wiki/index.php?title=docs/cplat/push/api/list#push_msg
* @param {Object} option
* @param {Function} callback (err, body)
*/
Baidu.prototype.push = function(option, callback) {
this.client.pushMsg(option, function(err, body) {
if (err) {
return callback(err);
}
if (body && body['response_params'] && body['response_params']['success_amount']) {
return callback(null, body);
}
return callback(new Error('success amount: 0'));
});
};
/*
* 推送类型
*/
Baidu.prototype.PUSH_TYPE = {
SINGLE: 1,
TAG: 2,
ALL: 3
};
/*
* 消息类型
*/
Baidu.prototype.MESSAGE_TYPE = {
MESSAGE: 0, // 消息(透传给应用的消息体)
NOTIFICATION: 1 // 通知(对应设备上的消息通知)
};
/*
* 设备类型
*/
Baidu.prototype.DEVICE_TYPE = {
ANDROID: 3,
IOS: 4
};
module.exports = Baidu;
<file_sep>/lib/umeng.js
var _ = require('underscore');
var crypto = require('crypto');
var request = require('request');
/**
* UMeng
* @class UMeng
* @param {Object} options
* @param {String} options.appKey
* @param {String} options.appMasterSecret
*/
function UMeng(options) {
this.appKey = options.appKey;
this.appMasterSecret = options.appMasterSecret;
this.host = 'http://msg.umeng.com';
this.baseUrl = this.host + '/api';
}
/**
* 推送消息
* http://dev.umeng.com/push/android/api-doc#2
* @param {Object} option
* @param {Function} callback (err, body)
*/
UMeng.prototype.push = function(option, callback) {
var url = this.baseUrl + '/send';
this.__post(url, option, {}, callback);
};
/*
* 推送类型
*/
UMeng.prototype.TYPE = {
UNICAST: 'unicast',
LISTCAST: 'listcast',
FILECAST: 'filecast',
BROADCAST: 'broadcast',
GROUPCAST: 'groupcast',
CUSTOMIZEDCAST: 'customizedcast'
};
/*
* 消息类型
*/
UMeng.prototype.MESSAGE_TYPE = {
NOTIFICATION: 'notification',
MESSAGE: 'message'
};
/*
* 点击"通知"的后续行为
*/
UMeng.prototype.AFTER_OPEN = {
GO_APP: 'go_app',
GO_URL: 'go_url',
GO_ACTIVITY: 'go_activity',
GO_CUSTOM: 'go_custom'
};
var sign = function(method, url, postBody, appMasterSecret) {
var str = method.toUpperCase();
str += url + JSON.stringify(postBody) + appMasterSecret;
var md5sum = crypto.createHash('md5');
md5sum.update(str, 'utf8');
return md5sum.digest('hex');
};
UMeng.prototype.__post = function(url, data, options, callback) {
options = _.defaults(options || {}, {});
data = _.defaults(data || {}, {
'appkey': this.appKey,
'timestamp': Date.now()
});
var headers = {
'Content-Type': options['Content-Type'] || 'application/json'
};
request({
method: 'post',
url: url,
headers: headers,
json: true,
body: data,
qs: {
sign: sign('post', url, data, this.appMasterSecret)
}
}, function(err, res, body) {
if (err) {
return callback(err);
}
if (!body) {
return callback(new Error('NO RESPONSE'));
}
if (body.ret === 'FAIL') {
var e = new Error(body.ret);
e.code = body.data['error_code'];
return callback(e);
}
return callback(null, body);
});
};
module.exports = UMeng;
<file_sep>/lib/jpush.js
var _ = require('underscore');
var request = require('request');
/**
* JPush
* @class JPush
* @param {Object} options
* @param {String} options.appKey
* @param {String} options.masterSecret
*/
function JPush(options) {
this.appKey = options.appKey;
this.masterSecret = options.masterSecret;
this.host = 'https://api.jpush.cn';
this.v = 'v3';
this.baseUrl = this.host + '/' + this.v;
}
/**
* 推送消息
* http://docs.jpush.io/server/rest_api_v3_push/#_1
* @param {Object} data
* @param {Function} callback (err, body)
*/
JPush.prototype.push = function(data, callback) {
var url = this.baseUrl + '/push';
this.__post(url, data, {}, callback);
};
/*
* 推送平台
*/
JPush.prototype.PLATFORM = {
ALL: 'all',
IOS: 'ios',
ANDROID: 'android'
};
/*
* 设备对象
*/
JPush.prototype.AUDIENCE = {
ALL: 'all',
TAG: function(tags) {
tags = [].concat(tags);
return {
tag: tags
};
}
};
JPush.prototype.__post = function(url, data, options, callback) {
options = _.defaults(options || {}, {});
var headers = {
'Content-Type': options['Content-Type'] || 'application/json'
};
request({
method: 'post',
url: url,
headers: headers,
auth: {
user: this.appKey,
pass: this.masterSecret
},
json: true,
body: data
}, function(err, res, body) {
if (err) {
return callback(err);
}
if (!body) {
return callback(new Error('NO RESPONSE'));
}
if (body.error) {
var e = new Error(body.error.message);
e.code = body.error.code;
return callback(e);
}
return callback(null, body);
});
};
module.exports = JPush;
|
8d5dce32c25a68ad7c49add3ad445d734d771ba2
|
[
"JavaScript"
] | 7 |
JavaScript
|
ShaopengHe/push-demo
|
67b3529e6cf1244496e95c2f57fe115f1aeb61eb
|
512356411fa78164536873f8738aa280daf43a06
|
refs/heads/master
|
<file_sep># we-feel-db<file_sep>CREATE TABLE hourly (
timestamp timestamp,
total integer,
anger integer,
fear integer,
joy integer,
love integer,
other integer,
sadness integer,
surprise integer
);
|
f16d8150b30784cb9cbaf441a2b04a579f455e1a
|
[
"Markdown",
"SQL"
] | 2 |
Markdown
|
beekpower/we-feel-db
|
65d0f0d78e571f4305e37678528e1fc22fffe001
|
706bd4f4a01c0f5c74c374e29b3dc50e998bd438
|
refs/heads/master
|
<repo_name>begliakm/srb-esp8266<file_sep>/testingPOST.ino
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <NTPtimeESP.h>
#include <ESP8266httpUpdate.h>
NTPtime NTPch("lt.pool.ntp.org");
strDateTime dateTime;
const int FW_VERSION = 1000;
const char* fwUrlBase = "http://kurmis.net/fota/esp8266";
const char* ssid = "BarclaysWiFi";
unsigned long lastMillis = 0;
// defines pins numbers
const int trigPin = 3; //RX
const int powerPin = 1; //TX
int echoPins[] = { 4, 13, 12, 14, 5, 15 }; // an array of ECHO pins { D2, D7, D6, D5, D1, D8 }
String host = "http://srb-middleware-dexter-lab.e4ff.pro-eu-west-1.openshiftapps.com";
String endPoint = "/v1/data";
//const char* json = "{\"id\":\"1\",\"mac\":\"00:00:00:00:00\",\"data\":\"-1\",\"time\":\"1994-03-09 00:00:00\"}";
void setup() {
//********** CHANGE PIN FUNCTION TO GPIO **********
pinMode(1, FUNCTION_3); //GPIO 1 (TX) swap the pin to a GPIO.
pinMode(3, FUNCTION_3); //GPIO 3 (RX) swap the pin to a GPIO.
//**************************************************
Serial.begin(115200); //Serial connection
WiFi.begin(ssid); //WiFi connection
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(powerPin, OUTPUT); // Sets the powerPin as an Output
for (int pin = 0; pin < (sizeof(echoPins)/sizeof(int)); pin++) {
pinMode(echoPins[pin], INPUT);
}
Serial.println("");
while (WiFi.status() != WL_CONNECTED) { //Wait for the WiFI connection completion
Serial.print(".");
delay(500);
}
Serial.println("WiFi connected");
if(WiFi.status() == WL_CONNECTED){ //Check WiFi connection status
//String mac = "aa:aa:aa:aa:aa:aa";
String mac = getMacAddress();
Serial.print("MAC: "); Serial.println(mac);
//String date = "1994-03-09 00:00:00";
String date = getTime();
Serial.print("TIME: "); Serial.println(date);
Serial.println("");
Serial.println("");
for (int pin = 0; pin < (sizeof(echoPins)/sizeof(int)); pin++) {
int sensor = pin + 1;
Serial.print("Sensor id: "); Serial.println(sensor);
double distance = getDistance(echoPins[pin]);
Serial.print("Distance: "); Serial.println(distance);
POSTrequest(sensor, mac, distance, date);
}
// checkForUpdates(); //call to check for awailable updates. Doesn't work with BarclaysWiFi
}
else
{
Serial.println("Error in WiFi connection");
}
Serial.println("Deep Sleep for 10 mins");
ESP.deepSleep(600e6, WAKE_RF_DEFAULT); // 60e6 is 1 min
}
void loop() {}
void POSTrequest(int sensor, String mac, double distance, String date) {
HTTPClient http; //Declare object of class HTTPClient
String json = "{\"id\":\"" + String(sensor) + "\",\"mac\":\"" + mac + "\",\"data\":\"" + String(distance)
+ "\",\"time\":\"" + date + "\"}";
const char* jsonFinal = json.c_str();
http.begin(host + endPoint); //Specify request destination
http.addHeader("Content-Type", "application/json"); //Specify content-type header
int request = http.POST((uint8_t *)jsonFinal, strlen(jsonFinal)); //Send the request
delay(500);
String response = http.getString(); //Get the response
Serial.print("Request: "); Serial.println(jsonFinal); //Print HTTP return code
Serial.print("Response: "); Serial.println(response); //Print request response
http.end(); //Close connection
}
String getMacAddress() {
String myMac = "";
byte mac[6];
WiFi.macAddress(mac);
for (int i = 0; i < 6; ++i) {
myMac += String(mac[i], HEX);
if (i < 5)
myMac += ':';
}
return myMac;
}
double getDistance(int echoPin) {
int count = 0;
long duration;
double distance = 0;
double averageDistance = 0;
digitalWrite(powerPin, HIGH); // powering up sensors
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
for(int i = 0; i < 5; i++) {
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
//Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
distance = duration*0.034/2;
if(distance < 200 && distance > 0) {
averageDistance += distance;
count++;
}
delay(100);
}
digitalWrite(powerPin, LOW); // power down sensors
return averageDistance/count;
}
String getTime() {
String date = "1994-03-09 00:00:00";
while(!dateTime.valid){
dateTime = NTPch.getNTPtime(2, 1);
}
byte hour = dateTime.hour;
byte minute = dateTime.minute;
byte second = dateTime.second;
int year = dateTime.year;
byte month = dateTime.month;
byte day = dateTime.day;
date = String(year)+"-"+String(month)+"-"+String(day)+" "+String(hour)+":"+String(minute)+":"+String(second);
return date;
}
void checkForUpdates() {
String fwURL = String( fwUrlBase );
String fwVersionURL = fwURL;
fwVersionURL.concat( ".version" );
Serial.println( "Checking for firmware updates." );
Serial.print( "Firmware version URL: " );
Serial.println( fwVersionURL );
HTTPClient httpClient;
httpClient.begin( fwVersionURL );
int httpCode = httpClient.GET();
if( httpCode == 200 ) {
String newFWVersion = httpClient.getString();
Serial.print( "Current firmware version: " );
Serial.println( FW_VERSION );
Serial.print( "Available firmware version: " );
Serial.println( newFWVersion );
int newVersion = newFWVersion.toInt();
if( newVersion > FW_VERSION ) {
Serial.println( "Preparing to update" );
String fwImageURL = fwURL;
fwImageURL.concat( ".txt" );
Serial.print( "Firmware URL: " );
Serial.println( fwImageURL );
t_httpUpdate_return ret = ESPhttpUpdate.update( fwImageURL );
switch(ret) {
case HTTP_UPDATE_FAILED:
Serial.printf("HTTP_UPDATE_FAILD Error (%d): %s", ESPhttpUpdate.getLastError(), ESPhttpUpdate.getLastErrorString().c_str());
break;
}
}
else {
Serial.println( "Already on latest version" );
}
}
else {
Serial.print( "Firmware version check failed, got HTTP response code " );
Serial.println( httpCode );
}
httpClient.end();
}
|
fc3183ea277604a6d9ecf2a4ac41644d5c62d99c
|
[
"C++"
] | 1 |
C++
|
begliakm/srb-esp8266
|
eac9fced1cbe15528c0f302bfa4243181b237ccf
|
7830378640a14241952b6cc025900fa94bad9142
|
refs/heads/master
|
<repo_name>tlherr/RADAutoCenter<file_sep>/AutoCenter/AutoCenterForm.cs
/**
* Student Name: <NAME>
* Student Number: 200325519
* Purpose: Allow users to view package configurations for local auto center
*/
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 AutoCenter
{
public partial class AutoCenterForm : Form
{
/**
* Factory class generates package arrays for us based on specified input
*/
PackageFactory pkgFactory = new PackageFactory();
/**
* Constructor
*/
public AutoCenterForm()
{
InitializeComponent();
}
/**
* Event handler for packageComboBox item changed event, fires when a new value is selected
*/
private void packageComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
//Empty the output
packageTextBox.Text = String.Empty;
ComboBox comboBox = (ComboBox)sender;
//If nothing was selected exit out immediatly before wasting any time
if (packageComboBox.SelectedItem == null)
{
return;
}
//Set the array that will store our display data, this is generated by the package factory class
string[][] data = this.pkgFactory.getPackage(comboBox.SelectedItem.ToString(), null);
displayOutput(data, 0, packageTextBox);
//Simulate a click on the fragrance box to make it update the UI
if (fragranceComboBox.SelectedItem!=null)
{
fragranceComboBox_SelectedIndexChanged(fragranceComboBox, e);
}
}
/**
* Event handler for fragranceComboBox item changed event, fires when a new value is selected
*/
private void fragranceComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
//Empty the output
fragranceTextBox.Text = String.Empty;
ComboBox comboBox = (ComboBox)sender;
//If nothing was selected exit out immediatly before wasting any time
if (fragranceComboBox.SelectedItem == null)
{
return;
}
//Set the array that will store our display data, this is generated by the package factory class
string[][] data = this.pkgFactory.getPackage(packageComboBox.SelectedItem.ToString(), comboBox.SelectedItem.ToString());
//Consume the arrays provided
displayOutput(data, 1, fragranceTextBox);
}
/**
* Format data and display to given output textbox
*/
private void displayOutput(string[][] data, int depth, TextBox output)
{
//Consume the arrays provided
for (int x = 0; x < data[depth].Length; x++)
{
//First item to be displayed, output a comma after it for formatting
if (x == 0 && x != data[depth].Length - 1)
{
output.Text += data[depth][x] + ",";
//Last item to be displayed, dont place a comma at the end
}
else if (x == data[depth].Length - 1)
{
output.Text += " " + data[0][x];
}
//Middle item, make sure it has a comma for formatting
else
{
output.Text += " " + data[depth][x] + ",";
}
}
}
/**
* Context menu about click event handler
*/
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
//Show the about form when requested
AboutForm aboutForm = new AboutForm();
aboutForm.Show();
}
/**
* Context menu clear click event handler
*/
private void clearToolStripMenuItem_Click(object sender, EventArgs e)
{
//Setting both of these to null will trigger the selected change event handled above so outputs will be automatically updated
fragranceComboBox.SelectedItem = null;
packageComboBox.SelectedItem = null;
}
/**
* Context Menu exit click event handler
*/
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
<file_sep>/AutoCenter/PackageFactory.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AutoCenter
{
public class PackageFactory
{
//Populate specified data structures
string[][] standardArray =
{
new string[] {"Hand Wash" },
new string[] {"Fragrance" }
};
string[][] deluxeArray =
{
new string[] {"Hand Wash", "Hand Wax"},
new string[] {"Fragrance", "Shampoo Carpets"}
};
string[][] executiveArray =
{
new string[] {"Hand Wash", "Hand Wax", "Check Engine Fluids"},
new string[] {"Fragrance", "Shampoo Carpets", "Interior Protection Coat (Dashboard and Console)" }
};
string[][] luxuryArray =
{
new string[] {"Hand Wash", "Hand Wax", "Check Engine Fluids", "Detail Engine Compartment", "Detail Undercarriage"},
new string[] {"Fragrance", "Shampoo Carpets", "Shampoo Upholstery", "Interior Protection Coat (Dashboard and Console)", "Scotchguard"}
};
//When a package is requested the name and fragrance are specified, a matching package array will be formatted and returned
public string[][] getPackage(string name, string fragrance)
{
name = name.ToLower();
switch(name)
{
case "standard":
string[][] standardArray = this.standardArray;
if(fragrance != null)
{
standardArray[1][0] = fragrance;
}
return standardArray;
case "deluxe":
string[][] deluxeArray = this.deluxeArray;
if (fragrance != null)
{
deluxeArray[1][0] = fragrance;
}
return deluxeArray;
case "executive":
string[][] executiveArray = this.executiveArray;
if (fragrance != null)
{
executiveArray[1][0] = fragrance;
}
return executiveArray;
case "luxury":
string[][] luxuryArray = this.luxuryArray;
if (fragrance != null)
{
luxuryArray[1][0] = fragrance;
}
return luxuryArray;
}
return null;
}
}
}
<file_sep>/AutoCenter/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AutoCenter
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
WelcomeForm.ShowSplashScreen();
AutoCenterForm mainForm = new AutoCenterForm();
WelcomeForm.CloseForm();
Application.Run(mainForm);
}
}
}
|
f83c39aecbaa3a1c0f7b7903c17704e957cbe804
|
[
"C#"
] | 3 |
C#
|
tlherr/RADAutoCenter
|
5f5a1b3d1debb335174ab70c2752d82a61337ed2
|
13f91cf5b80f3636610f3d0a1b184255676e3679
|
refs/heads/master
|
<repo_name>JiongRanWang/HW5<file_sep>/benchmark_llr.R
#install.packages("bench")
library(bench)
#setwd("..")
#dir<-getwd()
#setwd(toString(paste(dir,"/Stat610/",sep='')))
#setwd("/Users/jiongranwang/Desktop/S610")
bnchmark <- bench::mark(
source("llr_functions.R"))
bnchmark
|
4ff1f41fb1bb06a66e0beec2c3efc485259f2b96
|
[
"R"
] | 1 |
R
|
JiongRanWang/HW5
|
d5793f2ce18a0513c90051553b8c9258eac26b59
|
b9c31c38bda2e7354c38eb3a343b6f034cf823a1
|
refs/heads/master
|
<repo_name>dsbankov/findbugs-plugin<file_sep>/plugin/go.sh
rm -rf $HUDSON_HOME/plugins/findbugs*
mvn install || { echo "Build failed"; exit 1; }
cp -f target/*.hpi $HUDSON_HOME/plugins/
cd $HUDSON_HOME
java -jar hudson.war
<file_sep>/plugin/clean.sh
rm -rf $HUDSON_HOME/plugins/findbugs*
mvn clean install
cp -f target/*.hpi $HUDSON_HOME/plugins/
cd $HUDSON_HOME
java -jar hudson.war
|
e52389ab567dd3eb90e4050dae601af58194666e
|
[
"Shell"
] | 2 |
Shell
|
dsbankov/findbugs-plugin
|
c0037c492bc861f696465d591af36adb6550a3a5
|
aed5c8db07a21229a71fcbb55f7a9160fba75d8d
|
refs/heads/main
|
<file_sep>#ifndef __RESTAURANT_H_
#define __RESTAURANT_H_
#include "..\Defs.h"
#include "..\CMUgraphicsLib\CMUgraphics.h"
#include "..\GUI\GUI.h"
#include "..\Generic_DS\Queue.h"
#include "..\Generic_DS\PriorityQueue.h"
#include "..\Events\Event.h"
#include"..\Generic_DS\LinkedList.h"
#include"..\LinkedList.h"
#include <fstream>
#include<time.h>
#include "Order.h"
// it is the maestro of the project
class Restaurant
{
private:
GUI *pGUI;
Queue<Event*> EventsQueue; //Queue of all events that will be loaded from file
string IPfilename;
string OPfilename;
float InjProp;
//Queue for each type of Cooks
Queue<Cook*> NcooksQ;
Queue<Cook*> GcooksQ;
Queue<Cook*> VcooksQ;
//Priority Queue For Busy Cooks and queues for inBreak cooks
PriorityQueue<Cook*> busyCooksQ;
PriorityQueue<Cook*> CooksInBreak;
Queue<Cook*>CooksInRest;
//Priority Queue for vip orders depending on Priority Equation
PriorityQueue<Order*> QVIP_Order;
//
LinkedList<Order*> LNormal_Order;
Queue<Order*> Qvegan_Order;
Queue<Order**> QUrgentOrders;
PriorityQueue<Order*> InServing;
Queue<Order*>FinishedList;
public:
Restaurant();
~Restaurant();
void ExecuteEvents(int TimeStep); //executes all events at current timestep
void RunSimulation();
void fileLoading();
void outputFileLoading();
void SimpleSimulator();
void Interactive();
void Restaurant_Modes(int Mode);
void FillDrawingList();
void AddtoVIPQueue(Order*& po);
void AddtoNOList(Order*& po);
void AddtoVEQueue(Order*& po);
void cancellorder(int ID);
void promoteorder(int ID, double exmoney);
void Executepromotion(int CurrentTimeStep);
void serve_VIP_orders(int CurrentTimeStep);
void serve_Normal_orders(int CurrentTimeStep);
void serve_Vegan_orders(int CurrentTimeStep);
void getfrombusyCookQ(int CurrentTimeStep);
void getfromBreakCookQ(int CurrentTimeStep);
void getfromInServingQ(int CurrentTimeStep);
void CheckUrgentOrders(int CurrentTimeStep);
bool GetCooksFor_Urgent_VIP(int CurrentTimeStep);
void Serve_Urgent_VIP(int CurrentTimeStep);
int numNcooks, numGcooks, numVcooks, Ncookspeed_min, Ncookspeed_max, Gcookspeed_min, Gcookspeed_max, Vcookspeed_min, Vcookspeed_max;
int numOrdersBbreak, Nbreak_min, Nbreak_max, Gbreak_min, Gbreak_max, Vbreak_min, Vbreak_max, numofevents;
int NCookNum , GCookNum , VCookNum;
int injcooksnum = 0;
int NWaitNum, GWaitNum, VWaitNum;
int SRVorders, AutoP, RstPrd, VIP_WT;
int UrgentOredersNum=0;
int Userved=0,Vserved = 0, Nserved = 0, Gserved = 0;
float numAutoPromOrders = 0;
int originalNormOrdCount = 0;
bool Health_Emergency(int CurrentTimeStep);
void getfromRestCookQ(int CurrentTimeStep);
//This Strings are for storing Cooks and Orders info to be Printed on GUI
string UFinfo;
string VFinfo;
string NFinfo;
string GFinfo;
////////////////////
float RandomFloat(float a, float b) {
//srand((int)time(0));
float random = ((float)rand()) / (float)RAND_MAX;
float diff = b - a;
float r = random * diff;
return a + r;
}
int rangeRandomAlg2(int min, int max) {
int n = abs(max - min )+ 1;
int remainder = RAND_MAX % n;
int x;
do {
x = rand();
} while (x >= RAND_MAX - remainder);
return min + x % n;
}
};
#endif<file_sep>#include "Cook.h"
#include<cmath>
Cook::Cook()
{
RstPrd = 0;
Is_inj = false;
has_Urg =false;
}
Cook::~Cook()
{
}
int Cook::GetID() const
{
return ID;
}
ORD_TYPE Cook::GetType() const
{
return type;
}
int Cook::getSpeed() const
{
return speed;
}
int Cook::getNumOrdBbreak() const
{
return numOrdersBefBreak;
}
int Cook::getBreakDur() const
{
return breakDuration;
}
int Cook::getnumofOrderdServed() const
{
return numofOrderdServed;
}
void Cook::setID(int id)
{
ID = id;
}
void Cook::setType(ORD_TYPE t)
{
type = t;
}
void Cook::setSpeed(int s)
{
if (s >= 1)
speed = s;
else
speed = 1;
}
void Cook::setNumOrdBbreak(int num)
{
numOrdersBefBreak = abs(num);
}
void Cook::setBreakDur(int bd)
{
breakDuration = abs(bd);
}
void Cook::setnumofOrderdServed(int num)
{
numofOrderdServed = num;
}
void Cook::set_RstPrd(int r)
{
if (r >= 0)
RstPrd = r;
}
int Cook::get_RstPrd()
{
return RstPrd;
}
void Cook::assign_Order(int order)
{
ord_assigned = order;
}
int Cook::get_order()
{
return ord_assigned;
}
void Cook::injure(bool hurt)
{
Is_inj = hurt;
}
bool Cook::Is_injured()
{
return Is_inj;
}
void Cook::set_RstTime(int rst)
{
rst_ts = RstPrd + rst;
}
int Cook::get_rstTime()
{
return rst_ts;
}
void Cook::Give_Urg(bool urg)
{
has_Urg = urg;
}
bool Cook::Has_Urg()
{
return has_Urg;
}<file_sep>
#pragma once
template < typename T>
class PriorityNode
{
private:
T item;// A data item
float priority;//priority of data to insert in the queue
PriorityNode<T>* next; // Pointer to next node
public:
PriorityNode();
PriorityNode(const T& r_Item,float& pri); //passing by const ref.
PriorityNode(const T& r_Item,float& pri, PriorityNode<T>* nextNodePtr);
void setItem(const T& r_Item);
void setNext(PriorityNode<T>* nextNodePtr);
void setPriority(float& priority);
float GetPriority()const;
T getItem() const;
PriorityNode<T>* getNext() const;
}; // end p. Node
template < typename T>
PriorityNode<T>::PriorityNode()
{
next = nullptr;
priority = 0;
}
template < typename T>
PriorityNode<T>::PriorityNode(const T& r_Item,float& pri)
{
priority = pri;
item = r_Item;
next = nullptr;
}
template < typename T>
PriorityNode<T>::PriorityNode(const T& r_Item, float& pri, PriorityNode<T>* nextNodePtr)
{
setPriority(pri);
item = r_Item;
next = nextNodePtr;
}
template < typename T>
void PriorityNode<T>::setItem(const T& r_Item)
{
item = r_Item;
}
template < typename T>
void PriorityNode<T>::setPriority(float& pri)
{
if(pri>=0)
priority = pri;
}
template < typename T>
void PriorityNode<T>::setNext(PriorityNode<T>* nextNodePtr)
{
next = nextNodePtr;
}
template < typename T>
T PriorityNode<T>::getItem() const
{
return item;
}
template < typename T>
float PriorityNode<T>::GetPriority() const
{
return priority;
}
template < typename T>
PriorityNode<T>* PriorityNode<T>::getNext() const
{
return next;
}
<file_sep>#pragma once
#include "Generic_DS/Node.h"
template <typename T>
class LinkedList
{
private:
Node<T>* Head; //Pointer to the head of the list
//You can add tail pointer too (depending on your problem)
Node<T>* tail;
public:
LinkedList()
{
Head = nullptr;
tail = nullptr;
}
//List is being desturcted ==> delete all items in the list
~LinkedList()
{
DeleteAll();
}
bool isEmpty()
{
return Head == nullptr;
}
Node<T>* getHead()
{
return Head;
}
void settail(Node<T>* t)
{
tail = t;
}
void DeleteAll()
{
Node<T>* P = Head;
while (Head)
{
P = Head->getNext();
delete Head;
Head = P;
}
}
void InsertEnd(const T& data)
{
Node<T>* p = new Node<T>;
p->setItem(data);
if (!Head)
{
Head = tail = p;
p->setNext(nullptr);
return;
}
else if (!Head->getNext())
{
tail = p;
Head->setNext(p);
tail->setNext(nullptr);
}
else
{
tail->setNext(p);
p->setNext(nullptr);
tail = p;
}
}
bool DeleteFirst(T& frntEntry)
{
if (isEmpty())
return false;
else if (Head->getNext()==nullptr)
{
frntEntry = Head->getItem();
delete Head;
Head = tail = nullptr;
}
else
{
frntEntry = Head->getItem();
Node<T>* temp = new Node<T>;
temp =Head;
Head = Head->getNext();
delete temp;
}
}
bool peek(T& frntEntry)
{
if (isEmpty())
return false;
frntEntry = Head->getItem();
return true;
}
void DeleteLast(T& frntEntry)
{
Node<T>* temp = Head;
if (!Head)
{
return;
}
frntEntry = tail->getItem();
while (temp->getNext() != tail)
{
temp = temp->getNext();
}
temp->setNext(nullptr);
tail = temp;
}
bool DeleteNode(const T& value)
{
bool found = false;
if (!Head)
{
return found;
}
Node<T>* prev = Head;
if (Head->getItem() == value)
{
T num;
DeleteFirst(num);
found = true;
return found;
}
while (prev->getNext()->getNext())
{
if (prev->getNext()->getItem() == value)
{
Node<T>* temp = new Node<T>;
temp = prev->getNext();
prev->setNext(temp->getNext());
delete temp;
found = true;
return found;
}
else
prev = prev->getNext();
}
if (prev->getNext()->getItem() == value)
{
DeleteLast();
found = true;
}
return found;
}
T *toArray(int& count)
{
count = 0;
if (!Head)
return nullptr;
//counting the no. of items in the List
Node<T>* p = Head;
while (p)
{
count++;
p = p->getNext();
}
T* Arr = new T[count];
p = Head;
for (int i = 0; i < count;i++)
{
Arr[i] = p->getItem();
p = p->getNext();
}
return Arr;
}
};<file_sep>#include "Order.h"
#include<cmath>
Order::Order(ORD_TYPE r_Type,int arrtime, int id, int size, double totalmoney)
{
ID = (id>0&&id<1000)?id:0; //1<ID<999
type = r_Type;
status = WAIT;
WaitTime = 0;//initially 0 and will increment each time step
totalMoney =(totalmoney > 0)?totalmoney:0;
setArrTime(arrtime);
setOrderSize(size);
Priority = 0;
Urgent = false;
}
Order::~Order()
{
}
int Order::GetID()
{
return ID;
}
ORD_TYPE Order::GetType() const
{
return type;
}
void Order::setStatus(ORD_STATUS s)
{
status = s;
}
ORD_STATUS Order::getStatus() const
{
return status;
}
void Order::setOrderSize(int size)
{
orderSize = (size>0)?size:0;
}
void Order::setPriority()
{
Priority = 10*float(ArrTime * orderSize)/(totalMoney);
}
int Order::getOrderSize()const
{
return orderSize;
}
int Order::getArrTime()const
{
return ArrTime;
}
int Order::getServTime()const
{
return ServTime;
}
int Order::getServInt()const
{
return srvInt;
}
int Order::getWaitTime()const
{
return WaitTime;
}
int Order::getFinishTime()const
{
return FinishTime;
}
float Order::getPriority()
{
return Priority;
}
void Order::Promote(double& addedmoney)
{
type = TYPE_VIP;
totalMoney += abs(addedmoney);
setPriority();
}
void Order::setArrTime(int& arr)
{
ArrTime = abs(arr);
}
void Order::setServTime( int& serv)///as TimeStep
{
ServTime = serv;
}
void Order::setServInt( int& serv)////as time interval
{
srvInt = serv;/////will depend on the cook
}
void Order::setWaitTime()
{
WaitTime = ServTime -ArrTime;
}
void Order::setFinishTime()
{
FinishTime = ServTime+srvInt ;
}
void Order::Serve(int crrTS)
{
////Uhmmm ... lets talk a bit about the Algorithm I am following
//first and after making the queue of the events ... I take the orders by dequeuing
//each event"I guess that will be implementing in ArrivalEvent class" so that i prepare the queue of the Orders
//... During every iterartion I make an object of class order and construct it
////with the data members from the input file
///in case of VTP orders We call fundtion setPriority to calculate the priority of the order then assign it to priority queue
///when we assign an order to a cook .. depending on the cook speed we calculate the service interval
//and call the function of the order object ,i.e:order.setServInt(cookSpeed>=orderSize?1:Ceil(float(ordersize)/cookspeed))
///and finally we call Serve function by passing the current time step we are in to it
///so that we get the finish time
setServTime(crrTS);
setWaitTime();
setFinishTime();
setStatus(SRV);
}
void Order::setUrgent(bool flag)
{
Urgent = flag;
}
bool Order::isUrgent()
{
return Urgent;
}<file_sep>#pragma once
#include "Node.h"
template <class T>
//This Data Structure Depends On LIFO
class Stack
{
private:
Node<T>* Top; //A pointer that points to last element entered stack
public:
Stack();
bool Push(T element); //Pushing an element to stack
bool isEmpty(); //Checking if stack empty or not
bool pop(); // This Function Removes The Last Element in Stack
bool getTop(T& stacktop); //Get Last Elemnt Enterd the Stack
~Stack();
};
////////////////////////////////////////
//constuctor of Stack
template <class T>
Stack<T>::Stack()
{
Top = nullptr;
}
template <class T>
bool Stack<T>::Push(T element)
{
Node<T>* newnode = new Node<T>;
if (newnode == nullptr)
return false;
newnode->setItem(element);
newnode->setNext(Top);
Top = newnode;
return true;
}
template <class T>
bool Stack<T> ::isEmpty()
{
return Top == nullptr;
}
template <class T>
bool Stack<T> ::pop()
{
if (isEmpty())
{
return false;
}
else
{
Node<T>* temp = Top; //temporary pointer to remove last element
Top = Top->getNext();
temp->setNext(nullptr);
delete temp;
return true;
}
}
template <class T>
bool Stack<T> ::getTop(T& stacktop)
{
if (isEmpty())
return false;
else
{
stacktop = Top->getItem();
return true;
}
}
template <class T>
Stack<T> ::~Stack()
{
}<file_sep>#include "CancellationEvent.h"
#include "..\Rest\Restaurant.h"
CancellationEvent::CancellationEvent(int Time, int ID) :Event(Time, ID)
{
//there is no more data member
}
void CancellationEvent::Execute(Restaurant* pRest)
{
pRest->cancellorder(OrderID); //here we cancelled the order from Normal orders Queue
}<file_sep>#pragma once
#include "..\Defs.h"
#pragma once
class Cook
{
int ID;
ORD_TYPE type; //for each order type there is a corresponding type (VIP, Normal, Vegan)
int speed; //dishes it can prepare in one clock tick (in one timestep)
int ord_assigned;
bool Is_inj;
int rst_ts;
bool has_Urg;
int RstPrd;
int numOrdersBefBreak;
int breakDuration;
int numofOrderdServed;
public:
Cook();
virtual ~Cook();
int GetID() const;
ORD_TYPE GetType() const;
int getSpeed() const;
int getNumOrdBbreak() const;
int getBreakDur() const;
int getnumofOrderdServed() const;
//////////////////////////////////////////////////
void setID(int);
void setType(ORD_TYPE) ;
void setSpeed(int);
void setNumOrdBbreak(int num);
void setBreakDur(int bd);
void setnumofOrderdServed(int num);
void set_RstPrd(int r);
int get_RstPrd();
void assign_Order(int order);
int get_order();
bool Is_injured();
void injure(bool hurt);
void set_RstTime(int rst);
int get_rstTime();
void Give_Urg(bool);
bool Has_Urg();
float f_speed;
};
<file_sep>#ifndef __GUI_H_
#define __GUI_H_
#include "..\CMUgraphicsLib\CMUgraphics.h"
#include "..\Defs.h"
#include "..\Rest\Order.h"
#include "..\Rest\Cook.h"
#include "..\Generic_DS\Queue.h"
#include <string>
using namespace std;
class GUI
{
enum GUI_REGION {
ORD_REG, //GUI Regions where waiting orders are drawn
COOK_REG, //GUI Regions where waiting coocks are drawn
SRV_REG, //GUI Regions where in-service orders are drawn
DONE_REG, //GUI Regions where finished orders are drawn
REG_CNT //Total number of regions
};
struct DrawingItem //holds info for each item to be drawn on screen
{
int ID; //ID to be printed on the screen indicating this item
GUI_REGION region; //Region where it should be drawn
color clr; //drawing color
};
private:
window* pWind;
color DrawingColors[TYPE_CNT];
//The four regions in the GUI window:
// Some Static Constant Data Members: ---------------------
static const int
WindWidth = 1200, WindHeight =650, //Window width and height
StatusBarHeight = 150, //Status Bar Height
MenuBarHeight = 0, //Menu Bar Height (distance from top of window to bottom line of menu bar)
MenuItemWidth = 80, //Width of each item in menu bar menu
DrawingAreaHeight = WindHeight - MenuBarHeight - StatusBarHeight,
YHalfDrawingArea = MenuBarHeight + DrawingAreaHeight / 2, //The y coordinate of half the Drawing area
RestStartX = (int)(WindWidth * 0.45), //The x coordinate of the upper left corner of the Rest
RestEndX = (int)(WindWidth * 0.55), //The x coordinate of the lower right corner of the Rest
RestWidth = RestEndX - RestStartX, //The width of the Rest (Note: the Rest is a Square)
RestStartY = YHalfDrawingArea - RestWidth / 2, //The y coordinate of the upper left corner of the Rest
RestEndY = YHalfDrawingArea + RestWidth / 2, //The y coordinate of the lower right corner of the Rest
FontSize = 20, //font size used to draw orders ID on Interface
OrderWidth = 2 * FontSize, //width of the order to be drawn on GUI
OrderHeight = FontSize, //height of the order to be drawn on GUI
MaxHorizOrders = ((WindWidth - RestWidth) / 2) / (OrderWidth + 1), //The max no. of orders the can be drwan in on Horizontal line in a region
MaxVerticalOrders = (DrawingAreaHeight / 2) / (OrderHeight + 1), //The max no. of orders the can be drwan in on Horizontal line in a region
//Max no of orders that can be drawn in a single region
MaxRegionOrderCount = MaxHorizOrders * MaxVerticalOrders;
/////////
////////
////////
static const int maxItemCnt = MaxPossibleOrdCnt + MaxPossibleMcCnt;
DrawingItem* DrawingList[maxItemCnt]; //List of items pointers to be drawn every timestep
int DrawingItemsCount; //actual no. of items in the drawing list
//NOTES:
//Orders are assumed to be sorted by arrival time
// At every time step, you should update those pointers
// to point to the current waiting orders only
//
// TODO: Add more members if needed
//
void DrawSingleItem(const DrawingItem* pDitem, int RegionCount) const; //draws ONE item
void DrawAllItems(); //drwas ALL items in DrawingList
void DrawString(const int iX, const int iY, const string Text); // prints a message in the passed coordinates
void DrawString1(const int iX, const int iY, const string Text);
public:
GUI();
~GUI();
// Input Functions ---------------------------
void waitForClick() const; // waits a user click from the user
string GetString() const; // reads a string (keyboard input) from the user
// Output Functions ---------------------------
void PrintMessage(string msg, char* font="Jokerman") const; // prints a message in the status bar
void ClearStatusBar() const; // clears the status bar
void ClearDrawingArea() const; // clears the Drawing area from all drawings
void DrawRestArea() const; // draws the restaurant area
void UpdateInterface();
void AddToDrawingList(Order* pOrd); //Adds a new order to the drawing queue
void AddToDrawingList(Cook* pC); //Adds a new cook to the drawing queue
void ResetDrawingList(); //resets drawing list (should be called every timestep after drawing)
void ClearStatusBar(int line) const;
void PrintMessage(string msg, int line) const;
PROG_MODE getGUIMode() const; //returns the mode of the program
void PrintMessage2(string msg, char* font = "Jokerman") const;
};
#endif<file_sep>#include "ArrivalEvent.h"
#include "..\Rest\Restaurant.h"
ArrivalEvent::ArrivalEvent(int eTime, int oID, ORD_TYPE oType):Event(eTime, oID)
{
OrdType = oType;
}
ArrivalEvent::ArrivalEvent(int eTime, int oID, ORD_TYPE oType, int Osize, double Omoney): Event(eTime, oID)
{
OrdType = oType;
OrderSize = Osize;
OrdMoney = Omoney;
}
void ArrivalEvent::Execute(Restaurant* pRest)
{
//This function should create an order and fills its data
// Then adds it to normal, vegan, or VIP order lists that you will create in phase1
////TYPE_NRM, //normal order
//// TYPE_VGAN, //vegan
//// TYPE_VIP, //VIP
//Order(ORD_TYPE r_Type, int arrtime, int ID, int size, int totalmoney);
///For the sake of demo, this function will just create an order and add it to DemoQueue
///Remove the next code lines in phases 1&2
Order* pOrd = new Order(OrdType, EventTime,OrderID, OrderSize, OrdMoney);
//pRest->AddtoDemoQueue(pOrd);
pOrd->setStatus(WAIT);
if (OrdType == TYPE_NRM)
{
pRest->AddtoNOList(pOrd);
}
else if (OrdType == TYPE_VGAN)
{
pRest->AddtoVEQueue(pOrd);
}
else if (OrdType == TYPE_VIP)
{
pRest->AddtoVIPQueue(pOrd);
}
}
<file_sep># Salta3-Burger
A Data- Structure App for Restaurant Management made in c++ language
<img src="https://i.ibb.co/Njm8RMD/Screenshot-67.png">
<br/>
<img src="https://i.ibb.co/tYHRL7D/Screenshot-63.png">
<br/>
<img src="https://i.ibb.co/93msZ8r/Screenshot-66.png">
<file_sep>#ifndef __ORDER_H_
#define __ORDER_H_
#include "..\Defs.h"
class Order
{
protected:
int ID; //Each order has a unique ID (from 1 --> 999 )
ORD_TYPE type; //order type: Normal, vegan, VIP
ORD_STATUS status; //waiting, in-service, done
int Distance; //The distance (in meters) between the order location and the resturant
double totalMoney; //Total order money
int ArrTime, ServTime, FinishTime; //arrival, service start, and finish times
int orderSize;
float Priority;
int WaitTime;
int srvInt;
bool Urgent;
public:
Order( ORD_TYPE r_Type,int arrtime, int ID, int size,double totalmoney);
virtual ~Order();
int GetID();
ORD_TYPE GetType() const;
void setStatus(ORD_STATUS s);
ORD_STATUS getStatus() const;
void setPriority();
void setOrderSize(int size);
float getPriority();
int getOrderSize()const;
int getArrTime()const;
int getServTime()const;
int getServInt()const;
int getWaitTime()const;
int getFinishTime()const;
void Promote( double& addedmoney);
void setArrTime(int& arr);
void setServTime( int& serv);
void setServInt(int& serv);
void setFinishTime();
void setWaitTime();
void Serve( int);
void setUrgent(bool flag);
bool isUrgent();
};
#endif<file_sep>#pragma once
#include "Event.h"
class PromotionEvent :public Event
{
double ExMony;
public:
PromotionEvent(int Time, int ID, double extramony);
virtual void Execute(Restaurant* pRest); //override execute function
};
<file_sep>#include "PromotionEvent.h"
#include "..\Rest\Restaurant.h"
PromotionEvent::PromotionEvent(int Time, int ID, double extramony) :Event(Time, ID)
{
ExMony = extramony;
}
void PromotionEvent::Execute(Restaurant* pRest)
{
pRest->promoteorder(OrderID, ExMony);
}<file_sep>#include <cstdlib>
#include <time.h>
#include <iostream>
using namespace std;
#include "Restaurant.h"
#include "..\Events\ArrivalEvent.h"
#include "..\Events\CancellationEvent.h"
#include"..\Events\PromotionEvent.h"
Restaurant::Restaurant()
{
pGUI = NULL;
}
void Restaurant::RunSimulation()
{
pGUI = new GUI;
PROG_MODE mode = pGUI->getGUIMode();
switch (mode) //Add a function for each mode in next phases
{
case MODE_INTR:
Restaurant_Modes(1);
break;
case MODE_STEP:
Restaurant_Modes(2);
break;
case MODE_SLNT:
Restaurant_Modes(3);
break;
};
}
////////////////////////////////// Event handling functions /////////////////////////////
//Executes ALL events that should take place at current timestep
void Restaurant::ExecuteEvents(int CurrentTimeStep)
{
Event *pE;
while( EventsQueue.peekFront(pE) ) //as long as there are more events
{
if(pE->getEventTime() > CurrentTimeStep ) //no more events at current timestep
return;
pE->Execute(this);
EventsQueue.dequeue(pE); //remove event from the queue
delete pE; //deallocate event object from memory
}
}
//promot Normer orders automatically promoted to VIP after it excess (Autop) time step in waiting List
void Restaurant::Executepromotion(int CurrentTimeStep)
{
Order* proOrder;
while (LNormal_Order.peek(proOrder)) //as long as there is more waiting Orders
{
if ((CurrentTimeStep - proOrder->getArrTime()) < AutoP) //no more event can be promoted in this time step
return;
LNormal_Order.DeleteFirst(proOrder); //remove order from Normal List
double money = 0;
proOrder->Promote(money);
float priority = proOrder->getPriority();
QVIP_Order.enqueue(proOrder, priority); //add it to VIP queue
numAutoPromOrders++;
}
}
//Serving VIP orders after wating time excess VIP_WT to any cook in Break or Rest
void Restaurant::CheckUrgentOrders(int CurrentTimeStep)
{
Order**vipordersarr;
int size;
vipordersarr = QVIP_Order.toArray(size);
for (int i = 0; i < size;i++)
{
if (CurrentTimeStep - vipordersarr[i]->getArrTime() > VIP_WT && !vipordersarr[i]->isUrgent())
{
vipordersarr[i]->setUrgent(true);
QUrgentOrders.enqueue(&vipordersarr[i]);
UrgentOredersNum++;
}
}
}
bool Restaurant::GetCooksFor_Urgent_VIP(int CurrentTimeStep)
{
Order** UrgOrder;
Cook* urgentcook;
float cookprio;
bool found = false;
if (QUrgentOrders.peekFront(UrgOrder))
{
if (VcooksQ.isEmpty() && GcooksQ.isEmpty() && NcooksQ.isEmpty())
{
if (CooksInBreak.peekFront(urgentcook, cookprio)) //When waiting time exceeds VIP_WT, we check for
{ // is there is Cooks in break queue
CooksInBreak.dequeue(urgentcook, cookprio);
if (urgentcook->GetType() == TYPE_VIP) //return the cook to it's suitable list
VcooksQ.enqueue(urgentcook);
if (urgentcook->GetType() == TYPE_VGAN)
GcooksQ.enqueue(urgentcook);
if (urgentcook->GetType() == TYPE_NRM)
NcooksQ.enqueue(urgentcook);
found = true;
} //if there is no cooks in break we check for
else if (CooksInRest.peekFront(urgentcook)) //the cooks in rest but they work with half speed
{
CooksInRest.dequeue(urgentcook);
urgentcook->Give_Urg(true);
if (urgentcook->GetType() == TYPE_VIP)
VcooksQ.enqueue(urgentcook);
if (urgentcook->GetType() == TYPE_VGAN)
GcooksQ.enqueue(urgentcook);
if (urgentcook->GetType() == TYPE_NRM)
NcooksQ.enqueue(urgentcook);
found = true;
}
}
else
found = true;
}
return found;
}
void Restaurant::Serve_Urgent_VIP(int CurrentTimeStep)
{
bool flag;
CheckUrgentOrders(CurrentTimeStep);
Order** Urgorder;
UFinfo = "";
while (QUrgentOrders.peekFront(Urgorder))
{
flag = GetCooksFor_Urgent_VIP(CurrentTimeStep);
if (flag)
{
UFinfo = "Urgent-> ";
Cook* Bcook;
if (VcooksQ.dequeue(Bcook)) //check if there is available VIP cook
{
Bcook->setnumofOrderdServed(Bcook->getnumofOrderdServed() + 1);
(*Urgorder)->setServTime(CurrentTimeStep); //set serving time with current time step
int ST = ceil(float((*Urgorder)->getOrderSize()) / Bcook->getSpeed()); //calculate the surving time
(*Urgorder)->setServInt(ST);
(*Urgorder)->setWaitTime();
(*Urgorder)->setFinishTime();
(*Urgorder)->setStatus(SRV);
float priority = ((*Urgorder)->getFinishTime()); //set the priority of serving queue with the inverted finished time
Bcook->assign_Order((*Urgorder)->GetID());
InServing.enqueue(*Urgorder, priority);
busyCooksQ.enqueue(Bcook, priority); //enque the cook in priority busy cook queue
QUrgentOrders.dequeue(Urgorder);
Userved++;
UFinfo += "V" + to_string(Bcook->GetID()) + "(" + "V" + to_string((*Urgorder)->GetID()) + ") ";
}
else if (NcooksQ.dequeue(Bcook)) //check if there is available Normal cook when there is no VIP
{
Bcook->setnumofOrderdServed(Bcook->getnumofOrderdServed() + 1);
(*Urgorder)->setServTime(CurrentTimeStep); //set serving time with current time step
int ST = ceil(float((*Urgorder)->getOrderSize()) / Bcook->getSpeed()); //calculate the surving time
(*Urgorder)->setServInt(ST);
(*Urgorder)->setWaitTime();
(*Urgorder)->setFinishTime();
(*Urgorder)->setStatus(SRV);
float priority = ((*Urgorder)->getFinishTime()); //set the priority of serving queue with the inverted finished time
InServing.enqueue(*Urgorder, priority);
Bcook->assign_Order((*Urgorder)->GetID());
busyCooksQ.enqueue(Bcook, priority); //enque the cook in priority busy cook queue
QUrgentOrders.dequeue(Urgorder);
Userved++;
UFinfo += "N" + to_string(Bcook->GetID()) + "(" + "V" + to_string((*Urgorder)->GetID()) + ") ";
}
else if (GcooksQ.dequeue(Bcook)) //check if there is available Vegan cook when there is no VIP&&Normal
{
Bcook->setnumofOrderdServed(Bcook->getnumofOrderdServed() + 1);
(*Urgorder)->setServTime(CurrentTimeStep); //set serving time with current time step
int ST = ceil(float((*Urgorder)->getOrderSize()) / Bcook->getSpeed()); //calculate the surving time
(*Urgorder)->setServInt(ST);
(*Urgorder)->setWaitTime();
(*Urgorder)->setFinishTime();
(*Urgorder)->setStatus(SRV);
float priority = ((*Urgorder)->getFinishTime()); //set the priority of serving queue with the inverted finished time
InServing.enqueue(*Urgorder, priority);
Bcook->assign_Order((*Urgorder)->GetID());
busyCooksQ.enqueue(Bcook, priority); //enque the cook in priority busy cook queue
QUrgentOrders.dequeue(Urgorder);
Userved++;
UFinfo += "G" + to_string(Bcook->GetID()) + "(" + "V" + to_string((*Urgorder)->GetID()) + ") ";
}
else
{
return; //there is no more available cooks in this timestep
}
}
else
return;
}
}
void Restaurant::serve_VIP_orders(int CurrentTimeStep)
{
Order* proOrder;
float prio;
VFinfo = "";
while (QVIP_Order.peekFront(proOrder,prio)) //get orders from VIP waiting Queue to be serve
{
if (!proOrder->isUrgent())
{
Cook* Bcook;
if (VcooksQ.dequeue(Bcook)) //check if there is available VIP cook
{
Bcook->setnumofOrderdServed(Bcook->getnumofOrderdServed() + 1);
int ST = ceil(float(proOrder->getOrderSize()) / Bcook->getSpeed()); //calculate the surving time
proOrder->setServInt(ST);
proOrder->Serve(CurrentTimeStep);
float priority = (proOrder->getFinishTime()); //set the priority of serving queue with the inverted finished time
InServing.enqueue(proOrder, priority);
Bcook->assign_Order(proOrder->GetID());
busyCooksQ.enqueue(Bcook, priority); //enque the cook in priority busy cook queue
QVIP_Order.dequeue(proOrder, prio);
Vserved++;
VFinfo += "V" + to_string(Bcook->GetID())+"("+ "V" + to_string(proOrder->GetID())+") ";
}
else if (NcooksQ.dequeue(Bcook)) //check if there is available Normal cook when there is no VIP
{
Bcook->setnumofOrderdServed(Bcook->getnumofOrderdServed() + 1);
int ST = ceil(float(proOrder->getOrderSize()) / Bcook->getSpeed()); //calculate the surving time
proOrder->setServInt(ST);
proOrder->Serve(CurrentTimeStep);
float priority = (proOrder->getFinishTime()); //set the priority of serving queue with the inverted finished time
InServing.enqueue(proOrder, priority);
Bcook->assign_Order(proOrder->GetID());
busyCooksQ.enqueue(Bcook, priority); //enque the cook in priority busy cook queue
QVIP_Order.dequeue(proOrder, prio);
Vserved++;
VFinfo += "N" + to_string(Bcook->GetID()) + "(" + "V" + to_string(proOrder->GetID()) + ") ";
}
else if (GcooksQ.dequeue(Bcook)) //check if there is available Vegan cook when there is no VIP&&Normal
{
Bcook->setnumofOrderdServed(Bcook->getnumofOrderdServed() + 1);
int ST = ceil(float(proOrder->getOrderSize()) / Bcook->getSpeed()); //calculate the surving time
proOrder->setServInt(ST);
proOrder->Serve(CurrentTimeStep);
float priority = (proOrder->getFinishTime()); //set the priority of serving queue with the inverted finished time
InServing.enqueue(proOrder, priority);
Bcook->assign_Order(proOrder->GetID());
busyCooksQ.enqueue(Bcook, priority); //enque the cook in priority busy cook queue
QVIP_Order.dequeue(proOrder, prio);
Vserved++;
VFinfo += "G" + to_string(Bcook->GetID()) + "(" + "V" + to_string(proOrder->GetID()) + ") ";
}
else
{
return; //there is no more available cooks in this timestep
}
}
else
{
QVIP_Order.dequeue(proOrder, prio);
}
}
}
void Restaurant::serve_Vegan_orders(int CurrentTimeStep)
{
Order* proOrder;
GFinfo = "";
while (Qvegan_Order.peekFront(proOrder)) //get orders from Vegan waiting Queue to be serve
{
Cook* Bcook;
if (GcooksQ.dequeue(Bcook)) //check if there is available Vegan cook
{
Bcook->setnumofOrderdServed(Bcook->getnumofOrderdServed() + 1);
int ST = ceil(float(proOrder->getOrderSize() )/ Bcook->getSpeed()); //calculate the surving time
proOrder->setServInt(ST);
proOrder->Serve(CurrentTimeStep);
float priority = (proOrder->getFinishTime()); //set the priority of serving queue with the inverted finished time
InServing.enqueue(proOrder, priority);
Bcook->assign_Order(proOrder->GetID());
busyCooksQ.enqueue(Bcook, priority); //enque the cook in priority busy cook queue
Qvegan_Order.dequeue(proOrder);
Gserved++;
GFinfo += "G" + to_string(Bcook->GetID())+"("+ " G" + to_string(proOrder->GetID())+") ";
}
else
{
return; //there is no more available cooks in this timestep
}
}
}
bool Restaurant::Health_Emergency(int curr_ts)
{
Cook* temp;
float pri_temp;
Order* tempOrd;
int no_dishes_left;
float priority;
if (busyCooksQ.peekFront(temp, pri_temp) && InServing.peekFront(tempOrd, pri_temp)&&temp->Is_injured()==false)
{
busyCooksQ.dequeue(temp, pri_temp);
InServing.dequeue(tempOrd, pri_temp);
no_dishes_left = tempOrd->getOrderSize() - (curr_ts - tempOrd->getServTime()) * temp->getSpeed();
temp->f_speed = (float(temp->getSpeed()) / 2);
temp->setSpeed(temp->getSpeed() / 2);
int ST = curr_ts - tempOrd->getServTime()+ceil(float(no_dishes_left) / (temp->getSpeed())); //calculate the surving time
tempOrd->setServInt(ST);
tempOrd->setFinishTime();
priority = tempOrd->getFinishTime();
temp->set_RstTime(tempOrd->getFinishTime());//set the finish of rest time
temp->injure(true);//make the flag on
busyCooksQ.enqueue(temp, priority);
InServing.enqueue(tempOrd, priority);
injcooksnum++;
return true;
}
else
return false;
}
void Restaurant::serve_Normal_orders(int CurrentTimeStep)
{
Order* proOrder;
NFinfo = "";
while (LNormal_Order.peek(proOrder)) //get orders from Normal list to be serve
{
Cook* Bcook;
if (NcooksQ.dequeue(Bcook)) //check if there is available Normal cook
{
Bcook->setnumofOrderdServed(Bcook->getnumofOrderdServed() + 1);
int ST = ceil(float(proOrder->getOrderSize()) / Bcook->getSpeed()); //calculate the surving time
proOrder->setServInt(ST);
proOrder->Serve(CurrentTimeStep);
float priority = (proOrder->getFinishTime()); //set the priority of serving queue with the inverted finished time
Bcook->assign_Order(proOrder->GetID());
InServing.enqueue(proOrder, priority);
busyCooksQ.enqueue(Bcook, priority); //enque the cook in priority busy cook queue
LNormal_Order.DeleteFirst(proOrder);
Nserved++;
NFinfo += "N" + to_string(Bcook->GetID())+"("+ " N" + to_string(proOrder->GetID())+") ";
}
else if (VcooksQ.dequeue(Bcook)) //check if there is available VIP cook when there is no Normal
{
Bcook->setnumofOrderdServed(Bcook->getnumofOrderdServed() + 1);
int ST = ceil(float(proOrder->getOrderSize() )/ Bcook->getSpeed()); //calculate the surving time
proOrder->setServInt(ST);
proOrder->Serve(CurrentTimeStep);
float priority = (proOrder->getFinishTime()); //set the priority of serving queue with the inverted finished time
InServing.enqueue(proOrder, priority);
Bcook->assign_Order(proOrder->GetID());
busyCooksQ.enqueue(Bcook, priority); //enque the cook in priority busy cook queue
LNormal_Order.DeleteFirst(proOrder);
Nserved++;
NFinfo += "V" + to_string(Bcook->GetID()) + "(" + " N" + to_string(proOrder->GetID()) + ") ";
}
else
{
return; //there is no more available cooks in this timestep
}
}
}
void Restaurant::getfrombusyCookQ(int CurrentTimeStep)
{
Cook* Acook;
float priority;
while (busyCooksQ.peekFront(Acook, priority))
{
if ((priority) <= CurrentTimeStep && Acook->Is_injured() == true&&Acook->Has_Urg()==false)
{
busyCooksQ.dequeue(Acook, priority);
if (Acook->getnumofOrderdServed() == Acook->getNumOrdBbreak())
Acook->setnumofOrderdServed(0);
CooksInRest.enqueue(Acook);
}
else if((priority) <= CurrentTimeStep && Acook->getnumofOrderdServed() == Acook->getNumOrdBbreak()) //the cook servesed number of orders it should take break
{
busyCooksQ.dequeue(Acook, priority);
if (Acook->Is_injured() == true && Acook->Has_Urg() == true)
{
Acook->injure(false); ///if he was injured and was assigned to an urgent cook
Acook->Give_Urg(false); ////so its speed is still the half until he has his break
//if (Acook->f_speed != float(Acook->getSpeed()))
float original_speed = Acook->f_speed * 2;
Acook->setSpeed(int(original_speed));
}
Acook->setnumofOrderdServed(0);
float F = (Acook->getBreakDur() + CurrentTimeStep);
CooksInBreak.enqueue(Acook, F);
}
else if (( priority) <= CurrentTimeStep) //Finish time equal the current time step
{
busyCooksQ.dequeue(Acook, priority);
if (Acook->GetType() == TYPE_VIP)
VcooksQ.enqueue(Acook);
if (Acook->GetType() == TYPE_VGAN)
GcooksQ.enqueue(Acook);
if (Acook->GetType() == TYPE_NRM)
NcooksQ.enqueue(Acook);
}
else
{
return; //there is no more finished cooks
}
}
}
void Restaurant::getfromBreakCookQ(int CurrentTimeStep)
{
Cook* Acook;
float priority;
while (CooksInBreak.peekFront(Acook, priority))
{
if ((priority) <= CurrentTimeStep) //If there is a cooks finished it's break
{
CooksInBreak.dequeue(Acook, priority);
if (Acook->GetType() == TYPE_VIP)
VcooksQ.enqueue(Acook);
if (Acook->GetType() == TYPE_VGAN)
GcooksQ.enqueue(Acook);
if (Acook->GetType() == TYPE_NRM)
NcooksQ.enqueue(Acook);
}
else
{
return; //there is no more cooks finished it's break
}
}
}
void Restaurant::getfromInServingQ(int CurrentTimeStep)
{
Order* proOrder;
float prio;
while (InServing.peekFront(proOrder, prio))
{
if (prio > CurrentTimeStep)
return; //there is no more finished orders
InServing.dequeue(proOrder, prio);
proOrder->setStatus(DONE);
FinishedList.enqueue(proOrder);
}
}
void Restaurant::getfromRestCookQ(int CurrentTimeStep)
{
Cook* Rcook;
while (CooksInRest.peekFront(Rcook))
{
if ((Rcook->get_rstTime()) <= CurrentTimeStep) //check if there is a cooks finished his rest time
{
CooksInRest.dequeue(Rcook);
Rcook->injure(false);
//if(Rcook->f_speed!=float(Rcook->getSpeed()))
float original_speed = Rcook->f_speed * 2;
Rcook->setSpeed(int(original_speed));
switch (Rcook->GetType())
{
case TYPE_VIP:
VcooksQ.enqueue(Rcook);
break;
case TYPE_VGAN:
GcooksQ.enqueue(Rcook);
break;
case TYPE_NRM:
NcooksQ.enqueue(Rcook);
break;
default:
break;
}
}
else
{
return; //there is no more cooks finished their rest
}
}
}
Restaurant::~Restaurant()
{
if (pGUI)
delete pGUI;
}
//Filling GUI with Orders and Cooks of All types
void Restaurant::FillDrawingList()
{
//Converting The Cooks Q to Array to iterate on it and add cooks to drawing list
Cook** pC= NcooksQ.toArray(NCookNum);
for (int i = 0; i < NCookNum; i++)
{
pGUI->AddToDrawingList(pC[i]);
}
pC = GcooksQ.toArray(GCookNum);
for (int i = 0; i < GCookNum; i++)
{
pGUI->AddToDrawingList(pC[i]);
}
pC = VcooksQ.toArray(VCookNum);
for (int i = 0; i < VCookNum; i++)
{
pGUI->AddToDrawingList(pC[i]);
}
/////////////////////////////////////////
//end of drawing all cooks types
//////////////////////////////////////
//Converting The Orders Q to Array to iterate on it and add ordrs to drawing list
Order** pON= LNormal_Order.toArray(NWaitNum);
for (int i = 0; i < NWaitNum;i++)
pGUI->AddToDrawingList(pON[i]);
Order** pOG = Qvegan_Order.toArray(GWaitNum);
for (int i = 0; i < GWaitNum ;i++)
pGUI->AddToDrawingList(pOG[i]);
int usize = 0;
Order*** PU = QUrgentOrders.toArray(usize);
for (int i = 0; i < usize; i++)
pGUI->AddToDrawingList(*PU[i]);
Order** pOV = QVIP_Order.toArray(VWaitNum);
for (int i = 0; i < VWaitNum;i++)
{
if(!pOV[i]->isUrgent())
pGUI->AddToDrawingList(pOV[i]);
}
int size = 0;
Order** SO = InServing.toArray(SRVorders);
for (int i = 0; i < SRVorders;i++)
pGUI->AddToDrawingList(SO[i]);
size = 0;
Order** FD = FinishedList.toArray(size);
for (int i = 0; i < size;i++)
pGUI->AddToDrawingList(FD[i]);
}
/////////////////////////////////////////////////////
//Reading inputs from File and filling suitable lists
/////////////////////////////////////////////////////
void Restaurant::fileLoading()
{
pGUI->PrintMessage("Enter input file name","<NAME>");
IPfilename = pGUI->GetString();
ifstream InFile(IPfilename);
if (InFile.is_open())
{
InFile >> numNcooks >> numGcooks >> numVcooks >> Ncookspeed_min>> Ncookspeed_max>> Gcookspeed_min>> Gcookspeed_max>> Vcookspeed_min>> Vcookspeed_max;
InFile >> numOrdersBbreak >> Nbreak_min>> Nbreak_max>> Gbreak_min>> Gbreak_max>> Vbreak_min>> Vbreak_max >> InjProp >> RstPrd >> AutoP>> VIP_WT>>numofevents;
int numAllcooks = numNcooks + numGcooks + numVcooks;
int* arrCIDs = new int[numAllcooks+1];
for (int i = 1; i <= numAllcooks; i++)
{
arrCIDs[i] = i;
}
srand((unsigned)time(0));
for (int i = 0; i < numNcooks; i++)
{
Cook* newNCook = new Cook();
newNCook->setID(arrCIDs[i + 1]);
newNCook->setType(TYPE_NRM);
newNCook->setSpeed(rangeRandomAlg2(Ncookspeed_min, Ncookspeed_max));
newNCook->setNumOrdBbreak(numOrdersBbreak);
newNCook->setBreakDur(rangeRandomAlg2(Nbreak_min, Nbreak_max));
newNCook->set_RstPrd(RstPrd);
newNCook->setnumofOrderdServed(0);
NcooksQ.enqueue(newNCook);
}
for (int i = 0; i < numGcooks; i++)
{
Cook* newGCook = new Cook;
newGCook->setID(arrCIDs[i + numNcooks + 1]);
newGCook->setType(TYPE_VGAN);
newGCook->setSpeed(rangeRandomAlg2(Gcookspeed_min, Gcookspeed_max));
newGCook->setNumOrdBbreak(numOrdersBbreak);
newGCook->setBreakDur(rangeRandomAlg2(Gbreak_min, Gbreak_max));
newGCook->set_RstPrd(RstPrd);
newGCook->setnumofOrderdServed(0);
GcooksQ.enqueue(newGCook);
}
for (int i = 0; i < numVcooks; i++)
{
Cook* newVCook = new Cook;
newVCook->setID(arrCIDs[i + numNcooks + numGcooks + 1]);
newVCook->setType(TYPE_VIP);
newVCook->setSpeed(rangeRandomAlg2(Vcookspeed_min, Vcookspeed_max));
newVCook->setNumOrdBbreak(numOrdersBbreak);
newVCook->setBreakDur(rangeRandomAlg2(Vbreak_min, Vbreak_max));
newVCook->set_RstPrd(RstPrd);
newVCook->setnumofOrderdServed(0);
VcooksQ.enqueue(newVCook);
}
for (int i = 0; i < numofevents; i++)
{
char typeofevent;
InFile >> typeofevent;
Event* pEv;
if (typeofevent == 'R')
{
char ordertype;
int Ordertype, arrivaltime, ID, Size;
double Mony;
InFile >> ordertype>>arrivaltime>> ID>> Size>> Mony;
if (ordertype == 'N')
{
pEv = new ArrivalEvent(arrivaltime, ID, TYPE_NRM, Size, Mony);
originalNormOrdCount++;
}
else if (ordertype == 'G')
pEv = new ArrivalEvent(arrivaltime, ID, TYPE_VGAN, Size, Mony);
else if (ordertype == 'V')
pEv = new ArrivalEvent(arrivaltime, ID, TYPE_VIP, Size, Mony);
}
if (typeofevent == 'P')
{
int promotiontime, ID;
double exmony;
InFile >> promotiontime >> ID >> exmony;
pEv = new PromotionEvent(promotiontime,ID,exmony);
}
if (typeofevent == 'X')
{
int cancellationtime, ID;
InFile >> cancellationtime >> ID;
pEv = new CancellationEvent(cancellationtime, ID);
originalNormOrdCount--;
}
EventsQueue.enqueue(pEv);
}
}
}
void Restaurant::AddtoVIPQueue(Order*& po)
{
po->setPriority();
float priority = po->getPriority();
QVIP_Order.enqueue(po, priority);
}
void Restaurant::AddtoNOList(Order*& po)
{
LNormal_Order.InsertEnd(po);
}
void Restaurant::AddtoVEQueue(Order*& po)
{
Qvegan_Order.enqueue(po);
}
void Restaurant::cancellorder(int Id)
{
Order* del;
Node<Order*>* prv = LNormal_Order.getHead();
if (prv&&prv->getItem()->GetID() == Id)
LNormal_Order.DeleteFirst(del);
else if(prv)
{
Node<Order*>* Head = prv->getNext();
while (Head)
{
if (Head->getItem()->GetID() == Id)
{
if (!Head->getNext())
{
LNormal_Order.settail(prv);
}
prv->setNext(Head->getNext());
delete Head;
break;
}
else
{
prv = Head;
Head = Head->getNext();
}
}
}
}
void Restaurant::promoteorder(int Id, double exmoney)
{
Node<Order*>* prv = LNormal_Order.getHead();
if (!prv)
return;
if (prv->getItem()->GetID() == Id)
{
Order* proOrder;
LNormal_Order.DeleteFirst(proOrder);
proOrder->Promote(exmoney);
float priority = proOrder->getPriority();
QVIP_Order.enqueue(proOrder, priority);
return;
}
else if (prv->getNext())
{
while (prv->getNext()->getNext())
{
if (prv->getNext()->getItem()->GetID() == Id)
{
Order* proOrder;
Node<Order*>* temp = new Node<Order*>;
temp = prv->getNext();
prv->setNext(temp->getNext());
proOrder = temp->getItem();
proOrder->Promote(exmoney);
float priority = proOrder->getPriority();
QVIP_Order.enqueue(proOrder, priority);
delete temp;
return;
}
else
prv = prv->getNext();
}
if (prv && prv->getNext() && prv->getNext()->getItem()->GetID() == Id)
{
Order* proOrder;
LNormal_Order.DeleteLast( proOrder);
proOrder->Promote(exmoney);
float priority = proOrder->getPriority();
QVIP_Order.enqueue(proOrder, priority);
return;
}
}
return; ///if ID isn't in Qnormal
}
void Restaurant::Restaurant_Modes(int Mode)
{
bool injured;
srand((int)time(0));
if (Mode == 1)
{
pGUI->PrintMessage("Welcome To Our Restaurant .... Interactive Mode, Click To Continue","M<NAME>");
pGUI->waitForClick();
fileLoading();
int CurrentTimeStep = 1;
while (!EventsQueue.isEmpty() || !InServing.isEmpty() || !QVIP_Order.isEmpty() || !Qvegan_Order.isEmpty() || !LNormal_Order.isEmpty())
{
pGUI->ClearStatusBar();
char timestep[100];
itoa(CurrentTimeStep, timestep, 10);
pGUI->PrintMessage(timestep, 1);
ExecuteEvents(CurrentTimeStep);
getfromBreakCookQ(CurrentTimeStep);
getfrombusyCookQ(CurrentTimeStep);
getfromInServingQ(CurrentTimeStep);
float R= static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
if (R <= InjProp)
{
injured = Health_Emergency(CurrentTimeStep);
}
getfromRestCookQ(CurrentTimeStep);
Serve_Urgent_VIP(CurrentTimeStep);
Executepromotion(CurrentTimeStep);
serve_VIP_orders(CurrentTimeStep);
serve_Vegan_orders(CurrentTimeStep);
serve_Normal_orders(CurrentTimeStep);
FillDrawingList();
//Printing Cooks and Orders Information
pGUI->PrintMessage("Wating Orders -> Normal : " + to_string(NWaitNum) + " Vegan :" + to_string(GWaitNum) + " VIP : " + to_string(VWaitNum), 2);
pGUI->PrintMessage("Available Cooks - > Normal : " + to_string(NCookNum) + " Vegan :" + to_string(GCookNum) + " VIP :" + to_string(VCookNum), 3);
if(!UFinfo.empty()||!VFinfo.empty()||!GFinfo.empty() ||!NFinfo.empty())
pGUI->PrintMessage(UFinfo+VFinfo +GFinfo+NFinfo, 4);
else
pGUI->PrintMessage("No Served Orders", 4);
pGUI->PrintMessage("Total Served Orders Till Now-> Normal : " + to_string(Nserved) + " Vegan :" + to_string(Gserved) + " VIP :" + to_string(Vserved)+" Urgent :"+to_string(Userved), 5);
pGUI->UpdateInterface();
pGUI->waitForClick();
CurrentTimeStep++;
pGUI->ResetDrawingList();
}
while (!CooksInBreak.isEmpty() || !CooksInRest.isEmpty())
{
pGUI->PrintMessage("No More Orders...Please Do More Clicks, Some Cooks are in {Break, Rest}","Maiandra GD");
getfromBreakCookQ(CurrentTimeStep);
getfrombusyCookQ(CurrentTimeStep);
getfromRestCookQ(CurrentTimeStep);
FillDrawingList();
pGUI->UpdateInterface();
pGUI->ResetDrawingList();
pGUI->waitForClick();
CurrentTimeStep++;
}
outputFileLoading();
}
else if (Mode == 2)
{
pGUI->PrintMessage("Welcome To Our Restaurant .... Step-by-Step Mode, Click To Continue","<NAME>");
pGUI->waitForClick();
fileLoading();
int CurrentTimeStep = 1;
while (!EventsQueue.isEmpty() || !InServing.isEmpty()||!QVIP_Order.isEmpty()|| !Qvegan_Order.isEmpty() ||!LNormal_Order.isEmpty())
{
pGUI->ClearStatusBar();
char timestep[100];
itoa(CurrentTimeStep, timestep, 10);
pGUI->PrintMessage(timestep, 1);
ExecuteEvents(CurrentTimeStep);
getfromBreakCookQ(CurrentTimeStep);
getfrombusyCookQ(CurrentTimeStep);
getfromInServingQ(CurrentTimeStep);
float R = RandomFloat(0.0,1.0);
if (R <= InjProp)
{
injured = Health_Emergency(CurrentTimeStep);
}
getfromRestCookQ(CurrentTimeStep);
Serve_Urgent_VIP(CurrentTimeStep);
Executepromotion(CurrentTimeStep);
serve_VIP_orders(CurrentTimeStep);
serve_Vegan_orders(CurrentTimeStep);
serve_Normal_orders(CurrentTimeStep);
FillDrawingList();
//Printing Cooks and Orders Information
pGUI->PrintMessage("Wating Orders -> Normal : " + to_string(NWaitNum) + " Vegan :" + to_string(GWaitNum) + " VIP : " + to_string(VWaitNum), 2);
pGUI->PrintMessage("Available Cooks - > Normal : " + to_string(NCookNum) + " Vegan :" + to_string(GCookNum) + " VIP :" + to_string(VCookNum), 3);
if (!UFinfo.empty() || !VFinfo.empty() || !GFinfo.empty() || !NFinfo.empty())
pGUI->PrintMessage(UFinfo + VFinfo + GFinfo + NFinfo, 4);
else
pGUI->PrintMessage("No Served Orders", 4);
pGUI->PrintMessage("Total Served Orders Till Now-> Normal : " + to_string(Nserved) + " Vegan :" + to_string(Gserved) + " VIP :" + to_string(Vserved) + " Urgent :" + to_string(Userved), 5);
pGUI->UpdateInterface();
Sleep(1000);
CurrentTimeStep++;
pGUI->ResetDrawingList();
}
while (!CooksInBreak.isEmpty() || !CooksInRest.isEmpty())
{
pGUI->PrintMessage("No More Orders...Please Wait, Some Cooks are in{ Break, Rest }","Maiandra GD");
getfromBreakCookQ(CurrentTimeStep);
getfrombusyCookQ(CurrentTimeStep);
getfromRestCookQ(CurrentTimeStep);
FillDrawingList();
pGUI->UpdateInterface();
pGUI->ResetDrawingList();
Sleep(1000);
CurrentTimeStep++;
}
outputFileLoading();
}
else if (Mode == 3)
{
pGUI->PrintMessage("Welcome To Our Restaurant .... Silent Mode, Click To Continue","Maiandra GD");
pGUI->waitForClick();
fileLoading();
int CurrentTimeStep = 1;
while (!EventsQueue.isEmpty() || !InServing.isEmpty() || !QVIP_Order.isEmpty() || !Qvegan_Order.isEmpty() || !LNormal_Order.isEmpty()|| !CooksInBreak.isEmpty() || !CooksInRest.isEmpty())
{
ExecuteEvents(CurrentTimeStep);
getfromBreakCookQ(CurrentTimeStep);
getfrombusyCookQ(CurrentTimeStep);
getfromInServingQ(CurrentTimeStep);
getfromRestCookQ(CurrentTimeStep);
Serve_Urgent_VIP(CurrentTimeStep);
float R = static_cast <float> (rand()) / static_cast <float> (RAND_MAX);
if (R <= InjProp)
{
injured = Health_Emergency(CurrentTimeStep);
}
Executepromotion(CurrentTimeStep);
serve_VIP_orders(CurrentTimeStep);
serve_Vegan_orders(CurrentTimeStep);
serve_Normal_orders(CurrentTimeStep);
CurrentTimeStep++;
}
outputFileLoading();
}
pGUI->PrintMessage("End of Simulation....Click to Exit","Maiandra GD");
pGUI->waitForClick();
}
void Restaurant::outputFileLoading()
{
pGUI->PrintMessage("Enter output file name","Maiandra GD");
OPfilename = pGUI->GetString();
ofstream OutFile(OPfilename);
float totalwaittime = 0;
float totalServtime = 0;
int ordsCount = Nserved + Vserved + Gserved;
int cooksCount = numNcooks + numGcooks + numVcooks;
Order** FinishedOrdsArray = FinishedList.toArray(ordsCount);
if (OutFile.is_open())
{
OutFile << "FT ID AT WT ST" << endl;
for (int i = 0; i < ordsCount; i++)
{
for (int j = 0; j < ordsCount - 1; j++)
{
if (FinishedOrdsArray[j]->getFinishTime() == FinishedOrdsArray[j + 1]->getFinishTime())
{
if (FinishedOrdsArray[j]->getServInt() > FinishedOrdsArray[j + 1]->getServInt())
{
Order* temp = FinishedOrdsArray[j];
FinishedOrdsArray[j] = FinishedOrdsArray[j + 1];
FinishedOrdsArray[j + 1] = temp;
}
}
}
}
for (int i = 0; i < ordsCount; i++)
{
OutFile << FinishedOrdsArray[i]->getFinishTime() << " "
<< FinishedOrdsArray[i]->GetID() << " "
<< FinishedOrdsArray[i]->getArrTime() << " "
<< FinishedOrdsArray[i]->getWaitTime() << " "
<< FinishedOrdsArray[i]->getServInt() << endl;
totalwaittime = totalwaittime + FinishedOrdsArray[i]->getWaitTime();
totalServtime = totalServtime + FinishedOrdsArray[i]->getServInt();
}
OutFile << "Orders: " << ordsCount << " [Norm:" << Nserved << ", Veg:" << Gserved << ", VIP:" << Vserved << "]" << endl;
OutFile << "cooks: " << cooksCount << " [Norm:" << numNcooks << ", Veg:" << numGcooks << ", VIP:" << numVcooks
<< ", injured:" << injcooksnum << "]" << endl;
if (ordsCount != 0)
{
OutFile << "Avg Wait = " << totalwaittime / ordsCount
<< ", Avg Serv = " << totalServtime / ordsCount << endl;
}
OutFile << "Urgent orders: " << UrgentOredersNum;
if (originalNormOrdCount != 0)
{
OutFile<< ", Auto-promoted: " << (1 - ((originalNormOrdCount - numAutoPromOrders) / originalNormOrdCount)) * 100 << "%";
}
}
for (int i = 0; i < ordsCount; i++)
{
delete FinishedOrdsArray[i];
}
}
<file_sep>#pragma once
#include "Event.h"
class CancellationEvent:public Event
{
//there is no more data
public:
CancellationEvent(int Time, int ID);
virtual void Execute(Restaurant* pRest); //override execute function
};
<file_sep>#include "GUI.h"
//////////////////////////////////////////////////////////////////////////////////////////
GUI::GUI()
{
int L = WindWidth / 2;
DrawingItemsCount = 0;
pWind = new window(WindWidth - 300, WindHeight - 120, 0, 0);
pWind->ChangeTitle("The Restautant");
//Set color for each order type
DrawingColors[TYPE_NRM] = RED; //normal-order color
DrawingColors[TYPE_VGAN] = DARKBLUE; //vegan-order color
DrawingColors[TYPE_VIP] = VIOLETRED; //VIP-order color
pWind->DrawImage("GUI\\bggg.jpg", 0, MenuBarHeight, WindWidth - 300, WindHeight - 120);
int x, y;
pWind->WaitMouseClick(x, y);
delete pWind;
pWind = new window(WindWidth +15, WindHeight, 0, 0);
ClearStatusBar();
ClearDrawingArea();
DrawRestArea();
}
//////////////////////////////////////////////////////////////////////////////////////////
GUI::~GUI()
{
delete pWind;
}
//////////////////////////////////////////////////////////////////////////////////////////
// ================================== INPUT FUNCTIONS ====================================
//////////////////////////////////////////////////////////////////////////////////////////
void GUI::waitForClick() const
{
int x, y;
pWind->WaitMouseClick(x, y); //Wait for mouse click
}
//////////////////////////////////////////////////////////////////////////////////////////
string GUI::GetString() const
{
string Label;
char Key;
while (1)
{
pWind->WaitKeyPress(Key);
if (Key == 27) //ESCAPE key is pressed
return ""; //returns nothing as user has cancelled label
if (Key == 13) //ENTER key is pressed
return Label;
if ((Key == 8) && (Label.size() >= 1)) //BackSpace is pressed
Label.resize(Label.size() - 1);
else
Label += Key;
PrintMessage(Label,"Maiandra GD");
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// ================================== OUTPUT FUNCTIONS ===================================
//////////////////////////////////////////////////////////////////////////////////////////
void GUI::PrintMessage(string msg,char* font) const //Prints a message on status bar
{
ClearStatusBar(); //First clear the status bar
pWind->SetPen(Yellow);
pWind->SetFont(32,PLAIN, BY_NAME,font);
pWind->DrawString1(10, WindHeight - (int)(StatusBarHeight / 1.5), msg); // You may need to change these coordinates later
// to be able to write multi-line
}
void GUI::PrintMessage2(string msg, char* font) const //Prints a message on status bar
{
pWind->SetPen(Yellow);
pWind->SetFont(32, PLAIN, BY_NAME, font);
pWind->DrawString1(10, WindHeight - (int)(StatusBarHeight / 1.5), msg); // You may need to change these coordinates later
// to be able to write multi-line
}
void GUI::PrintMessage(string msg, int line) const
{
pWind->SetPen(DARKBLUE);
pWind->SetFont(20, BOLD, BY_NAME, "Times New Roman");
if (line == 1)
{
//ClearStatusBar(1);
pWind->DrawString(10, WindHeight - (int)(StatusBarHeight / 1.1), msg);
}
if (line == 2)
{
//ClearStatusBar(2);
pWind->DrawString(10, WindHeight - (int)(StatusBarHeight / 1.3), msg);
}
if (line == 3)
{
//ClearStatusBar(3);
pWind->DrawString(10, WindHeight - (int)(StatusBarHeight /1.6), msg);
}
if (line == 4)
{
//ClearStatusBar(4);
pWind->DrawString(10, WindHeight - (int)(StatusBarHeight / 2.11), msg);
}
if (line == 5)
{
//ClearStatusBar(5);
pWind->DrawString(10, WindHeight - (int)(StatusBarHeight / 2.95), msg);
}
}
//////////////////////////////////////////////////////////////////////////////////////////
void GUI::DrawString(const int iX, const int iY, const string Text)
{
pWind->SetPen(BROWN);
pWind->SetFont(22, BOLD, BY_NAME, "Arial");
pWind->DrawString(iX, iY, Text);
}
void GUI::DrawString1(const int iX, const int iY, const string Text)
{
pWind->SetPen(Yellow);
pWind->SetFont(22, BOLD, BY_NAME, "Lucida Console");
pWind->DrawString1(iX, iY, Text);
}
//////////////////////////////////////////////////////////////////////////////////////////
void GUI::ClearStatusBar() const
{
/*pWind->SetPen(WHITE, 3);
pWind->SetBrush(WHITE);
pWind->DrawRectangle(0, WindHeight - StatusBarHeight , WindWidth, WindHeight); */
pWind->DrawImage("GUI\\d.jpg", 0, WindHeight - StatusBarHeight, WindWidth+2, StatusBarHeight);
pWind->SetPen(DARKBLUE, 3);
pWind->DrawLine(0, WindHeight - StatusBarHeight, WindWidth, WindHeight - StatusBarHeight);
}
///////////////////////////////////////////////////////////////////////////////////
void GUI::ClearDrawingArea() const
{
// Clearing the Drawing area
//pWind->SetPen(PINK, 3);
//pWind->SetBrush(PINK);
//pWind->DrawRectangle(0, MenuBarHeight, WindWidth, WindHeight - StatusBarHeight);
pWind->DrawImage("GUI\\waiting3.jpg", 0, MenuBarHeight, (WindWidth / 2)-1, (WindHeight - StatusBarHeight) / 2-60);
pWind->DrawImage("GUI\\waiting3-2.jpg", 0, MenuBarHeight + (WindHeight - StatusBarHeight) / 2-60, WindWidth / 2-60,59);
pWind->DrawImage("GUI\\chef.jpg", WindWidth / 2+2, MenuBarHeight, WindWidth / 2, (WindHeight - StatusBarHeight) / 2-60);
pWind->DrawImage("GUI\\chef-2.jpg", WindWidth / 2+61, MenuBarHeight + (WindHeight - StatusBarHeight) / 2 - 60, WindWidth / 2-58,59);
pWind->DrawImage("GUI\\6.jpg", -1, MenuBarHeight + ((WindHeight - StatusBarHeight) / 2)+60, WindWidth / 2, (WindHeight - StatusBarHeight) / 2-61);
pWind->DrawImage("GUI\\6-2.jpg", -1, MenuBarHeight + ((WindHeight - StatusBarHeight) / 2) + 1, WindWidth / 2-60, 60);
pWind->DrawImage("GUI\\38.jpg", WindWidth / 2+2, MenuBarHeight + (WindHeight - StatusBarHeight) / 2 +60, WindWidth / 2+1, (WindHeight - StatusBarHeight) / 2-61);
pWind->DrawImage("GUI\\38-2.jpg", WindWidth / 2+60, MenuBarHeight + (WindHeight - StatusBarHeight) / 2 + 1, WindWidth / 2 - 59, 60);
}
void GUI::ClearStatusBar(int line) const
{
pWind->SetPen(WHITE, 3);
pWind->SetBrush(WHITE);
if (line == 1)
pWind->DrawImage("GUI\\d.jpg",0, WindHeight - StatusBarHeight, WindWidth, WindHeight - (int)(StatusBarHeight / 1.3));
if (line == 2)
pWind->DrawImage("GUI\\d.jpg",0, WindHeight - (int)(StatusBarHeight / 1.3), WindWidth, WindHeight - (int)(StatusBarHeight / 1.5));
if (line == 3)
pWind->DrawImage("GUI\\d.jpg",0, WindHeight - (int)(StatusBarHeight / 1.56), WindWidth, WindHeight - (int)(StatusBarHeight / 1.9));
if (line == 4)
pWind->DrawImage("GUI\\d.jpg",0, WindHeight - (int)(StatusBarHeight / 1.9), WindWidth, WindHeight - (int)(StatusBarHeight / 2.7));
if (line == 5)
pWind->DrawImage("GUI\\d.jpg",0, WindHeight - (int)(StatusBarHeight / 3), WindWidth, WindHeight - (int)(StatusBarHeight / 4));
pWind->SetPen(DARKBLUE, 3);
pWind->DrawLine(0, WindHeight - StatusBarHeight, WindWidth, WindHeight - StatusBarHeight);
}
///////////////////////////////////////////////////////////////////////////////////
void GUI::DrawRestArea() const
{
int L = RestWidth / 2;
// 1- Drawing the brown square of the Rest
pWind->SetPen(DARKBLUE);
pWind->SetBrush(Yellow);
pWind->DrawRectangle(RestStartX, RestStartY, RestEndX, RestEndY);
// 2- Drawing the 2 brown crossed lines (for making 4 regions)
pWind->SetPen(DARKBLUE, 3);
pWind->DrawLine(0, YHalfDrawingArea, WindWidth, YHalfDrawingArea);
pWind->DrawLine(WindWidth / 2, MenuBarHeight, WindWidth / 2, WindHeight - StatusBarHeight);
// 3- Drawing the 2 white crossed lines (inside the Rest)
pWind->SetPen(DARKBLUE);
pWind->DrawLine(WindWidth / 2, YHalfDrawingArea - RestWidth / 2, WindWidth / 2, YHalfDrawingArea + RestWidth / 2);
pWind->DrawLine(WindWidth / 2 - RestWidth / 2, YHalfDrawingArea, WindWidth / 2 + RestWidth / 2, YHalfDrawingArea);
// 4- Drawing the 4 white squares inside the Rest (one for each region)
/*pWind->SetPen(WHITE);
pWind->SetBrush(WHITE);
pWind->DrawRectangle(RestStartX , RestStartY , RestStartX + 2*L/2, RestStartY + 2*L/2);
pWind->DrawRectangle(RestStartX + L/3, RestEndY - L/3, RestStartX + 2*L/3, RestEndY - 2*L/3);
pWind->DrawRectangle(RestEndX - 2*L/3, RestStartY + L/3, RestEndX - L/3, RestStartY + 2*L/3);
pWind->DrawRectangle(RestEndX - 2*L/3, RestEndY - L/3, RestEndX - L/3, RestEndY - 2*L/3);*/
// 5- Writing regions labels
pWind->SetPen(DARKBLUE);
pWind->SetFont(22, PLAIN, BY_NAME, "jokerman");
pWind->DrawString1(RestStartX + (int)(0.1 * L), RestStartY + 5 * L / 12, "WAIT");
pWind->DrawString1(WindWidth / 2 + (int)(0.1 * L), RestStartY + 5 * L / 12, "COOK");
pWind->DrawString1(WindWidth / 2 + (int)(0.1 * L), YHalfDrawingArea + 5 * L / 12, "SRVG");
pWind->DrawString1(RestStartX + (int)(0.1 * L), YHalfDrawingArea + 5 * L / 12, "DONE");
}
//////////////////////////////////////////////////////////////////////////////////////////
//Draws the passed item in its region
//region count in the numbers of items drawn so far in that item's region
void GUI::DrawSingleItem(const DrawingItem* pDitem, int RegionCount) const // It is a private function
{
if (RegionCount > MaxRegionOrderCount)
return; //no more items can be drawn in this region
int DrawDistance = RegionCount;
int YPos = 1;
if (RegionCount >= MaxHorizOrders) //max no. of orders to draw in one line
{
DrawDistance = (RegionCount - 1) % MaxHorizOrders + 1;
YPos = (RegionCount - 1) / MaxHorizOrders + 1;
}
GUI_REGION Region = pDitem->region;
int x, y, refX, refY;
//First calculate x,y position of the order on the output screen
//It depends on the region and the order distance
switch (Region)
{
case ORD_REG:
refX = (WindWidth / 2 - RestWidth / 2);
refY = YHalfDrawingArea - OrderHeight; //
x = refX - DrawDistance * OrderWidth - DrawDistance; //(Distance)
y = refY - YPos * OrderHeight - YPos; // YPos
break;
case COOK_REG:
refX = (WindWidth / 2 + RestWidth / 2);
refY = YHalfDrawingArea - OrderHeight; //
x = refX + (DrawDistance - 1) * OrderWidth + DrawDistance; //(Distance)
y = refY - YPos * OrderHeight - YPos; // YPos
break;
case SRV_REG:
refX = (WindWidth / 2 + RestWidth / 2);
refY = YHalfDrawingArea + OrderHeight; //
x = refX + (DrawDistance - 1) * OrderWidth + DrawDistance; //(Distance)
y = refY + (YPos - 1) * OrderHeight + YPos; // YPos
break;
case DONE_REG:
refX = (WindWidth / 2 - RestWidth / 2);
refY = YHalfDrawingArea + OrderHeight; //
x = refX - DrawDistance * OrderWidth - DrawDistance; //(Distance)
y = refY + (YPos - 1) * OrderHeight + YPos; // YPos
break;
default:
break;
}
// Drawing the item
pWind->SetPen(pDitem->clr);
pWind->SetFont(24, BOLD, BY_NAME,"Lucida Handwriting");
pWind->DrawInteger(x, y, pDitem->ID);
}
//////////////////////////////////////////////////////////////////////////////////////////
/* A function to draw all items in DrawingList and ensure there is no overflow in the drawing*/
void GUI::DrawAllItems()
{
//Prepare counter for each region
int RegionsCounts[REG_CNT] = { 0 }; //initlaize all counters to zero
DrawingItem* pDitem;
for (int i = 0; i < DrawingItemsCount; i++)
{
pDitem = DrawingList[i];
RegionsCounts[pDitem->region]++;
DrawSingleItem(DrawingList[i], RegionsCounts[pDitem->region]);
}
}
void GUI::UpdateInterface()
{
ClearDrawingArea();
DrawRestArea();
DrawAllItems();
}
/*
AddOrderForDrawing: Adds a new item related to the passed Order to the drawing list
*/
void GUI::AddToDrawingList(Order* pOrd)
{
DrawingItem* pDitem = new DrawingItem;
pDitem->ID = pOrd->GetID();
pDitem->clr = DrawingColors[pOrd->GetType()];
ORD_STATUS order_status = pOrd->getStatus();
GUI_REGION reg;
switch (order_status)
{
case WAIT:
reg = ORD_REG; //region of waiting orders
break;
case SRV:
reg = SRV_REG; //region of waiting orders
break;
case DONE:
reg = DONE_REG; //region of waiting orders
break;
}
pDitem->region = reg;
DrawingList[DrawingItemsCount++] = pDitem;
}
void GUI::AddToDrawingList(Cook* pC)
{
DrawingItem* pDitem = new DrawingItem;
pDitem->ID = pC->GetID();
pDitem->clr = DrawingColors[pC->GetType()];
pDitem->region = COOK_REG;
DrawingList[DrawingItemsCount++] = pDitem;
}
void GUI::ResetDrawingList()
{
for (int i = 0; i < DrawingItemsCount; i++)
delete DrawingList[i];
DrawingItemsCount = 0;
}
PROG_MODE GUI::getGUIMode() const
{
PROG_MODE Mode;
PrintMessage("Please select GUI mode: (1)Interactive, (2)StepByStep, (3)Silent");
string S = GetString();
Mode = (PROG_MODE)(atoi(S.c_str()) - 1);
while (Mode < 0 || Mode >= 3)
{
pWind->DrawImage("GUI\\crop.jpg", 0, WindHeight - StatusBarHeight, WindWidth + 2, StatusBarHeight);
pWind->SetPen(DARKBLUE, 3);
pWind->DrawLine(0, WindHeight - StatusBarHeight, WindWidth, WindHeight - StatusBarHeight);
PrintMessage2("Invalid input!, Click to continue ---> " , "Cooper Black" );
waitForClick();
ClearStatusBar();
Mode = getGUIMode();
}
return Mode;
}
|
646e51263ff77f3394eedea4bd6de56cbf4c551c
|
[
"Markdown",
"C++"
] | 17 |
C++
|
DoniaEsawi/Salta3-Burger
|
70d290d77fc7772ac45a44cb8769759de2e42dd2
|
1f1071a731c6119815a3c29fe3f279c8dded5c6f
|
refs/heads/master
|
<repo_name>JeevanLiang/ClockApp<file_sep>/README.md
# ClockApp
A learning exercise!
2019年12月6日
这是我第五天进入ByteDance实习,也是我第五天接触Android。
所以:
***我很菜,如果代码写得不规范,出什么问题请各位大佬指教!***
***我很菜,如果代码写得不规范,出什么问题请各位大佬指教!***
***我很菜,如果代码写得不规范,出什么问题请各位大佬指教!***
(重要事情说三遍)
当前的任务:
1.实现一个会动的时钟⏲️
2.实现卡片式的时间显示
第一步:不用任何自定义属性做一个最简单的自定义时钟view
```Java
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 获取view的宽高
mWidth = getMeasuredWidth();
mHeight = getMeasuredHeight();
sTime.setToNow();
// 画外圆
printCircle(canvas);
printPointer(canvas);
}
//画时钟的外圆
private void printCircle(Canvas canvas) {
Paint paintCircle = new Paint();
paintCircle.setStyle(Paint.Style.STROKE);
paintCircle.setAntiAlias(true);
paintCircle.setStrokeWidth(5);
canvas.drawCircle(mWidth / 2,
mHeight / 2, mWidth / 2.1f, paintCircle);
}
//画指针(时、分、秒)
private void printPointer(Canvas canvas) {
//获取各指针对应角度
float secRot = sTime.second * 6;
float minRot = sTime.minute * 6 + 6 * sTime.second / 60F;
float hrRot = (sTime.hour % 12) * 30 + 30 * minRot / 360F;
//绘制canvas之前调用,保存状态
canvas.save();
//秒针
Paint paintSecond = new Paint();
paintSecond.setStrokeWidth(5);
//这里有三步绘制
//
canvas.rotate(secRot, mWidth / 2, mHeight / 2);
canvas.drawLine(mWidth / 2, mHeight / 2, mWidth / 2, mHeight / 2 - mWidth / 2 + 150,
paintSecond);
canvas.rotate(-secRot, mWidth / 2, mHeight / 2);
//分针
Paint paintMinute = new Paint();
paintMinute.setStrokeWidth(9);
canvas.rotate(minRot, mWidth / 2, mHeight / 2);
canvas.drawLine(mWidth / 2, mHeight / 2, mWidth / 2, mHeight / 2 - mWidth / 2 + 190,
paintMinute);
canvas.rotate(-minRot, mWidth / 2, mHeight / 2);
//时针
Paint paintHour = new Paint();
paintHour.setStrokeWidth(12);
canvas.rotate(hrRot, mWidth / 2, mHeight / 2);
canvas.drawLine(mWidth / 2, mHeight / 2, mWidth / 2, mHeight / 2 - mWidth / 2 + 250,
paintHour);
canvas.rotate(-hrRot, mWidth / 2, mHeight / 2);
canvas.restore();
}
```
第二步:还要求这个时钟是会动的,所以暴露一个public方法可以进行view重绘:
```Java
public void refreshPointer() {
postInvalidate();
}
```
然后用Handler做定时重绘:
```Java
private Runnable updateTime = new Runnable() {
public void run() {
mClockView.refreshPointer();
mClockView.postDelayed(updateTime, 1000);
}
};
//不要忘记要有一个初始的调用
```
做完上面的时钟之后我觉得太丑了,就把view换了以刻度做成环形的形式:
```Java
private void printCircle(Canvas canvas) {
//画圆心
//在中心画一个空心圆,注意这里给的半径是10
Paint paintCenter = new Paint();
paintCenter.setStyle(Paint.Style.STROKE);
paintCenter.setAntiAlias(true);
paintCenter.setStrokeWidth(8);
canvas.drawCircle(mWidth / 2,
mHeight / 2, 10, paintCenter);
// 画刻度
Paint painDegree = new Paint();
painDegree.setStrokeWidth(8);
painDegree.setColor(Color.BLACK);
for (int i = 0; i < 60; i++) {
// 区分整点与非整点
if (i%5 == 0) {
painDegree.setStrokeWidth(7);
canvas.drawLine(mWidth / 2, mHeight / 2 - mWidth / 2,
mWidth / 2, mHeight / 2 - mWidth / 2 + 30,
painDegree);
} else {
painDegree.setStrokeWidth(7);
painDegree.setAlpha(30);
canvas.drawLine(mWidth / 2, mHeight / 2 - mWidth / 2,
mWidth / 2, mHeight / 2 - mWidth / 2 + 30,
painDegree);
}
// 通过旋转画布简化坐标运算
canvas.rotate(6, mWidth / 2, mHeight / 2);
}
}
//画指针(时、分、秒)
private void printPointer(Canvas canvas) {
//获取各指针对应角度
float secRot = sTime.second * 6;
float minRot = sTime.minute * 6 + 6 * sTime.second / 60F;
float hrRot = (sTime.hour % 12) * 30 + 30 * minRot / 360F;
canvas.save();
//秒针
Paint paintSecond = new Paint();
paintSecond.setColor(Color.BLACK);
paintSecond.setStrokeWidth(5);
canvas.rotate(secRot, mWidth / 2, mHeight / 2);
//这里的startY减了10是因为之前的中心圆
canvas.drawLine(mWidth / 2, mHeight / 2 - 10, mWidth / 2, mHeight / 2 - mWidth / 2 + 150,
paintSecond);
canvas.rotate(-secRot, mWidth / 2, mHeight / 2);
//分针
Paint paintMinute = new Paint();
paintMinute.setColor(Color.BLACK);
paintMinute.setStrokeWidth(9);
canvas.rotate(minRot, mWidth / 2, mHeight / 2);
canvas.drawLine(mWidth / 2, mHeight / 2 - 10, mWidth / 2, mHeight / 2 - mWidth / 2 + 190,
paintMinute);
canvas.rotate(-minRot, mWidth / 2, mHeight / 2);
//时针
Paint paintHour = new Paint();
paintHour.setColor(Color.BLACK);
paintHour.setStrokeWidth(12);
canvas.rotate(hrRot, mWidth / 2, mHeight / 2);
canvas.drawLine(mWidth / 2, mHeight / 2 - 10, mWidth / 2, mHeight / 2 - mWidth / 2 + 250,
paintHour);
canvas.rotate(-hrRot, mWidth / 2, mHeight / 2);
canvas.restore();
}
```
目前第一项任务已经完成,然后就是数字式的时钟
第一步:实现一个最简单的数字时钟,用最简单的drawText实现
```Java
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mWidth = getMeasuredWidth();
mHeight = getMeasuredHeight();
sTime.setToNow();
printNumber(canvas);
}
private void printNumber(Canvas canvas) {
Paint paintNumber = new Paint();
paintNumber.setTextSize(mWidth/5);
canvas.save();
canvas.drawText(String.valueOf(sTime.hour), 0, mHeight/2, paintNumber);
canvas.drawText(":", mWidth/4, mHeight/2 - 15, paintNumber);
canvas.drawText(String.valueOf(sTime.minute), mWidth/4 + 50, mHeight/2, paintNumber);
canvas.drawText(":", mWidth/2 + 40, mHeight/2 - 15, paintNumber);
canvas.drawText(String.valueOf(sTime.second), mWidth/2 + 100, mHeight/2, paintNumber);
canvas.restore();
}
public void refreshNumber() {
postInvalidate();
}
```
同样用Handler去实现每一秒更新一遍的调度。
但是上面的实现会十分的丑陋,甚至会出现14:15:6这样的情况,所以下面改用卡片式的实现:
//算了,我太懒不搞了<file_sep>/app/src/main/java/com/example/clockapp/MainActivity.java
package com.example.clockapp;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Window;
public class MainActivity extends AppCompatActivity {
ClockView mClockView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
ViewPager viewPager = findViewById(R.id.view_pager);
try {
viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
@NonNull
@Override
public Fragment getItem(int position) {
System.out.println("POSITION:"+position);
switch (position) {
case 0 :{
return new ClockFragment();
}
case 1 :{
return new NumberFragment();
}
}
return new ClockFragment();
}
@Override
public int getCount() {
return 2;
}
});
}
catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>/app/src/main/java/com/example/clockapp/NumberClockView.java
package com.example.clockapp;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.text.format.Time;
import android.util.AttributeSet;
import android.view.View;
/**
* TODO: document your custom view class.
*/
public class NumberClockView extends View {
private float mWidth;
private float mHeight;
private static Time sTime = new Time();
public NumberClockView(Context context) {
super(context);
}
public NumberClockView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public NumberClockView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
mWidth = getMeasuredWidth();
mHeight = getMeasuredHeight();
sTime.setToNow();
printNumber(canvas);
}
private void printNumber(Canvas canvas) {
Paint paintNumber = new Paint();
paintNumber.setTextSize(mWidth/5);
canvas.save();
canvas.drawText(String.valueOf(sTime.hour), 0, mHeight/2, paintNumber);
canvas.drawText(":", mWidth/4, mHeight/2 - 15, paintNumber);
canvas.drawText(String.valueOf(sTime.minute), mWidth/4 + 50, mHeight/2, paintNumber);
canvas.drawText(":", mWidth/2 + 40, mHeight/2 - 15, paintNumber);
canvas.drawText(String.valueOf(sTime.second), mWidth/2 + 100, mHeight/2, paintNumber);
canvas.restore();
}
public void refreshNumber() {
postInvalidate();
}
}
<file_sep>/app/src/main/java/com/example/clockapp/ClockView.java
package com.example.clockapp;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.text.format.Time;
import android.util.AttributeSet;
import android.view.View;
/**
* TODO: document your custom view class.
*/
public class ClockView extends View {
private float mWidth;
private float mHeight;
static Time sTime = new Time();
public ClockView(Context context) {
super(context);
}
public ClockView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ClockView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// 获取view的宽高
mWidth = getMeasuredWidth();
mHeight = getMeasuredHeight();
sTime.setToNow();
// 画外圆
printCircle(canvas);
printPointer(canvas);
}
//画时钟的外圆
private void printCircle(Canvas canvas) {
// Paint paintCircle = new Paint();
// paintCircle.setStyle(Paint.Style.STROKE);
// paintCircle.setAntiAlias(true);
// paintCircle.setStrokeWidth(5);
// canvas.drawCircle(mWidth / 2,
// mHeight / 2, mWidth / 2.1f, paintCircle);
//画圆心
Paint paintCenter = new Paint();
paintCenter.setStyle(Paint.Style.STROKE);
paintCenter.setAntiAlias(true);
paintCenter.setStrokeWidth(8);
canvas.drawCircle(mWidth / 2,
mHeight / 2, 10, paintCenter);
// 画大刻度
Paint painDegree = new Paint();
painDegree.setStrokeWidth(8);
painDegree.setColor(Color.BLACK);
// 画小刻度
for (int i = 0; i < 60; i++) {
// 区分整点与非整点
if (i%5 == 0) {
painDegree.setStrokeWidth(7);
painDegree.setAlpha(100);
canvas.drawLine(mWidth / 2, mHeight / 2 - mWidth / 2,
mWidth / 2, mHeight / 2 - mWidth / 2 + 30,
painDegree);
} else {
painDegree.setStrokeWidth(7);
painDegree.setAlpha(30);
canvas.drawLine(mWidth / 2, mHeight / 2 - mWidth / 2,
mWidth / 2, mHeight / 2 - mWidth / 2 + 30,
painDegree);
}
// 通过旋转画布简化坐标运算
canvas.rotate(6, mWidth / 2, mHeight / 2);
}
}
//画指针(时、分、秒)
private void printPointer(Canvas canvas) {
//获取各指针对应角度
float secRot = sTime.second * 6;
float minRot = sTime.minute * 6 + 6 * sTime.second / 60F;
float hrRot = (sTime.hour % 12) * 30 + 30 * minRot / 360F;
canvas.save();
//秒针
Paint paintSecond = new Paint();
paintSecond.setColor(Color.BLACK);
paintSecond.setStrokeWidth(5);
canvas.rotate(secRot, mWidth / 2, mHeight / 2);
canvas.drawLine(mWidth / 2, mHeight / 2 - 10, mWidth / 2, mHeight / 2 - mWidth / 2 + 150,
paintSecond);
canvas.rotate(-secRot, mWidth / 2, mHeight / 2);
//分针
Paint paintMinute = new Paint();
paintMinute.setColor(Color.BLACK);
paintMinute.setStrokeWidth(9);
canvas.rotate(minRot, mWidth / 2, mHeight / 2);
canvas.drawLine(mWidth / 2, mHeight / 2 - 10, mWidth / 2, mHeight / 2 - mWidth / 2 + 190,
paintMinute);
canvas.rotate(-minRot, mWidth / 2, mHeight / 2);
//时针
Paint paintHour = new Paint();
paintHour.setColor(Color.BLACK);
paintHour.setStrokeWidth(12);
canvas.rotate(hrRot, mWidth / 2, mHeight / 2);
canvas.drawLine(mWidth / 2, mHeight / 2 - 10, mWidth / 2, mHeight / 2 - mWidth / 2 + 250,
paintHour);
canvas.rotate(-hrRot, mWidth / 2, mHeight / 2);
canvas.restore();
}
public void refreshPointer() {
postInvalidate();
}
}
|
9a1911d1801a033172b0a6a6d9294c48a0c27ea4
|
[
"Markdown",
"Java"
] | 4 |
Markdown
|
JeevanLiang/ClockApp
|
4727d16ec9fcc6fa4d2b24e96811430eba06ebde
|
6b439ed567c3cd4aa16d821eaf29b93c8298835b
|
refs/heads/master
|
<repo_name>JKBowling/JKBowling-online-heroku<file_sep>/src/main/java/it/uniroma3/siw/spring/jkb/model/Squadra.java
package it.uniroma3.siw.spring.jkb.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import lombok.Data;
@Entity
@Data
public class Squadra {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
@Column(nullable=false, unique=true)
private String nome;
@OneToMany(mappedBy="squadra", cascade=CascadeType.PERSIST)
private List<Giocatore> giocatori;
@ManyToOne
private Torneo torneo;
public Squadra() {
this.giocatori=new ArrayList<>();
this.torneo=null;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Squadra other = (Squadra) obj;
if (nome == null) {
if (other.nome != null)
return false;
} else if (!nome.equals(other.nome))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
return result;
}
@Override
public String toString() {
return "Squadra [nome=" + nome + ", giocatori=" + giocatori + "]";
}
}
<file_sep>/src/main/java/it/uniroma3/siw/spring/jkb/service/IndirizzoService.java
/*
package it.uniroma3.siw.spring.jkb.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import it.uniroma3.siw.spring.jkb.model.Indirizzo;
import it.uniroma3.siw.spring.jkb.repository.IndirizzoRepository;
@Service
public class IndirizzoService {
@Autowired
private IndirizzoRepository indirizzoRepository;
@Transactional
public void inserisci(Indirizzo indirizzo) {
this.indirizzoRepository.save(indirizzo);
}
@Transactional
public void rimuovi(Indirizzo indirizzo) {
this.indirizzoRepository.delete(indirizzo);
}
@Transactional
public Indirizzo getIndirizzoById(Long id) {
Optional<Indirizzo> result = this.indirizzoRepository.findById(id);
return result.orElse(null);
}
@Transactional
public List<Indirizzo> tutti(){
return (List<Indirizzo>) this.indirizzoRepository.findAll();
}
}
*/
<file_sep>/src/main/java/it/uniroma3/siw/spring/jkb/controller/SalaDaBowlingController.java
package it.uniroma3.siw.spring.jkb.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
//import it.uniroma3.siw.spring.jkb.model.Indirizzo;
import it.uniroma3.siw.spring.jkb.model.SalaDaBowling;
import it.uniroma3.siw.spring.jkb.model.Squadra;
import it.uniroma3.siw.spring.jkb.model.Torneo;
//import it.uniroma3.siw.spring.jkb.service.IndirizzoService;
import it.uniroma3.siw.spring.jkb.service.SalaDaBowlingService;
import it.uniroma3.siw.spring.jkb.validator.SalaDaBowlingValidator;
@Controller
public class SalaDaBowlingController {
@Autowired
private SalaDaBowlingService salaDaBowlingService;
/*
@Autowired
private IndirizzoService indirizzoService;
*/
@Autowired
private SalaDaBowlingValidator salaDaBowlingValidator;
@RequestMapping(value="/admin/addSala",method= RequestMethod.GET)
public String sala(Model model) {
model.addAttribute("sala",new SalaDaBowling());
//model.addAttribute("indirizzo",new Indirizzo());
return "admin/sala/salaDaBowlingForm.html";
}
@RequestMapping(value = "/admin/deleteSala", method = RequestMethod.GET)
public String eliminaSala(@RequestParam("sala") String nome, Model model) {
SalaDaBowling salaDelete = this.salaDaBowlingService.salaPerNome(nome).get(0);
this.salaDaBowlingService.eliminaSala(salaDelete);
model.addAttribute("sale",this.salaDaBowlingService.tutti());
return "admin/sala/sale.html";
}
@RequestMapping(value="/admin/salePartner",method= RequestMethod.GET)
public String saleAdmin(Model model) {
model.addAttribute("sale",this.salaDaBowlingService.tutti());
return "admin/sala/sale.html";
}
@RequestMapping(value="/controlloSala", method=RequestMethod.POST)
public String controlloSala(@RequestParam(value = "modifica", required = false) String modifica,
@RequestParam(value = "elimina", required = false) String elimina,
@RequestParam("link") String link,
Model model) {
if(modifica != null && elimina == null) {
model.addAttribute("sala", this.salaDaBowlingService.getSala(this.salaDaBowlingService.salaPerLink(link).get(0).getId()));
model.addAttribute("indirizzo", this.salaDaBowlingService.salaPerLink(link).get(0).getIndirizzo());
return "admin/sala/salaDaBowlingModifica.html";
}
SalaDaBowling salaDelete = this.salaDaBowlingService.salaPerLink(link).get(0);
for(Torneo torneo : salaDelete.getTorneiOspitati()) {
for(Squadra squadra : torneo.getSquadreIscritte())
squadra.setTorneo(null);
}
this.salaDaBowlingService.eliminaSala(salaDelete);
model.addAttribute("sale",this.salaDaBowlingService.tutti());
return "admin/sala/sale.html";
}
@RequestMapping(value="/admin/modificaSala", method= {RequestMethod.POST, RequestMethod.PUT})
public String modificaSala(@RequestParam("id") Long id, @RequestParam("nome") String nome,
@RequestParam("descrizione") String descrizione, @RequestParam("link") String link,
@RequestParam("indirizzo") String indirizzo, Model model) {
this.salaDaBowlingService.modifica(nome, descrizione, link, indirizzo, id);
model.addAttribute("sale",this.salaDaBowlingService.tutti());
return "admin/sala/sale.html";
}
@RequestMapping(value = "/admin/nuovaSala", method = RequestMethod.POST)
public String newSala(@ModelAttribute("sala") SalaDaBowling sala,/*@ModelAttribute("indirizzo") Indirizzo indirizzo,*/
Model model, BindingResult bindingResult) {
this.salaDaBowlingValidator.validate(sala, bindingResult);
if(!bindingResult.hasErrors()) {
//sala.setIndirizzo(indirizzo);
this.salaDaBowlingService.inserisci(sala);
model.addAttribute("sale", this.salaDaBowlingService.tutti());
return "admin/sala/sale.html";
}
return "error.html";
}
}
<file_sep>/src/main/java/it/uniroma3/siw/spring/jkb/service/SalaDaBowlingService.java
package it.uniroma3.siw.spring.jkb.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
//import it.uniroma3.siw.spring.jkb.model.Indirizzo;
import it.uniroma3.siw.spring.jkb.model.SalaDaBowling;
import it.uniroma3.siw.spring.jkb.repository.SalaDaBowlingRepository;
@Service
public class SalaDaBowlingService {
@Autowired
private SalaDaBowlingRepository salaDaBowlingRepository;
@Transactional
public SalaDaBowling inserisci(SalaDaBowling sala) {
List<SalaDaBowling> sale = (List<SalaDaBowling>) this.salaDaBowlingRepository.findAll();
if(sale.size()!=0) {
if(this.getSala(this.salaUltima()).getYes()!=null) {
sala.setYes(null);
}
}
return this.salaDaBowlingRepository.save(sala);
}
@Transactional
public List<SalaDaBowling> salaPerNome(String nome) {
return this.salaDaBowlingRepository.findByNomeLike(nome);
}
@Transactional
public SalaDaBowling getSala(Long id) {
Optional<SalaDaBowling> result = this.salaDaBowlingRepository.findById(id);
return result.orElse(null);
}
@Transactional
public void eliminaSala(SalaDaBowling sala) {
this.salaDaBowlingRepository.deleteById(sala.getId());
}
@Transactional
public List<SalaDaBowling> tutti(){
return (List<SalaDaBowling>) this.salaDaBowlingRepository.findAll();
}
@Transactional
public List<SalaDaBowling> salaPerNomeAndIndirizzo(String sala, String indirizzo) {
return this.salaDaBowlingRepository.findByNomeAndIndirizzo(sala, indirizzo);
}
@Transactional
public List<SalaDaBowling> salaPerLink(String link) {
return this.salaDaBowlingRepository.findByLink(link);
}
@Transactional
public boolean alreadyExists(SalaDaBowling sala, String indirizzo) {
List<SalaDaBowling> sale = this.salaDaBowlingRepository.findByNomeAndIndirizzo(sala.getNome(), indirizzo);
if (sale.size() > 0)
return true;
else
return false;
}
@Transactional
public Long salaUltima() {
return this.salaDaBowlingRepository.findSalaUltima();
}
@Transactional
public void modifica(String nome, String descrizione, String link, String indirizzo, Long id) {
this.salaDaBowlingRepository.modificaSala(nome, descrizione, link, indirizzo, id);
}
}
<file_sep>/src/main/java/it/uniroma3/siw/spring/jkb/service/SquadraService.java
package it.uniroma3.siw.spring.jkb.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import it.uniroma3.siw.spring.jkb.model.Squadra;
import it.uniroma3.siw.spring.jkb.model.Torneo;
import it.uniroma3.siw.spring.jkb.repository.SquadraRepository;
@Service
public class SquadraService {
@Autowired
private SquadraRepository squadraRepository;
@Transactional
public Squadra getSquadra(Long id) {
Optional<Squadra> result = this.squadraRepository.findById(id);
return result.orElse(null);
}
@Transactional
public List<Squadra> tutti(){
return (List<Squadra>) this.squadraRepository.findAll();
}
@Transactional
public void inserisci(Squadra squadra) {
this.squadraRepository.save(squadra);
}
@Transactional
public List<Squadra> squadraPerNome(String nome){
return this.squadraRepository.findByNomeLike(nome);
}
@Transactional
public void eliminaSquadra(Squadra squadra) {
this.squadraRepository.delete(squadra);
}
@Transactional
public void modificaSquadra(String nome, Long id) {
this.squadraRepository.modificaSquadra(nome, id);
}
@Transactional
public void impostaTorneo(Torneo torneo, Long idSquadra) {
this.squadraRepository.impostaTorneo(torneo, idSquadra);
}
}
<file_sep>/src/main/java/it/uniroma3/siw/spring/jkb/model/Giocatore.java
package it.uniroma3.siw.spring.jkb.model;
import java.time.LocalDate;
import java.util.Random;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.springframework.format.annotation.DateTimeFormat;
import lombok.Data;
@Entity
@Data
public class Giocatore {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
Long id;
@Column(nullable=false)
private String nome;
@Column(nullable=false)
private String cognome;
@Column
@DateTimeFormat(pattern="yyyy-MM-dd")
private LocalDate dataNascita;
@Column(nullable=true,unique=true)
private String soprannome;
@Column(nullable=false)
private String email;
@Column
private String cellulare;
@Column(nullable=false,unique=true)
private String codiceSquadra;
@ManyToOne
@JoinColumn(name = "giocatori")
private Squadra squadra;
private Boolean isCapitano;
private String messaggi;
public Giocatore() {
this.isCapitano = false;
}
public void generaCodice() {
Random rnd = new Random();
int number = rnd.nextInt(999999);
this.codiceSquadra = String.format("%06d", number);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Giocatore other = (Giocatore) obj;
if (codiceSquadra == null) {
if (other.codiceSquadra != null)
return false;
} else if (!codiceSquadra.equals(other.codiceSquadra))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((codiceSquadra == null) ? 0 : codiceSquadra.hashCode());
return result;
}
@Override
public String toString() {
return "Giocatore [nome=" + nome + ", cognome=" + cognome + ", dataNascita=" + dataNascita + ", soprannome="
+ soprannome + ", email=" + email + ", cellulare=" + cellulare + ", codiceSquadra=" + codiceSquadra
+ "]";
}
}
<file_sep>/src/main/java/it/uniroma3/siw/spring/jkb/SiwSpringJkbApplication.java
package it.uniroma3.siw.spring.jkb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SiwSpringJkbApplication {
public static void main(String[] args) {
SpringApplication.run(SiwSpringJkbApplication.class, args);
}
}
<file_sep>/src/main/java/it/uniroma3/siw/spring/jkb/model/Torneo.java
package it.uniroma3.siw.spring.jkb.model;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import org.springframework.format.annotation.DateTimeFormat;
import lombok.Data;
@Entity
@Data
public class Torneo {
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE)
private Long id;
@Column(nullable=false,unique=true)
private String nome;
@Column(nullable=false,length=20000)
private String descrizione;
@Column(nullable=false)
@DateTimeFormat(pattern="yyyy-MM-dd")
private LocalDate dataInizio;
@Column(nullable=false)
@DateTimeFormat(pattern="yyyy-MM-dd")
private LocalDate dataFine;
@Column(nullable=false)
@DateTimeFormat(pattern="yyyy-MM-dd")
private LocalDate dataInizioIscrizioni;
@Column(nullable=false)
@DateTimeFormat(pattern="yyyy-MM-dd")
private LocalDate dataFineIscrizioni;
@Column
private String quotaIscrizione;
// @Column//(nullable=false,unique=true)
// private Integer code;
//
@Column//attributo che serve per la presentazione dei torne nella pagina
private String yes;
@Column//attributo che serve per verificare che le date di iscrizioni siano accessibili o meno
private Boolean scadenza;
@Column(length=20000)//mi dice se la form verrà mostrata o meno a seconda che il valore sia true o null
private String form;
@OneToMany(mappedBy="torneo")
private List<Squadra> squadreIscritte;
@ManyToOne
private SalaDaBowling sala;
public Torneo() {
this.squadreIscritte = new ArrayList<>();
this.yes="y";
}
@Override
public String toString() {
return "Torneo [nome=" + nome + ", descrizione=" + descrizione + ", dataInizio=" + dataInizio + ", dataFine="
+ dataFine + ", dataInizioIscrizioni=" + dataInizioIscrizioni + ", dataFineIscrizioni="
+ dataFineIscrizioni + ", quotaIscrizione=" + quotaIscrizione + ", sala=" + sala
+ "]";
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Torneo other = (Torneo) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (nome == null) {
if (other.nome != null)
return false;
} else if (!nome.equals(other.nome))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((nome == null) ? 0 : nome.hashCode());
return result;
}
}
<file_sep>/src/main/java/it/uniroma3/siw/spring/jkb/controller/AuthenticationController.java
package it.uniroma3.siw.spring.jkb.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import it.uniroma3.siw.spring.jkb.model.Credentials;
import it.uniroma3.siw.spring.jkb.model.Giocatore;
import it.uniroma3.siw.spring.jkb.service.CredentialsService;
import it.uniroma3.siw.spring.jkb.service.GiocatoreService;
import it.uniroma3.siw.spring.jkb.service.TorneoService;
import it.uniroma3.siw.spring.jkb.validator.CredentialsValidator;
import it.uniroma3.siw.spring.jkb.validator.GiocatoreValidator;
@Controller
public class AuthenticationController {
@Autowired
private CredentialsService credentialsService;
@Autowired
private TorneoService torneoService;
@Autowired
private GiocatoreService giocatoreService;
@Autowired
private GiocatoreValidator giocatoreValidator;
@Autowired
private CredentialsValidator credentialsValidator;
@RequestMapping(value = "/register", method = RequestMethod.GET)
public String showRegisterForm(Model model) {
model.addAttribute("giocatore", new Giocatore());
model.addAttribute("credentials", new Credentials());
return "registerUser.html";
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String showLoginForm(Model model) {
return "login.html";
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(Model model) {
return "index.html";
}
@RequestMapping(value = "/default", method = RequestMethod.GET)
public String defaultAfterLogin(Model model) {
UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Credentials credentials = credentialsService.getCredentials(userDetails.getUsername());
if(credentials.getRole().equals(Credentials.ADMIN_ROLE)) {
return "admin/adminHome.html";
}
model.addAttribute("giocatore", this.giocatoreService.getGiocatore(credentials.getGiocatore().getId()));
return "giocatore/home.html";
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String registerUser(@ModelAttribute("giocatore") Giocatore giocatore, BindingResult giocatoreBindingResult,
@ModelAttribute("credentials") Credentials credentials,
BindingResult credentialsBindingResult,
Model model) {
this.giocatoreValidator.validate(giocatore, giocatoreBindingResult);
this.credentialsValidator.validate(credentials, credentialsBindingResult);
if(!giocatoreBindingResult.hasErrors() && !credentialsBindingResult.hasErrors()) {
giocatore.generaCodice();
credentials.setGiocatore(giocatore);
credentialsService.saveCredentials(credentials);
if(this.torneoService.torneiProssimiAllaScadenza().size()!=0)
model.addAttribute("tornei",this.torneoService.torneiProssimiAllaScadenza());
return "index.html";
}
return "registerUser.html";
}
}
<file_sep>/src/main/java/it/uniroma3/siw/spring/jkb/repository/SquadraRepository.java
package it.uniroma3.siw.spring.jkb.repository;
import java.util.List;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import it.uniroma3.siw.spring.jkb.model.Squadra;
import it.uniroma3.siw.spring.jkb.model.Torneo;
public interface SquadraRepository extends CrudRepository<Squadra,Long>{
public List<Squadra> findByNomeLike(String nome);
@Modifying
@Query("update Squadra s set s.nome = ?1 where s.id = ?2")
public void modificaSquadra(String nome,Long id);
@Modifying
@Query("update Squadra s set s.torneo = ?1 where s.id = ?2")
public void impostaTorneo(Torneo torneo,Long idSquadra);
}
<file_sep>/src/main/java/it/uniroma3/siw/spring/jkb/validator/TorneoValidator.java
package it.uniroma3.siw.spring.jkb.validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import it.uniroma3.siw.spring.jkb.model.Torneo;
import it.uniroma3.siw.spring.jkb.service.TorneoService;
@Component
public class TorneoValidator implements Validator {
@Autowired
private TorneoService torneoService;
private final static Logger logger = LoggerFactory.getLogger(TorneoValidator.class);
@Override
public boolean supports(Class<?> clazz) {
return Torneo.class.equals(clazz);
}
@Override
public void validate(Object obj, Errors errors) {
Torneo o = (Torneo) obj;
if(this.torneoService.alreadyExists(o)) {
logger.debug("Torneo già inserito");
errors.reject("Torneo già inserito");
}
logger.debug("valori validi");
}
}
<file_sep>/src/main/java/it/uniroma3/siw/spring/jkb/validator/CredentialsValidator.java
package it.uniroma3.siw.spring.jkb.validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import it.uniroma3.siw.spring.jkb.model.Credentials;
import it.uniroma3.siw.spring.jkb.service.CredentialsService;
@Component
public class CredentialsValidator implements Validator {
@Autowired
private CredentialsService credentialService;
final Integer MAX_PASSWORD_LENGTH = 20;
final Integer MIN_PASSWORD_LENGTH = 6;
private static final Logger logger = LoggerFactory.getLogger(CredentialsValidator.class);
@Override
public boolean supports(Class<?> clazz) {
return Credentials.class.equals(clazz);
}
@Override
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "required");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "required");
Credentials credentials = (Credentials) obj;
String password = credentials.getPassword().trim();
if(password.length() < MIN_PASSWORD_LENGTH || password.length() > MAX_PASSWORD_LENGTH)
errors.rejectValue("password", "size");
if(!errors.hasErrors()) {
logger.debug("valori validi");
if(this.credentialService.getCredentials(credentials.getUsername()) != null ) {
logger.debug("utente già registrato");
errors.reject("duplicato");
}
}
}
}
<file_sep>/src/main/java/it/uniroma3/siw/spring/jkb/service/TorneoService.java
package it.uniroma3.siw.spring.jkb.service;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import it.uniroma3.siw.spring.jkb.model.SalaDaBowling;
import it.uniroma3.siw.spring.jkb.model.Torneo;
import it.uniroma3.siw.spring.jkb.repository.TorneoRepository;
@Service
public class TorneoService {
@Autowired
private TorneoRepository torneoRepository;
@Transactional
public Torneo getTorneo(Long id) {
Optional<Torneo> result = this.torneoRepository.findById(id);
return result.orElse(null);
}
@Transactional
public void modificaTorneo(String nome,String descrizione,LocalDate dataInizio,LocalDate dataFine,
LocalDate dataInizioIscrizioni,LocalDate dataFineIscrzioni,String quota,SalaDaBowling sala,Long id) {
this.torneoRepository.modificaTorneo(nome, descrizione, dataInizio, dataFine, dataInizioIscrizioni, dataFineIscrzioni, quota, sala, id);
}
@Transactional
public Boolean controlloDate(Torneo torneo,LocalDate dateInizio,LocalDate dateFine,LocalDate dateInizioIscr,LocalDate dateFineIscr) {
String messaggio=null;
if(LocalDate.now().isBefore(dateInizioIscr)) {
messaggio="Questo torneo non è ancora aperto alle iscrizioni.";
this.torneoRepository.mostraForm(null,messaggio,torneo.getId());
return null;
}
if(LocalDate.now().isAfter(dateInizioIscr) && LocalDate.now().isBefore(dateFineIscr)) {
messaggio="Iscrizioni Aperte!";
this.torneoRepository.mostraForm(true,messaggio,torneo.getId());
return true;
}
if(LocalDate.now().isAfter(dateFineIscr) && LocalDate.now().isBefore(dateInizio)) {
messaggio="Le iscrizioni a questo torneo sono chiuse.";
this.torneoRepository.mostraForm(null,messaggio,torneo.getId());
return null;
}
if(LocalDate.now().isAfter(dateInizio) && LocalDate.now().isBefore(dateFine)) {
this.torneoRepository.mostraForm(null,messaggio,torneo.getId());
return null;
}
if(LocalDate.now().isAfter(dateFine)) {
messaggio="Torneo Concluso";
this.torneoRepository.mostraForm(null,messaggio,torneo.getId());
return null;
}
return null;
}
@Transactional
public List<Torneo> torneiProssimiAllaScadenza(){
return this.torneoRepository.torneiScadenti();
}
@Transactional
public Torneo saveTorneo(Torneo torneo) {
List<Torneo> tornei = (List<Torneo>) this.torneoRepository.findAll();
if(tornei.size()!=0) {
if(this.getTorneo(this.torneoRepository.findTorneoUltimo()).getYes()!=null) {
torneo.setYes(null);
}
}
return this.torneoRepository.save(torneo);
}
@Transactional
public List<Torneo> tutti(){
return (List<Torneo>) this.torneoRepository.findAll();
}
@Transactional
public List<Torneo> torneoPerNome(String nome) {
return this.torneoRepository.findByNome(nome);
}
@Transactional
public void eliminaTorneo(Torneo torneo) {
this.torneoRepository.deleteById(torneo.getId());
}
@Transactional
public Long torneoUltimo() {
return this.torneoRepository.findTorneoUltimo();
}
@Transactional
public boolean alreadyExists(Torneo torneo) {
List<Torneo> tornei = this.torneoRepository.findByNome(torneo.getNome());
if (tornei.size() > 0)
return true;
else
return false;
}
}
<file_sep>/src/main/java/it/uniroma3/siw/spring/jkb/controller/SquadraController.java
package it.uniroma3.siw.spring.jkb.controller;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import it.uniroma3.siw.spring.jkb.model.Credentials;
import it.uniroma3.siw.spring.jkb.model.Giocatore;
import it.uniroma3.siw.spring.jkb.model.Squadra;
import it.uniroma3.siw.spring.jkb.model.Torneo;
import it.uniroma3.siw.spring.jkb.service.CredentialsService;
import it.uniroma3.siw.spring.jkb.service.GiocatoreService;
import it.uniroma3.siw.spring.jkb.service.SquadraService;
import it.uniroma3.siw.spring.jkb.service.TorneoService;
@Controller
public class SquadraController {
@Autowired
private CredentialsService credentialsService;
@Autowired
private SquadraService squadraService;
@Autowired
private GiocatoreService giocatoreService;
@Autowired
private TorneoService torneoService;
@RequestMapping(value="/creaSquadra", method=RequestMethod.GET)
public String creaSquadra(Model model){
UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Credentials credentials = credentialsService.getCredentials(userDetails.getUsername());
Giocatore capitano = credentials.getGiocatore();
if(capitano.getSquadra() != null)
return "error.html";
model.addAttribute("squadra", new Squadra());
model.addAttribute("capitano", capitano);
model.addAttribute("giocatori",this.giocatoreService.tutti());
return "/giocatore/creaSquadra.html";
}
@RequestMapping(value="/verificaSquadra", method=RequestMethod.POST)
public String verificaSquadra(@ModelAttribute("squadra") Squadra squadra,@RequestParam("capitano") String capitano,
@RequestParam("giocatore2") String giocatore2, @RequestParam("giocatore3") String giocatore3,
@RequestParam("giocatore4") String giocatore4, Model model) {
Giocatore c = this.giocatoreService.reclutaGiocatore(capitano).get(0);
Giocatore g2 = this.giocatoreService.reclutaGiocatore(giocatore2).get(0);
model.addAttribute("giocatore2", g2);
Giocatore g3 = this.giocatoreService.reclutaGiocatore(giocatore3).get(0);
model.addAttribute("giocatore3", g3);
Giocatore g4 = this.giocatoreService.reclutaGiocatore(giocatore4).get(0);
model.addAttribute("giocatore4", g4);
model.addAttribute("squadra", squadra);
model.addAttribute("capitano", c);
return "/giocatore/verificaSquadra.html";
}
@RequestMapping(value="/controlloSquadra", method=RequestMethod.POST)
public String indietroSquadra(@ModelAttribute("squadra") Squadra squadra,@RequestParam("capitano") String capitano,
@RequestParam("giocatore2") String giocatore2, @RequestParam("giocatore3") String giocatore3,
@RequestParam("giocatore4") String giocatore4,
@RequestParam(value = "avanti", required = false) String avanti,
@RequestParam(value = "indietro", required = false) String indietro,
Model model) {
if(avanti != null && indietro == null) {
List<Giocatore> team = new ArrayList<>();
Giocatore cpt = this.giocatoreService.reclutaGiocatore(capitano).get(0);
team.add(cpt);
Giocatore g2 = this.giocatoreService.reclutaGiocatore(giocatore2).get(0);
team.add(g2);
Giocatore g3 = this.giocatoreService.reclutaGiocatore(giocatore3).get(0);
team.add(g3);
Giocatore g4 = this.giocatoreService.reclutaGiocatore(giocatore4).get(0);
team.add(g4);
squadra.setGiocatori(team);
for(Giocatore g : squadra.getGiocatori())
g.setSquadra(squadra);
squadra.getGiocatori().get(0).setIsCapitano(true);
this.squadraService.inserisci(squadra);
model.addAttribute("giocatore",cpt);
return "/giocatore/home.html";
}
Giocatore c = this.giocatoreService.reclutaGiocatore(capitano).get(0);
Giocatore g2 = this.giocatoreService.reclutaGiocatore(giocatore2).get(0);
model.addAttribute("giocatore2", g2);
Giocatore g3 = this.giocatoreService.reclutaGiocatore(giocatore3).get(0);
model.addAttribute("giocatore3", g3);
Giocatore g4 = this.giocatoreService.reclutaGiocatore(giocatore4).get(0);
model.addAttribute("giocatore4", g4);
model.addAttribute("squadra", squadra);
model.addAttribute("capitano", c);
return "/giocatore/creaSquadra.html";
}
@RequestMapping(value = "/giocatore/eliminaSquadra", method = RequestMethod.POST)
public String elimiminaSquadra(Model model) {
UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Credentials credentials = credentialsService.getCredentials(userDetails.getUsername());
Giocatore capitano = credentials.getGiocatore();
Squadra squadra = capitano.getSquadra();
for(Giocatore g : squadra.getGiocatori())
g.setSquadra(null);
if(squadra.getTorneo()!=null)
squadra.getTorneo().getSquadreIscritte().remove(squadra);
this.squadraService.eliminaSquadra(squadra);
model.addAttribute("giocatore", capitano);
return "giocatore/home.html";
}
@RequestMapping(value="/giocatore/modificaSquadra", method = RequestMethod.GET)
public String modificaSquadra(Model model) {
UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Credentials credentials = credentialsService.getCredentials(userDetails.getUsername());
Giocatore capitano = credentials.getGiocatore();
Squadra squadra = capitano.getSquadra();
if(squadra != null) {
model.addAttribute("squadra", squadra);
model.addAttribute("capitano", capitano);
model.addAttribute("giocatore2", squadra.getGiocatori().get(1));
model.addAttribute("giocatore3", squadra.getGiocatori().get(2));
model.addAttribute("giocatore4", squadra.getGiocatori().get(3));
return "/giocatore/modificaSquadra.html";
}
return "error.html";
}
@RequestMapping(value="/giocatore/confermaModifica", method = RequestMethod.POST)
public String modificaSquadra(@ModelAttribute("id") Long id, @RequestParam("nome") String nome,
@RequestParam("capitano") String capitano, @RequestParam("giocatore2") String giocatore2,
@RequestParam("giocatore3") String giocatore3,
@RequestParam("giocatore4") String giocatore4,
Model model) {
Squadra s = this.squadraService.getSquadra(id);
for(Giocatore g : s.getGiocatori())
g.setSquadra(null);
List<Giocatore> team = new ArrayList<>();
Giocatore cpt = this.giocatoreService.reclutaGiocatore(capitano).get(0);
team.add(cpt);
Giocatore g2 = this.giocatoreService.reclutaGiocatore(giocatore2).get(0);
team.add(g2);
Giocatore g3 = this.giocatoreService.reclutaGiocatore(giocatore3).get(0);
team.add(g3);
Giocatore g4 = this.giocatoreService.reclutaGiocatore(giocatore4).get(0);
team.add(g4);
s.setGiocatori(team);
for(Giocatore g : s.getGiocatori())
g.setSquadra(s);
s.getGiocatori().get(0).setIsCapitano(true);
this.squadraService.modificaSquadra(nome, id);
UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Credentials credentials = credentialsService.getCredentials(userDetails.getUsername());
Giocatore user = credentials.getGiocatore();
model.addAttribute("giocatore", user);
return "/giocatore/home.html";
}
@RequestMapping(value="/iscrizione", method = RequestMethod.POST)
public String iscriviti(@RequestParam("nome") String torneo, Model model) {
UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Credentials credentials = credentialsService.getCredentials(userDetails.getUsername());
Giocatore giocatore = credentials.getGiocatore();
Squadra s = this.squadraService.getSquadra(giocatore.getSquadra().getId());
Torneo t = this.torneoService.torneoPerNome(torneo).get(0);
this.squadraService.impostaTorneo(t, s.getId());
t.getSquadreIscritte().add(s);
model.addAttribute("giocatore", giocatore);
return "/giocatore/home.html";
}
}
<file_sep>/src/main/java/it/uniroma3/siw/spring/jkb/repository/GiocatoreRepository.java
package it.uniroma3.siw.spring.jkb.repository;
import java.util.List;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import it.uniroma3.siw.spring.jkb.model.Giocatore;
import it.uniroma3.siw.spring.jkb.model.Squadra;
public interface GiocatoreRepository extends CrudRepository<Giocatore,Long> {
public List<Giocatore> findByCodiceSquadra(String codiceSquadra);
@Modifying
@Query("update Giocatore g set g.squadra = ?1 where g.id = ?2")
public void impostaSquadra(Squadra squadra,Long id);
}
|
e2cec02d589f3d226538e878c0871f46004cfabf
|
[
"Java"
] | 15 |
Java
|
JKBowling/JKBowling-online-heroku
|
9999a286719a4e5fffcd450182f3a7645ef32ce2
|
fb02060e914756d9f26568758624718998d34044
|
refs/heads/master
|
<repo_name>weimingtom/chunktrans_java<file_sep>/README.md
# chunktrans_java
Java port of chunktrans
## Ref
* https://github.com/weimingtom/chunktrans
* https://github.com/haramako/mlua
* https://github.com/dawee/moonchild
* https://github.com/cartman300/LuaBintils
* https://github.com/Nymphium/moonstep
## OP Command
* https://github.com/haramako/mlua/blob/master/state.rb
* https://github.com/andyleap/LuaVM/blob/master/VM.go
* https://github.com/andyleap/LuaVM/blob/master/Instructions.go
## virtual machine in c
* https://felixangell.com/blog/virtual-machine-in-c
* https://github.com/felixangell/mac
<file_sep>/test/fib.lua
function fib(n)
if n<2 then
return n
else
return fib(n-1)+fib(n-2)
end
end
print(fib(10))
|
39e479da99845589eee5a68f229dfb418c938c99
|
[
"Markdown",
"Lua"
] | 2 |
Markdown
|
weimingtom/chunktrans_java
|
582122a06980682b541025c091574a6344e19c7f
|
f4adc7119e05604dab7fa3c799f66ab21d2318b0
|
refs/heads/master
|
<file_sep>__author__ = 'Bob'
from get_pet_price_data import *
from get_realm_data import *
from write_pet_price_data import *
from realm_list import update_realm_list
import random,os
server1_complete = False
server2_complete = False
r1_hi = {}
r1_lo = {}
r2_hi = {}
r2_lo = {}
realm_list=list(update_realm_list())
selection=random.randrange(0,(len(realm_list)),1)
def generate_testrealm():
selection=random.randrange(0,(len(realm_list)),1)
return realm_list[selection]
def tester():
server1=generate_testrealm()
server2=generate_testrealm()
testprice=127162214
print('test pet quslity is',pet_quality(3))
x=str('%s and %s'% (server1,server2))
print ('two realms being tested are %s .' % (x))
print ('test price is %s'% (gold_only(testprice)))
process_server(server1,1)
server1_complete=True
process_server(server2,2)
server2_complete=True
compare_prices(server1,server2)
def compare_prices(server1,server2):
write_to_master(bargain_hunter(r1_hi, r1_lo, r2_lo, server2, server1))
write_to_master(bargain_hunter(r2_hi, r2_lo, r1_lo, server1, server2))
clean_up()
def compare_pricess_check(server1,server2):
if server1_complete and server2_complete:
compare_prices(server1,server2)
def process_server(server,order):
api_page= (api_page_get(server))
print (api_page)
working_list=list(pet_auction_get(api_page))
create_pet_auction_lists(working_list,order)
def create_pet_auction_lists(working_list,order):
if order == 1:
hi = r1_hi
lo = r1_lo
else:
hi = r2_hi
lo = r2_lo
for line in working_list:
name = str(line[3])
price = int(line[2])
if name in hi:
if price > hi[name]:
hi[name] = price
else:
pass
else:
hi[name] = price
if name in lo:
if price < lo[name]:
lo[name] = price
else:
pass
else:
lo[name] = price
def main():
tester()
pet_checker()
price_checker()
main()<file_sep>__author__ = 'Bob'
import json
import httplib2,json
def realm_checker(server):
pass
def api_page_get(server):
print(str('http://eu.battle.net/api/wow/auction/data/' + server))
request = str('http://eu.battle.net/api/wow/auction/data/' + server)
h = httplib2.Http(".cache")
content_headers, content = h.request(request,"GET")
content = content.decode()
obj = json.loads(content)
for key, value in obj.items():
x = (value[0])
return (x['url'])
<file_sep>__author__ = 'Bob'
import json,httplib2,os
from get_pet_price_data import gold_only
PET_QUALITY = [ 'Poor', 'Common', 'Uncommon', 'Rare', 'Epic', 'Legendary','unknown']
def pet_checker():
pass
def pet_quality(grade):
return PET_QUALITY[grade]
def petid_get_new(id):
request = str('http://eu.battle.net/api/wow/battlePet/species/' + id)
h = httplib2.Http(".cache",timeout = 60)
content_headers, content = h.request(request)
content = content.decode()
obj = json.loads(content)
if 'creatureId' in obj:
return (obj['name'])
else:
return 'unknown pet'
def pet_auction_get(auc_api):
auc_list = []
print('Calculating ,please wait')
h = httplib2.Http(".cache", timeout = 60)
content_headers, content = h.request(auc_api,"GET")
content = content.decode()
obj = json.loads(content)
print('got json object')
x=( obj['auctions'])
y=x['auctions']
for i in y:
if (i['item'])==82800:
print('found pet number '+ str(len(auc_list)),end='\r')
temp_list=[]
temp_list.append(i['owner'])
temp_list.append(i['ownerRealm'])
temp_list.append(gold_only(i['buyout']))
check=str(i['petSpeciesId'])
id = petid_get_new(check)
x=int((i['petQualityId']))
quality = PET_QUALITY[x]
petname = str(id + ' of ' + quality + ' quality.')
temp_list.append(petname)
temp_list.append(i['petBreedId'])
#print(temp_list)
auc_list.append(temp_list)
print('list complete')
return auc_list
def write_to_master(auc_list):
with open('temp.txt', 'a') as master:
for line in auc_list:
master.write(str(line))
print('details written to bargains.txt')
def clean_up():
try:
os.remove("bargains.txt")
except:
os.rename("temp.txt", "bargains.txt ")
os.rename("temp.txt", "bargains.txt ")
<file_sep>__author__ = 'Bob'
bronze=100
silver=100
def price_checker():
pass
def gold_only(price):
return(int(round(price/(bronze*silver),2)))
def bargain_hunter(sell_server_hi, sell_server_lo, buy_server, cheap_server, exp_server):
bargains = []
for auction in sell_server_lo:
if auction in buy_server:
if buy_server[auction] < sell_server_lo[auction]:
sell_cost = sell_server_lo[auction]
buy_cost = buy_server[auction]
low_profit = (sell_server_lo[auction] - buy_server[auction])
high_profit = (sell_server_hi[auction] - buy_server[auction])
line = (' \nPossible bargain: ' + auction + ' on ' + str(cheap_server) + ' costs ' + str(
buy_cost) + ' and on ' + str(exp_server) + ' costs at least ' + str(
sell_cost) + ' \n...a potential profit of between ' + str(low_profit) + ' up to possibly ' + str(
high_profit) + ' \n' + '*' * 20)
bargains.append(line)
return (bargains)
|
18b8a865eaf70d2a825f4459bf5e213c2ea7fae3
|
[
"Python"
] | 4 |
Python
|
bob-lewis/wow_auc_gui_version
|
239ec82db9939c316a9da06bf08566301f9d9a40
|
1db2a99f8e4e5eacfaa328a551810cc271e4924e
|
refs/heads/master
|
<repo_name>AngelManuel1995/front-end-tdg<file_sep>/client/src/app/app.routes.ts
import { Routes, RouterModule } from '@angular/router'
import { PagesComponent } from "./pages/pages.component"
import { DashboardComponent } from './pages/dashboard/dashboars.component'
import { LoginComponent } from './login/login.component'
// import { ProgressComponent } from './pages/progress/progess.component'
// import { GraphicOneComponent } from './pages/graphicone/graphicone.component'
import { NopageFoundComponent } from './shared/nopagefound/nopagefound.component'
import { RegisterComponent } from "./login/register.component";
// import { AccountSettingsComponent } from './pages/account-settings/account-settings.component';
// import { PromiseComponent } from './pages/promises/promise.component';
// import { RxjsComponent } from './pages/rxjs/rxjs.component';
const appRoutes:Routes = [
{
path:'',
component:PagesComponent,
children:[
{path:'dashboard', component:DashboardComponent },
// {path:'progress', component:ProgressComponent},
// {path:'graphicsone', component:GraphicOneComponent},
// {path:'account-settings', component:AccountSettingsComponent},
// {path:'promesas', component:PromiseComponent},
// {path:'RxJs', component:RxjsComponent},
{path:'', redirectTo:'/dashboard', pathMatch:'full'},
]
},
{path:'login', component:LoginComponent},
{path:'register', component:RegisterComponent},
{path:'**', component:NopageFoundComponent}
]
export const APP_ROUTES = RouterModule.forRoot(appRoutes, { useHash:true })<file_sep>/server/README.md
#Proyecto de trabajo de grado
<NAME>
<NAME>
Ingeniería informática
Politécnico Colombiano Jaime Isaza Cadavid
Medellín Antioquia
<file_sep>/client/src/app/login/register.component.ts
import { Component, OnInit } from "@angular/core"
import { FormGroup, FormControl, Validators } from "@angular/forms";
// import * as swal from 'sweetalert'
// import { UsuariosService } from '../services/service.index'
import { Usuario } from "../models/usuario.model";
@Component({
selector:'app-register',
templateUrl:'./register.component.html',
styleUrls:['./login.component.css']
})
export class RegisterComponent implements OnInit{
// forma: FormGroup
// constructor(public _usuariosService:UsuariosService){
// }
constructor(){
}
// sonIguales(campo1:string, campo2:string){
// return (group: FormGroup) => {
// let pass1 = group.controls[campo1].value
// let pass2 = group.controls[campo2].value
// if(pass1 === pass2){
// return null
// }
// return {
// sonIguales:true
// }
// }
// }
// Si no se cumple debo retornar un error
// Si pasa la validación debo retornar un null
ngOnInit(): void {
// this.forma = new FormGroup({
// nombre: new FormControl(null, Validators.required),
// correo: new FormControl(null, [Validators.required, Validators.email]),
// password: new FormControl(null, Validators.required),
// password2: new FormControl(null, Validators.required),
// condiciones: new FormControl(false),
// }, {validators: this.sonIguales('password', '<PASSWORD>') });
}
registrarUsuario(){
// if(this.forma.invalid){
// return
// }
// if(!this.forma.value.condiciones){
// // swal('Importante', 'Debe aceptar los terminos y condiciones', 'warning')
// return
// }
// let usuario = new Usuario(this.forma.value.nombre, this.forma.value.correo, this.forma.value.password)
// // this._usuariosService.crearUsuario(usuario).subscribe( data => {
// // console.log(data)
// // })
}
}<file_sep>/client/src/app/pages/dashboard/dashboars.component.ts
import { Component, OnInit } from '@angular/core'
@Component({
selector:'app-dashboard',
templateUrl:'./dashboars.component.html'
})
export class DashboardComponent implements OnInit {
public avatares = [
{
name:'',
img:'https://miro.medium.com/fit/c/240/240/1*yh90bW8jL4f8pOTZTvbzqw.png',
selected: false
},
{
name:'',
img:'https://picandocodigo.net/wp-content/uploads/2014/06/femalecodertocat.png',
selected: false
},
{
name:'',
img:'https://techcrunch.com/wp-content/uploads/2010/07/github-logo.png?w=512',
selected: false
},
{
name:'',
img:'https://avatars0.githubusercontent.com/u/24922775?s=460&v=4',
selected: false
},
{
name:'',
img:'https://avatars0.githubusercontent.com/u/6642527?s=400&v=4',
selected: false
},
{
name:'',
img:'https://blog.mgechev.com/images/revive/revive.png',
selected: false
},
{
name:'',
img:'https://camo.githubusercontent.com/0e3c4976eb4b8ec80e285608a7f23744408a0ffb/68747470733a2f2f736563757265676f2e696f2f696d672f676f7365632e706e67',
selected: false
},
{
name:'',
img:'https://d1q6f0aelx0por.cloudfront.net/product-logos/f5326186-8ae7-425c-a78d-7192dabf75be-jenkins.png',
selected: false
},
{
name:'',
img:'https://image.flaticon.com/icons/png/512/186/186037.png',
selected: false
}
]
constructor(){
}
ngOnInit(): void {
}
}<file_sep>/README.md
# Trabajo de grado
<file_sep>/client/src/app/pages/pages.module.ts
import { NgModule } from "@angular/core";
import { FormsModule } from '@angular/forms'
import { RouterModule } from '@angular/router'
import { CommonModule } from '@angular/common'
// import { ProgressComponent } from "./progress/progess.component";
// import { GraphicOneComponent } from './graphicone/graphicone.component'
// import { AccountSettingsComponent } from './account-settings/account-settings.component'
// import { ComponentsModule } from '../components/components.module'
import { DashboardComponent } from "./dashboard/dashboars.component";
import { PagesComponent } from "./pages.component";
import { SharedModule } from '../shared/shared.module'
// import { PromiseComponent } from "./promises/promise.component";
// import { RxjsComponent } from "./rxjs/rxjs.component";
// import { ServiceModule } from "../services/service.module";
@NgModule({
declarations:[
// ProgressComponent,
// GraphicOneComponent,
// AccountSettingsComponent,
DashboardComponent,
PagesComponent,
// PromiseComponent,
// RxjsComponent,
],
exports:[
// ProgressComponent,
// GraphicOneComponent,
// AccountSettingsComponent,
DashboardComponent,
PagesComponent,
// PromiseComponent,
// RxjsComponent
],
imports:[
FormsModule,
CommonModule,
// ComponentsModule,
SharedModule,
RouterModule,
// ServiceModule
]
})
export class PagesModule{}<file_sep>/client/Dockerfile
FROM node:alpine as builder
RUN npm install -g @angular/cli
WORKDIR '/client'
COPY package.json /client
RUN npm install
COPY . .
RUN ng build --prod=true
FROM nginx
EXPOSE 4200
COPY ./nginx/default.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /client/dist/frontEndTdg /usr/share/nginx/html/cliente
<file_sep>/server/server/index.js
const express = require('express')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const keys = require('./config/keys')
mongoose.connection.openUri(`mongodb://${keys.mongoRootusername}:${keys.mongoPassword}@${keys.mongoHost}:${keys.mongoPort}/${keys.mongoDatabase}`, (err, res) => {
if(err) throw err
console.log('Base de datos: \x1b[32m%s\x1b[0m', 'Online')
})
let app = express()
app.use(function(req, res, next) {
'mongodb://nostradatos:<EMAIL>:27018/nostradatos'
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "POST, GET, PUT, PATCH, DELETE, OPTIONS");
next();
});
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
const usuarioRoutes = require('./routes/usuario')
app.use('/usuario',usuarioRoutes)
app.listen(PORT=5000, () => {
console.log('Aplicación corriendo en el puerto 5000. \x1b[32m%s\x1b[0m','Online')
})
|
2ea0ad43a18dc5940a32310fa98dc716a0c3e7db
|
[
"Markdown",
"TypeScript",
"JavaScript",
"Dockerfile"
] | 8 |
TypeScript
|
AngelManuel1995/front-end-tdg
|
2fc6697c0430418951870d0523998fc41d9c5fc5
|
3419db6c35f67677838b69b5da352f6610afee0f
|
refs/heads/master
|
<repo_name>Solester/zombiecrusades<file_sep>/Assets/Scripts/button.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class button : MonoBehaviour
{
private GameObject GameMenu;
public GameObject GameMenu2;
private GameObject ObjGear;
private bool isPaused;
void Start()
{
GameMenu = GameObject.Find("Canvas").transform.GetChild(0).gameObject;
ObjGear = GameObject.Find("Canvas").transform.GetChild(1).gameObject;
GameMenu.SetActive(false);
isPaused = false;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Escape) && !isPaused)
{
GameMenu.SetActive(true);
ObjGear.SetActive(false);
isPaused = true;
}
else if (Input.GetKeyDown(KeyCode.Escape) && isPaused)
{
GameMenu.SetActive(false);
ObjGear.SetActive(true);
isPaused = false;
}
if (isPaused)
{
Time.timeScale = 0;
}
else
{
Time.timeScale = 1;
}
}
public void Gear()
{
ObjGear.SetActive(false);
GameMenu.SetActive(true);
isPaused = true;
}
public void Resume()
{
ObjGear.SetActive(true);
GameMenu.SetActive(false);
isPaused = false;
}
public void Exit()
{
Application.Quit();
}
}
|
e7e65b35ea89ead8a7aefa6dc45f79054d83b87f
|
[
"C#"
] | 1 |
C#
|
Solester/zombiecrusades
|
0a7280ad9ad91fa7136cb5cbfc4f08e84e500d94
|
cd78e00b74c9b9c6c240a626a32d400156f4ede9
|
refs/heads/master
|
<repo_name>sebug/cnn-blocker<file_sep>/local-version/tutorial.py
import networkx
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.metrics import (accuracy_score, f1_score, confusion_matrix, plot_confusion_matrix)
from matplotlib import pylab as pl
import matplotlib.pyplot as plt
from abp.graphml.datasets.dataset import Dataset
ds = Dataset('data/adjacency.csv', 'data/features.csv', 200)
ds.print_summary()
all_posts = [post.to_nx_graph() for post in ds.data.values()]
all_labels = [post.label for post in ds.data.values()]
print('Total number of posts: ', len(all_posts))
regular_posts = [post for (post, label) in zip(all_posts, all_labels) if label == 0]
ad_posts = [post for (post, label) in zip(all_posts, all_labels) if label == 1]
print('Number of regular posts: ', len(regular_posts))
print('Number of ads: ', len(ad_posts))
import grakel
POSTS_COUNT = 150
sel_posts = all_posts[:POSTS_COUNT]
sel_labels = all_labels[:POSTS_COUNT]
g_posts = grakel.graph_from_networkx(sel_posts)
kernel = grakel.ShortestPath(with_labels=False, normalize=True, verbose=True)
K_all = kernel.fit_transform(g_posts)
K_posts = [post for (post, label) in zip(K_all, sel_labels) if label == 0]
K_ads = [post for (post, label) in zip(K_all, sel_labels) if label == 1]
K_train, K_test, y_train, y_test = train_test_split(K_all, sel_labels, test_size=0.2, random_state=42)
from tensorboardX import SummaryWriter
<file_sep>/README.md
# Augmenting web browsing experience using machine learning
General concept: HTML to graphs, detect those subgraphs.
The workbook: https://colab.research.google.com/drive/1T_0nmG-Ll0zLVLst4HEVvJ7CUA8KLH8G
So their dataset is a graph of HTML nodes. First step was to calculate graph kernels with [GraKeL](https://github.com/ysig/GraKeL).
We try some basic techniques on the kernel data (SVM, random forest classifier).
## Graph Convolutional Network
Convolutional networks - focus on the neighbors. Works well with graphs as well.
Their sample uses [Keras](https://keras.io)
## Learning on the web
Uses WebGL to benefit from the integrated GPU for re-learning.
|
843eb424af177b2b43bb17e2247a2f56e15fb506
|
[
"Markdown",
"Python"
] | 2 |
Python
|
sebug/cnn-blocker
|
f8d42081e06d9434559a96ad975f2913fa2f7969
|
625140b2765231870a9359b9cfe91e81aaaf8f36
|
refs/heads/main
|
<file_sep>#############################################################################################################################
#START BY RUNNING CHECKS ON INPUT RASTER LAYERS
#############################################################################################################################
#' Checks input raster layers
#'
#'
#'
#' This function checks the occupancy and detectability raster layers before running the power analysis
#' @param occ The occ raster stack
#' @keywords
#' @export
#' @examples
check.inputs <- function(occ){
#Check dimensions of raster layers and print warning if they don't match
if (ncol(occ) != ncol(det.method1) & ncol(det.method2) & ncol(det.method3) & ncol(parks) & ncol(remote)) {
cat('\n',"Warning: Raster layers have unequal number of columns")
}
if (model.fire == TRUE){
#if ((nrow(fire) != nrow(veg)) | (ncol(fire) != ncol(veg))){
#cat('\n',"Warning: Raster layers have unequal number of columns")}
}
#Check dimensions of raster layers and print warning if they don't match
if (nrow(occ) != nrow(det.method1) & nrow(det.method2) & nrow(det.method3) & nrow(parks) & nrow(remote)) {
cat('\n',"Warning: Raster layers have unequal number of columns")
}
#Check number of species match
if (nrow(species.list) != nlayers(occ) & nrow(species.cov) & nlayers(det.method1) & nlayers(det.method2) & nlayers(det.method3)) {
cat('\n',"Warning: Number of species in species/list and/or species.cov not equal to number of raster layers in occ stack")
}
if (Tmax != max(s.years)) {
cat('\n',"Warning: Monitoring must occur in final year (last year of monitoring must be equal to Tmax")}
if (park.level == TRUE & length(n.park) == 1) {
cat('\n',"Warning: Park level analysis selected but only one park identified in raster layer")
}
if (n.sites == 0) {
cat('\n',"Warning: No monitoring sites identified")
}
if (existing.sites == TRUE & all.existing.sites == FALSE & new.site.selection == "maxocc") {
cat('\n',"Warning: If new.site.selection == maxocc, set existing.sites == FALSE")
}
if (existing.sites == TRUE & all.existing.sites == FALSE & new.site.selection == "stratified") {
cat('\n',"Warning: If new.site.selection == stratified, set existing.sites == FALSE")
}
if (existing.sites == TRUE & all.existing.sites == FALSE & new.site.selection == "manual") {
cat('\n',"Warning: If new.site.selection == manual, set existing.sites == FALSE")
}
}
#' Site selection function
#'
#' This function selects sites in the landscape for monitoring. Sites can be pre-selected by loading in file of the XY coordinates, randomly selected, randomly stratified across environmental layers, positioned on cells
#' with the highest expected species richness, or manually selected by clicking on the raster map. Sites can also be divided between remote and non-remote areas
#' @param sites Contains the XY coordinates of sites loaded into the package for analysis
#' @param n.sites The number of sites to be monitored. This is equal to the number of rows in 'sites' if all.prespecified.sites == TRUE. Otherwise, it is specified by the user
#' @param R The ratio of remote to non-remote sites to be monitored. Setting R=1 means all sites will be in remote areas. Setting R=0 means no sites will be in remote areas
#' @keywords
#' @export
#' @examples
#' existing.sites <- TRUE
#' all.existing.sites <- TRUE
#' randomise.sites <- FALSE
#' new.site.selection <- 'random'
#' R <- 0.5
#' if (all.existing.sites == TRUE) {n.sites <- nrow(sites)} else {n.sites <- 50}
#' plotter <- TRUE
#' xy.sites <- select.sites(sites, n.sites, R)
#function to calculate budget per group
select.sites <- function(sites, n.sites, R, all.existing.sites, existing.sites, new.site.selection, plotter, occ, zonationOutput) { #I should really change the name of function and add new.site.selection + plotter as arguments in main function. Note, doesn't apply when sites are randomly selected - need to add, plots maxocc if selected
#Identify and then separate remote and non-remote site
rem.ras <- acc.ras <- remote
rem.ras[rem.ras==2] <- NA
acc.ras[acc.ras==1] <- NA
colnames(sites)<-c("POINT_X", "POINT_Y")
sites<- (as.data.frame(sites))
Rem <- remote[cellFromXY(remote, cbind(sites$POINT_X, sites$POINT_Y))] #Extract remote ID from remote layer
n.rem <- floor(n.sites*R) #Calculate number of remote sites
n.acc <- n.sites - n.rem #Calculate number of non-remote sites
XY.rem <- cbind(sites$POINT_X,sites$POINT_Y)[which(Rem==2),] #Separate remote and non-remote sites
XY.acc <- cbind(sites$POINT_X,sites$POINT_Y)[which(Rem==1),]
# create all sites up to n.sites via Zonation pairs.
if (existing.sites == FALSE & all.existing.sites == TRUE & new.site.selection == "pairs") {
XY.acc <- XY.rem <- NULL
zon.burnt <- zon.unburnt <- zonationOutput
zon.burnt[is.na(rem.ras)] <- NA
zon.unburnt[is.na(acc.ras)] <- NA
notna <- which(!is.na(getValues(zon.burnt)))
samp <- sample(notna, n.rem, replace = FALSE)
XY.rem <- xyFromCell(zon.burnt, samp)
XY.rem2 <- SpatialPoints(XY.rem, proj4string=CRS(as.character(NA)))#Turn into a spatial points layer
test <- extract(acc.ras, XY.rem2, buffer= 15000, cellnumbers=TRUE)
test2 <- lapply(test, function(x) x[complete.cases(x), ])
test3 <- pairs.rem <- seq(1, n.rem, 1)
for (i in 1:n.rem){
if (length(test2[[i]])<=2) {test3[i] <- test2[[i]][1]}
if (length(test2[[i]])>2) {test3[i] <- test2[[i]][sample(1:nrow(test2[[i]]),1)][1]}
if (length(test2[[i]])<=1) {test3[i] <- 0}
}
pairs.acc <- which(!is.na(test3))
pairs.acc<- sample(pairs.acc, n.acc, replace= FALSE)
XY.acc <- xyFromCell(acc.ras, test3[pairs.acc])
XY.acc2 <- SpatialPoints(XY.acc, proj4string=CRS(as.character(NA)))#Turn into a spatial points layer
XY.sites <- rbind(XY.rem, XY.acc) #Combine remote and non-remote site
XY.sites <- cbind(XY.sites,c(pairs.rem, pairs.acc))
colnames(XY.sites) <- c("x","y","pair.ID")
}
if (existing.sites == FALSE & all.existing.sites == FALSE & new.site.selection == "pairs") {
XY.acc <- XY.rem <- NULL
if (n.rem > 0){
notna <- which(!is.na(getValues(rem.ras)))
samp <- sample(notna, n.rem, replace = FALSE)
XY.rem <- xyFromCell(rem.ras, samp)
}
# if (n.rem > 0){XY.rem <- sampleRandom(rem.ras, n.rem, na.rm=TRUE, xy=TRUE)[,1:2]} #Sample 50% of sites at edge of burnt areas
XY.rem2 <- SpatialPoints(XY.rem, proj4string=CRS(as.character(NA)))#Turn into a spatial points layer
test <- extract(acc.ras, XY.rem2, buffer= 15000, cellnumbers=TRUE)
test2 <- lapply(test, function(x) x[complete.cases(x), ])
test3 <- pairs.rem <- seq(1,n.rem,1)
for (i in 1:n.rem){
if (length(test2[[i]])<=2) {test3[i] <- test2[[i]][1]}
if (length(test2[[i]])>2) {test3[i] <- test2[[i]][sample(1:nrow(test2[[i]]),1)][1]}
if (length(test2[[i]])<=1) {test3[i] <- 0}
}
pairs.acc <- which(!is.na(test3))
pairs.acc<- ample(pairs.acc, n.acc, replace= FALSE)
XY.acc <- xyFromCell(acc.ras, test3[pairs.acc])
XY.acc2 <- SpatialPoints(XY.acc, proj4string=CRS(as.character(NA)))#Turn into a spatial points layer
XY.sites <- rbind(XY.rem, XY.acc) #Combine remote and non-remote site
XY.sites <- cbind(XY.sites,c(pairs.rem,pairs.acc))
colnames(XY.sites) <- c("x","y","pair.ID")
}
if (plotter == TRUE) {
plot(remote, alpha = 0.5, main = new.site.selection)
if (new.site.selection == "stratified.pairs"){points(XY.sites, col = c("red", "orange"), pch =16, cex=0.5)}
else points(XY.sites, col = c("red"), pch =16, cex=0.5)
}
rm(acc.ras, rem.ras)
return(XY.sites)
}
#' Site cost function
#'
#This section calls upon cost.to.survey.site to return the cost to monitor a site given the species present, travel time and the detection methods used to find each species (taking into account survey duration and repeats),
#Up to four detection methods are assigned from species.detection (Step 3), with costs defined via detection.costs.
#Site locations are taken from xy.sites (Step 10), and travel time to each site is extracted from vic.road within the cost.to.survey.site function.
cost.to.survey.site<-function(zonationOutput, occ, sites, xy.sites, species.detection, species.detection.all, existing.sites, n.sites, s.years, n.method, group, vic.road, method.cost.array, overhead.cost, max.budget, plotter){
#Check site inputs. If existing load in, if not, random sample
sites <- xy.sites
#Rename exisiting sites colnames and drop any additional cols
sites<-sites[,1:2]
colnames(sites)<-c("POINT_X", "POINT_Y")
#Remove sites outside of analysis area
if (existing.sites == TRUE){
include.site<- extract(zonationOutput, sites[,1:2])
sites<- sites[!is.na(include.site),]
}
#Save object for plotting
input.sites<<- sites
#Make site occupancy logical
site.occ<- extract(occ, sites[1:nrow(sites), 1:2])
site.occ<- site.occ > 0
#Extract travel time
travel.time<- extract(vic.road, sites[,1:2])
travel.time<- cbind(sites[,1:2], travel.time)
for (i in 1:nrow(travel.time)){
if (is.na(travel.time[i,3])){travel.time[i,3]<- 200000}
}
#Rename
species.names<- species.list$Species
colnames(site.occ)<- species.names
#Pull out unique methods per site (each method must have a unique name and not include parts of another method)
method<- sort(unique(unlist(species.detection[,2:5])))
method<- method[method != ""]
#Set units to 0 if no overhead costs
if (overhead.cost == FALSE){method.cost.array[,4]<- 0} else {method.cost.array[,4]<- method.cost.array[, 4]}
method.cost.array[,6] = (method.cost.array[,2] * method.cost.array[,3]) + (method.cost.array[,4]+ method.cost.array[,5])
method.cost.array<- method.cost.array[, -c(2,3,4,5)]
method.cost<- unlist(method.cost.array[method.cost.array$method %in% method,][[2]])
# Create list of unique methods at each site (across all species)
site.cost<-list()
for(i in seq_len(nrow(site.occ))){
m1<- species.detection[ , "Method1"][site.occ[i,]]
m1<- unique(m1[m1 != ""])
m1 <- m1[!is.na(m1)]
m2<- species.detection[ , "Method2"][site.occ[i,]]
m2<- unique(m2[m2 != ""])
m2 <- m2[!is.na(m2)]
m3<- species.detection[ , "Method3"][site.occ[i,]]
m3<- unique(m3[m3 != ""])
m3 <- m3[!is.na(m3)]
m4<- species.detection[ , "Method4"][site.occ[i,]]
m4<- unique(m4[m4 != ""])
m4 <- m4[!is.na(m4)]
site.cost[[i]]<-list(m1, m2, m3, m4)
}
# Turn methods into numeric based on method.cost
for (i in seq_along(method)){
site.cost<- rapply(site.cost, function(x){gsub(method[i], method.cost[i], x)}, how = "list")
}
for (j in seq_along(site.cost)){
site.cost[[j]]<- lapply(site.cost[[j]], as.numeric)
}
for (j in seq_along(site.cost)){
for (i in seq_along(n.method)){
site.cost[[j]][[i]]<- unlist(site.cost[[j]][i])*n.method[i]
}
site.cost[[j]]<- sapply(site.cost[[j]], sum)
site.cost[[j]]<- sum(site.cost[[j]], na.rm = T)
}
#Total site cost
net.cost<- as.data.frame(unlist(site.cost))
colnames(net.cost)<- "survey.cost"
net.cost$siteID<- seq.int(nrow(net.cost))
#Figure out travel cost
travel.cost<- (120 + (120*0.016) * length(s.years))# travel cost as a variable to make it indexed ($) by year
net.cost$travel.cost<- ((travel.time[,3]/60 * travel.cost * mean(n.method) * 2) + 100) # return trip
net.cost$total.cost<- rowSums(net.cost[c(1, 3)])
net.cost$program.site.cost<- net.cost[4] * length(s.years)
project.costs<<- net.cost #push to global env.
# Outputs to console
#cat("Total sites:", n.sites, "\n")
#cat("Total budget:", format(max.budget, scientific = FALSE), "\n")
#cat("Program cost:", sum(project.costs$program.site.cost), "\n")
#if (sum(project.costs$program.site.cost)>max.budget){cat("Budget deficit:", sum(project.costs$program.site.cost)-max.budget, "\n")} else {cat("Budget surplus:", max.budget - sum(project.costs$program.site.cost), "\n")}
#cat("Average site cost:", colMeans(project.costs[,6]), "\n")
#if (plotter == TRUE) {plot(vic.road, main="Input Sites", alpha = 0.8)
#if (new.site.selection == "pairs"){points(input.sites, col = c("red", "black"), pch =16, cex=0.5)}
#else {points(input.sites, col = "red", pch =16, cex=0.5)}}
return(project.costs)
}
#This function removes sites over budget based on the site selection method.
remove.excess.site<- function(new.site.selection, project.costs, max.budget, all.existing.sites, det.method1.time, det.method2.time, det.method3.time, det.method4.time, occ.time, occ, plotter, xy.sites){
#No site alterating if keeping all sites
if (all.existing.sites == TRUE & existing.sites == TRUE){cat("All sites kept")}
#Random site selection: remove sites over budget by cheapest -> most expensive.
# if (new.site.selection == "random" & existing.sites != TRUE){
# project.costs<- project.costs[order(-project.costs$program.site.cost), ]
# project.costs$cumulative<- cumsum(project.costs$program.site.cost)
# project.costs<- project.costs[project.costs$cumulative < max.budget, ]
# n.sites<<- length(project.costs$siteID)
# xy.sites<<- xy.sites[project.costs$siteID, ]
#
# input.sites<<- xy.sites[,1:2]
# }
#Paired site selection across burnt and unburnt sites
#if (new.site.selection == "pairs" & existing.sites == FALSE){
if (new.site.selection == "pairs"){
project.costs <- cbind(project.costs, xy.sites[,4])
# project.costs<- project.costs[project.costs[1]!= 0, ]
colnames(project.costs) <- c("survey.cost","siteID","travel.cost","total.cost","program.cost", "pair.ID")
project.costs <- project.costs[with(project.costs, order(project.costs$pair.ID)),] #order by pair ID
project.costs$priority<- duplicated(project.costs$pair.ID) # which sites are paired
temp<- which(project.costs$priority == TRUE) # make logical
temp<- (c(temp, (temp-1))) #a dd paired site
temp<- sort(temp)
project.costs$priority[temp]<- -1
project.costs <- project.costs[with(project.costs, order(project.costs$priority, project.costs$pair.ID, decreasing = FALSE)),] #order by priority
temp<- rowsum(project.costs[,5], as.integer(gl(nrow(project.costs), 2, nrow(project.costs)))) #total cost of each paired site
temp<-as.vector(t(temp[rep(seq_along(nrow(temp)), 2)])) #duplicate and interleave so that nrow=n.sites
project.costs$site.sum<- temp
project.costs <- project.costs[with(project.costs, order(project.costs$priority, project.costs$site.sum)),] #order by pair cost
project.costs$cumulative<- cumsum(project.costs$program.cost)
if (max.budget >= project.costs[2,8]){project.costs<- project.costs[project.costs$cumulative < max.budget, ]}
if (max.budget < project.costs[2,8]){project.costs<- project.costs[1:2,]}
}
# #If monitoring all sites or method implies fixed sites assign below
# if (all.existing.sites == TRUE & new.site.selection == "maxocc"){
# det.method1.time<<- det.method1.time[project.costs$siteID,,]
# det.method2.time<<- det.method2.time[project.costs$siteID,,]
# det.method3.time<<- det.method3.time[project.costs$siteID,,]
# det.method4.time<<- det.method4.time[project.costs$siteID,,]
# occ.time<<- occ.time[project.costs$siteID,,]
# }
#Outputs to console
xy.sites<- xy.sites[project.costs$siteID, ]
if (plotter == TRUE) {plot(vic.road, main="Remaining Sites", alpha = 0.8)
if (new.site.selection == "pairs"){
points(subset(xy.sites, xy.sites[,3]==1), col = c("blue"), pch =16, cex=0.5)
points(subset(xy.sites, xy.sites[,3]==2), col = c("purple"), pch =16, cex=0.5)}
}
return(project.costs)
}
#' Significance level function
#'
#' This function returns a critical value needed to calculate confidence intervals around the trend parameter given the Type I error rate and whether it is a one or two-tailed significance test.
#' @param two.tailed Set to TRUE for a two-tailed test, FALSE for a one-tailed test.
#' @param alpha Set the type one error rate. Choose between 0.1, 0.05 and 0.01
#' @keywords
#' @export
#' @examples
#' two.tailed <- TRUE
#' alpha <- 0.05
#' sig.test(two.tailed, alpha)
sig.test <- function(two.tailed, alpha) {
values <- matrix(c(1.28, 1.645, 1.65, 1.96, 2.33, 2.58), ncol=3, nrow=2)
if (two.tailed == TRUE) {ind <- 2} else {ind <- 1}
if (alpha == 0.1) {value <- values[ind,1]}
if (alpha == 0.05) {value <- values[ind,2]}
if (alpha == 0.01) {value <- values[ind,3]}
return(value)
}
#' Run power analysis
#'
#' This function runs the main power analysis. It starts by creating empty vectors to record the number of times a significant trend is detected in the simulated detection histories
#' It then simulates fire at sites if model.fire = TRUE, and models a decline in occupancy over time depending on the specified effect size.
#' Detection histories are simulated at each site given the occupancy status at each site, the number of survey methods used to detect a species and the detection probability of each relevent method.
#' Simulated detection histories are loaded into the package unmarked, and a trend in occupancy is modelled over time. The proportion of times a significant trend is detected is recorded.
#' This process is repeated for each effect size.
#' @param effect.size An integer specifying the proportional reduction in occupancy between the start and end of the monitoring program
#' @param nsims An integer specifying the number of simulations
#' @param alpha The Type I error rate. Must be either 0.1, 0.05 or 0.01
#' @param decline Specifies the pattern of decline across space. Set to 'random' to model a constant 'blanket' decline across space
#' @param Tmax An integer specifying the length of the monitoring program
#' @param s.years A vector specifying the years in which monitoring occurs. Note, the final year or monitoring must be equal to Tmax
#' @param sites An array containing the XY coordinates of pre-specified monitoring sites
#' @param fire.hist Delete
#' @param model.fire Set to TRUE if the incidence of fire is modelled at sites, FALSE to model a static landscape over time
#' @param species.list An array containing the name of each species in the first column, and a zero or one describing how many methods are used to detect the species
#' @param park.level Set to TRUE if power is to be estimated within sub-level management units
#' @param fire.fr Delete
#' @param combined.effect An array that records the reduction in occupancy across sites due to the effect size and fire
#' @param xy.sites The XY coordinates of monitoring sites
#' @param two.tailed Set to TRUE is conducting a two-tailed significance test, FALSE if conducting a one-tailed test
#' @param plotter Set to TRUE to plot the location of sites at the start of each simulation, FALSE otherwise
#' @param n.sites The number of sites to be monitored.
#' @param n.species The number of species for which monitoring is simulated. Is equal to the number of layers in the occ raster stack
#' @param n.park The number of sub-level management units in which power is estimated
#' @param randomise.sites Set to TRUE if sites are to randomly selected for monitoring, FALSE if pre-specified sites are surveyed
#' @param all.existing.sites Set to TRUE if all of the prespecified sites are to be monitored, FALSE if fewer or more sites are to be monitored
#' @param occ.new An array containing the occupancy value for each species at monitoring sites over time
#' @param occ.time An array containing the occupancy value for each species at monitoring sites over time
#' @param det.method1.new An array containing the detectability values of method 1 for each species at monitoring sites over time
#' @param det.method2.new An array containing the detectability values of method 2 for each species at monitoring sites over time
#' @param det.method3.new An array containing the detectability values of method 3 for each species at monitoring sites over time
#' @param det.method1.time An array containing the detectability values of method 1 for each species at monitoring sites over time
#' @param det.method2.time An array containing the detectability values of method 2 for each species at monitoring sites over time
#' @param det.method3.time An array containing the detectability values of method 3 for each species at monitoring sites over time
#' @param det1.method1 An array that records simulated detection histories at sites using method 1
#' @param det1.method2 An array that records simulated detection histories at sites using method 2
#' @param det1.method3 An array that records simulated detection histories at sites using method 3
#' @param fire.freq Delete!
#' @param n.method1 The number of repeat visits to sites using method 1
#' @param n.method2 The number of repeat visits to sites using method 2
#' @param n.method3 The number of repeat visits to sites using method 3
#' @keywords
#' @export
#' @examples
#' run.power()
#Run pwr analysis at a regional level
#run.power <- function(effect.size, nsims, alpha, det1, working.raster, decline, plot.decline, plot.fire, Tmax, s.years, n.remote, n.4WD, sites, fire.hist, burn.area, study.area, model.fire, species.list, park.level, fire.fr, combined.effect, xy.sites) {
#run.power <- function(effect.size, nsims, alpha, working.raster, decline, Tmax, s.years, sites, fire.hist, model.fire, species.list, park.level, fire.fr, combined.effect, xy.sites, two.tailed, plotter, n.sites, n.species, n.park, randomise.sites, all.existing.sites) {
run.power <- function(effect.size, nsims, alpha, decline, Tmax, s.years, sites, model.fire, species.list, park.level, xy.sites, R, two.tailed, plotter, n.sites, n.species, n.park, all.existing.sites, existing.sites, new.site.selection, n.method, occ, det.method1, det.method2, det.method3, det.method4, veg, remote, parks, trend, variation, model.variation, zonationOutput, species.detection, species.detection.all, group, vic.road, method.cost.array, overhead.cost, max.budget, project.costs, init.sites, prop.man, man.effect.size, init.occ.burnt, program.cost) { #}, occ.time, det.method1.time, det.method2.time, det.method3.time, det.method4.time) {
det.method1.time<- det.method2.time<- det.method3.time<- det.method4.time<- occ.time<- array(0, dim = c(n.sites, n.species, Tmax)) #Create empty arrays
occ.time[,, s.years]<- occ[cellFromXY(occ, xy.sites)] #Extract occupancy values from monitoring sites
occ.time[,, s.years]<- ifelse(is.na(occ.time[,, s.years]), 0, (occ.time[,, s.years])) #turn NA to 0
for (ss in 1:n.species){
if (species.list[ss,2] == 1) {det.method1.time[, ss, s.years]<- det.method1[[ss]][cellFromXY(det.method1[[ss]], xy.sites)]} #Extract detectability values from sites using method 1
if (species.list[ss,3] == 1) {det.method2.time[, ss, s.years]<- det.method2[[ss]][cellFromXY(det.method2[[ss]], xy.sites)]} #Extract detectability values from sites using method 2
if (species.list[ss,4] == 1) {det.method3.time[, ss, s.years]<- det.method3[[ss]][cellFromXY(det.method3[[ss]], xy.sites)]} #Extract detectability values from sites using method 3
if (species.list[ss,5] == 1) {det.method4.time[, ss, s.years]<- det.method4[[ss]][cellFromXY(det.method4[[ss]], xy.sites)]}
}
det1.method1 <- array(NA, dim=c(n.sites,n.species,n.method[1],Tmax))
det1.method2 <- array(NA, dim=c(n.sites,n.species,n.method[2],Tmax))
det1.method3 <- array(NA, dim=c(n.sites,n.species,n.method[3],Tmax))
det1.method4 <- array(NA, dim=c(n.sites,n.species,n.method[4],Tmax))
det.method1.new <- det.method2.new <- det.method3.new <- det.method4.new <- occ.new <- array(0, dim=c(n.sites,n.species,Tmax))
combined.effect <- matrix(NA, nsims, n.species)
total.cost <- rep(program.cost, nsims)
total.sites <- rep(n.sites, nsims)
fr.hist <- time.hist <-veg.ID <- park.ID <- rep(NA,n.sites)
time.fire <- array(NA, dim=c(n.sites,Tmax))
fire.freq <- array(NA, dim=c(n.sites,Tmax))
#Set up vectors and matrices to record the number of instances when we detect a change in occupancy
powcnt <-rep(0,n.species)
pow.park <- matrix(0,ncol=n.species,nrow=length(n.park))
fail <- rep(0,n.species)
fail.park <- matrix(0,ncol=n.species,nrow=length(n.park))
for (ii in 1:nsims){ #Loop through number of simulations from 1 to nsims
cat('\n',"Effect size = ", effect.size, " Simulation = ", ii)
#Select survey sites
if (existing.sites == FALSE & new.site.selection == "pairs") {
cat('\n',"Selecting survey sites.....")
n.sites <- init.sites
xy.sites <- select.sites(sites=sites, n.sites=n.sites, R=R, all.existing.sites=all.existing.sites, existing.sites=existing.sites, new.site.selection=new.site.selection, plotter=plotter, occ=occ, zonationOutput=zonationOutput) #Returns matrix of XY coordinates plus description for which park each point belongs in
park.ID <- parks[cellFromXY(parks, xy.sites)]
xy.sites <- cbind(xy.sites[,1:2],park.ID,xy.sites[,3])
cat('\n',"Estimating cost.....")
project.costs <- cost.to.survey.site(zonationOutput, occ, sites, xy.sites, species.detection, species.detection.all, existing.sites, n.sites, s.years, n.method, group, vic.road, method.cost.array, overhead.cost, max.budget, plotter)
cat('\n',"Removing excess sites.....")
print(nrow(xy.sites))
program.cost <- remove.excess.site(new.site.selection, project.costs, max.budget, all.existing.sites, det.method1.time, det.method2.time, det.method3.time, det.method4.time, occ.time, occ, plotter, xy.sites)
xy.sites<- xy.sites[program.cost$siteID, ]
n.sites<- nrow(xy.sites)
program.cost <- sum(program.cost$program.cost)
cat('\n',"Finished removing excess sites.....")
print(nrow(xy.sites))
print(n.sites)
total.cost[ii] <- program.cost
total.sites[ii] <- n.sites
if (n.method[1]==0){n.method[1]<- 2}
det1.method1 <- array(NA, dim=c(n.sites,n.species,n.method[1],Tmax))
if (n.method[2]==0){n.method[2]<- 2}
det1.method2 <- array(NA, dim=c(n.sites,n.species,n.method[2],Tmax))
if (n.method[3]==0){n.method[3]<- 2}
det1.method3 <- array(NA, dim=c(n.sites,n.species,n.method[3],Tmax))
if (n.method[4]==0){n.method[4]<- 2}
det1.method4 <- array(NA, dim=c(n.sites,n.species,n.method[4],Tmax))
det.method1.new <- det.method2.new <- det.method3.new <- det.method4.new <- occ.new <- array(0, dim=c(n.sites,n.species,Tmax))
det.method1.time<- det.method2.time<- det.method3.time<- det.method4.time<- occ.time<- array(0, dim = c(n.sites, n.species, Tmax)) #Create empty arrays
#occ.time[,, s.years]<- occ[cellFromXY(occ, xy.sites[,1:2])] #Extract occupancy values from monitoring sites
fr.hist <- time.hist <-veg.ID <- park.ID <- rep(NA,n.sites)
time.fire <- array(NA, dim=c(n.sites,Tmax))
fire.freq <- array(NA, dim=c(n.sites,Tmax))
#Extract occ and det values from selected sites
cat('\n',"Extracting values from selected sites.....")
occ.time[,,s.years] <- occ[cellFromXY(occ, xy.sites[,1:2])]
occ.time[,, s.years]<- ifelse(is.na(occ.time[,, s.years]), 0, (occ.time[,, s.years])) #turn NA to 0
for (ss in 1:n.species){
if (species.list[ss,2] == 1) {det.method1.time[,ss,s.years] <- det.method1[[ss]][cellFromXY(det.method1[[ss]], xy.sites)]}
if (species.list[ss,3] == 1) {det.method2.time[,ss,s.years] <- det.method2[[ss]][cellFromXY(det.method2[[ss]], xy.sites)]}
if (species.list[ss,4] == 1) {det.method3.time[,ss,s.years] <- det.method3[[ss]][cellFromXY(det.method3[[ss]], xy.sites)]}
if (species.list[ss,5] == 1) {det.method4.time[,ss,s.years] <- det.method4[[ss]][cellFromXY(det.method4[[ss]], xy.sites)]}
}
}
#Extract park ID, veg type and fire histories from selected sites
managed <- rep(0,nrow(xy.sites))
managed[sample(nrow(xy.sites), round(nrow(xy.sites)*prop.man))] <- 1
xy.sites <- cbind(xy.sites, managed)
#Make a copy of the occ and det values at each site so they can be manipulated by fire and the effect size over time
det.method1.new[] <- det.method1.time
det.method2.new[] <- det.method2.time
det.method3.new[] <- det.method3.time
det.method4.new[] <- det.method4.time
occ.new[] <- occ.time
#Model fire at monitoring sites if the model.fire == TRUE
if (model.fire == TRUE) { #If we specified that fire be modelled then simulate fire spread during the year
cat('\n',"Modelling fire and updating occ and det layers.....")
fire.ID <- matrix(NA, nrow = n.sites, ncol=nlayers(fire) + Tmax)
veg.ID <- veg[cellFromXY(veg, xy.sites)]
layers <- covar[cellFromXY(covar, xy.sites)]
fire.ID[,1:nlayers(fire)] <- fire[cellFromXY(fire, xy.sites)]
time.hist <- apply(fire.ID[,1:nlayers(fire)], 1, function(x) (nlayers(fire)+1)-max(which(x==1))) #time.hist <- round(fire.hist[cellFromXY(fire.hist, xy.sites)]) #time.fire <-
fr.hist <- rowSums(fire.ID[,1:nlayers(fire)]) #fire.freq <- rowSums(fire.ID[,1:nlayers(fire)])
for (jj in 1:Tmax) { #For each simulation loop ii, loop through time from 1 to Tmax
#burn <- fire.point.model(time.hist, time.fire, veg.ID, jj) #Simulate whether monitoring sites burn
burn <- fire.point.model2(time.hist, jj)
fire.ID[,nlayers(fire) + jj] <- burn #Record fire history at sites for year jj
if (jj==1) {
time.fire[,jj] <- ifelse(burn == 1, 1, time.hist+1)
fire.freq[,jj] <- rowSums(fire.ID[, (jj+1):(jj+nlayers(fire))]) #Sum number of fires in 15 year moving window
}
if (jj>1) {
time.fire[,jj] <- ifelse(burn == 1, 1, time.fire[,jj-1]+1)
fire.freq[,jj] <- rowSums(fire.ID[, (jj+1):(jj+nlayers(fire))]) #Sum number of fires in 15 year moving window
}
if (jj %in% s.years) {
occ.new <- refit.occ(occ.new, layers, time.fire, fire.freq, jj, veg.ID)
det.out <- refit.det(det.method1.new=det.method1.new, det.method2.new=det.method2.new, det.method3.new=det.method3.new, det.method4.new=det.method4.new, layers, time.fire, fire.freq, jj)
}
}
det.method1.new[] <- det.out[[1]]
det.method2.new[] <- det.out[[2]]
det.method3.new[] <- det.out[[3]]
det.method4.new[] <- det.out[[4]]
}
#Make occupancy in burnt areas zero for all species
occ.new[which(xy.sites[,3]==1),,] <- init.occ.burnt
if (trend == "decreasing") { #Model decreasing trend
effect.time <- 1-(effect.size/Tmax*c(1:Tmax))
effect.time.man <- 1-((effect.size+man.effect.size)/Tmax*c(1:Tmax))
if (model.variation == TRUE) {
effect.time <- runif(Tmax,effect.time-variation[ss]/2, effect.time+variation[ss]/2)
effect.time[effect.time>1] <- 1
effect.time[effect.time<0] <- 0
}
for (i in 1:Tmax) {occ.new[which(xy.sites[,5]==0),,i] <- occ.new[which(xy.sites[,5]==0),,i]*effect.time[i]}
for (i in 1:Tmax) {occ.new[which(xy.sites[,5]==1),,i] <- occ.new[which(xy.sites[,5]==0),,i]*effect.time.man[i]}
#for (i in 1:Tmax) {occ.new[,,i] <- occ.new[,,i]*effect.time[i]}
}
if (trend == "increasing") { #Model increasing trend
effect.time <- effect.size/Tmax*c(1:Tmax)
effect.time.man <- (effect.size+man.effect.size)/Tmax*c(1:Tmax)
if (model.variation == TRUE) {
effect.time <- runif(Tmax, effect.time-variation[ss]/2,effect.time+variation[ss]/2)
effect.time[effect.time>1] <- 1
effect.time[effect.time<0] <- 0
}
for (i in 1:Tmax) {occ.new[which(xy.sites[,5]==0),,i] <- occ.new[which(xy.sites[,5]==0),,i] + ((occ.time[which(xy.sites[,5]==0),,i]-occ.new[which(xy.sites[,5]==0),,i])*effect.time[i])}
for (i in 1:Tmax) {occ.new[which(xy.sites[,5]==1),,i] <- occ.new[which(xy.sites[,5]==1),,i] + ((occ.time[which(xy.sites[,5]==1),,i]-occ.new[which(xy.sites[,5]==1),,i])*effect.time.man[i])}
#for (i in 1:Tmax) {occ.new[,,i] <- occ.new[,,i] + ((occ.time[,,i]-occ.new[,,i])*effect.time[i])}
}
combined.effect[ii,] <- (occ.time[1,,1]-occ.new[1,,Tmax])/occ.time[1,,1]
if (decline== "random") {
for (i in 1:Tmax) {
occ.new[,,i] <- ifelse(runif(ncell(occ.new[,,i])) < occ.new[,,i],1,0)
}
}
cat('\n',"Simulating monitoring at sites.....")
for (jj in 1:n.method[1]){
for (tt in 1:Tmax) { #MIGHT BE ABLE TO REMOVE TT LOOP
det1.method1[,,jj,tt] <- ifelse(runif(ncell(det.method1.new[,,tt])) < det.method1.new[,,tt] & occ.new[,,tt] == 1, 1, 0)
}}
for (jj in 1:n.method[2]){
for (tt in 1:Tmax) { #MIGHT BE ABLE TO REMOVE TT LOOP
det1.method2[,,jj,tt] <- ifelse(runif(ncell(det.method2.new[,,tt])) < det.method2.new[,,tt] & occ.new[,,tt] == 1, 1, 0)
}
}
for (jj in 1:n.method[3]){
for (tt in 1:Tmax) { #MIGHT BE ABLE TO REMOVE TT LOOP
det1.method3[,,jj,tt] <- ifelse(runif(ncell(det.method3.new[,,tt])) < det.method3.new[,,tt] & occ.new[,,tt] == 1 ,1,0)
}
}
for (jj in 1:n.method[4]){
for (tt in 1:Tmax) { #MIGHT BE ABLE TO REMOVE TT LOOP
det1.method4[,,jj,tt] <- ifelse(runif(ncell(det.method4.new[,,tt])) < det.method4.new[,,tt] & occ.new[,,tt] == 1 ,1,0)
}
}
#Combine the results of each detection method for each species, create detection histories and fit occupancy model
cat('\n',"Fitting occ model.....")
value <- sig.test(two.tailed, alpha)
methods <- list(det1.method1,det1.method2,det1.method3,det1.method4)
for (ss in 1:n.species) {
#Fit occ model for species detected using method 1
if (sum(species.list[ss,-1]) == 1) {
pos <- which(species.list[ss,-1]==1)
occ.fit <- fit.occ.1method(method=methods[[pos]], repeats=n.method[pos], s.years, n.sites, xy.sites, park.ID, park.level, powcnt, fail, pow.park, fail.park, value, ss, two.tailed, n.park)
}
#Fit occ model for species detected using 2 methods
if (sum(species.list[ss,-1]) == 2) {
pos <- which(species.list[ss,-1]==1)
occ.fit <- fit.occ.2method(method1=methods[[pos[1]]], method2=methods[[pos[2]]], repeats1=n.method[pos[1]], repeats2=n.method[pos[2]], s.years, n.sites, xy.sites, park.ID, park.level, powcnt, fail, pow.park, fail.park, value, ss, two.tailed, n.park)
}
#Fit occ model for species detected using 3 methods
if (sum(species.list[ss,-1]) == 3) {
pos <- which(species.list[ss,-1]==1)
occ.fit <- fit.occ.3method(method1=methods[[pos[1]]], method2=methods[[pos[2]]], method3=methods[[pos[3]]], repeats1=n.method[pos[1]], repeats2=n.method[pos[2]], repeats3=n.method[pos[3]], s.years, n.sites, xy.sites, park.ID, park.level, powcnt, fail, pow.park, fail.park, value, ss, two.tailed, n.park)
}
#Fit occ model for species detected using 4 methods
if (sum(species.list[ss,-1]) == 4) {
pos <- which(species.list[ss,-1]==1)
occ.fit <- fit.occ.4method(method1=methods[[pos[1]]], method2=methods[[pos[2]]], method3=methods[[pos[3]]], method4=methods[[pos[4]]], repeats1=n.method[pos[1]], repeats2=n.method[pos[2]], repeats3=n.method[pos[3]], repeats4=n.method[pos[4]], s.years, n.sites, xy.sites, park.ID, park.level, powcnt, fail, pow.park, fail.park, value, ss, two.tailed, n.park)
}
#Fit occ model for species only detected using method 1
#if (species.list[ss,2] == 1 & species.list[ss,3] == 0 & species.list[ss,4] == 0) {
#occ.fit <- fit.occ.1method(method=det1.method1, repeats=n.method[1], s.years, n.sites, xy.sites, park.ID, park.level, powcnt, fail, pow.park, fail.park, value, ss, two.tailed, n.park)
# }
#Sit occ model for species only detected using method 2
#if (species.list[ss,2] == 0 & species.list[ss,3] == 1 & species.list[ss,4] == 0) {
#occ.fit <- fit.occ.1method(method=det1.method2, repeats=n.method[2], s.years, n.sites, xy.sites, park.ID, park.level, powcnt, fail, pow.park, fail.park, value, ss, two.tailed, n.park)
#}
#Fit occ model for species only detected using method 3
#if (species.list[ss,2] == 0 & species.list[ss,3] == 0 & species.list[ss,4] == 1) {
# occ.fit <- fit.occ.1method(method=det1.method3, repeats=n.method[3], s.years, n.sites, xy.sites, park.ID, park.level, powcnt, fail, pow.park, fail.park, value, ss, two.tailed, n.park)
#}
#Fit occ model for species detected using method 1 and 2
#if (species.list[ss,2] == 1 & species.list[ss,3] == 1 & species.list[ss,4] == 0) {
#occ.fit <- fit.occ.2method(method1=det1.method1, method2=det1.method2, repeats1=n.method[1], repeats2=n.method[2], s.years, n.sites, xy.sites, park.ID, park.level, powcnt, fail, pow.park, fail.park, value, ss, two.tailed, n.park)
# }
#Fit occ model for species detected using method 1 and 3
# if (species.list[ss,2] == 1 & species.list[ss,3] == 0 & species.list[ss,4] == 1) {
# occ.fit <- fit.occ.2method(method1=det1.method1, method2=det1.method3, repeats1=n.method[1], repeats2=n.method[3], s.years, n.sites, xy.sites, park.ID, park.level, powcnt, fail, pow.park, fail.park, value, ss, two.tailed, n.park)
#}
#Fit occ model for species detected using method 2 and 3
# if (species.list[ss,2] == 0 & species.list[ss,3] == 1 & species.list[ss,4] == 1) {
#occ.fit <- fit.occ.2method(method1=det1.method2, method2=det1.method3, repeats1=n.method[2], repeats2=n.method[3], s.years, n.sites, xy.sites, park.ID, park.level, powcnt, fail, pow.park, fail.park, value, ss, two.tailed, n.park)
# }
#Fit occ model for species detected using methods 1, 2 and 3
# if (species.list[ss,2] == 1 & species.list[ss,3] == 1 & species.list[ss,4] == 1) {
# occ.fit <- fit.occ.3method(method1=det1.method1, method2=det1.method2, method3=det1.method3, repeats1=n.method[1], repeats2=n.method[2], repeats3=n.method[3], s.years, n.sites, xy.sites, park.ID, park.level, powcnt, fail, pow.park, fail.park, value, ss, two.tailed, n.park)
# }
powcnt <- occ.fit[[1]]
fail <- occ.fit[[2]]
pow.park <- occ.fit[[3]]
fail.park <- occ.fit[[4]]
} #End species loop
} #End sims loop (ii)
#Calculate pwr from simulations for each species
combined.effect <- colMeans(combined.effect)
mean.cost <- mean(total.cost)
mean.sites <- round(mean(total.sites))
output <- rbind(powcnt, fail, pow.park, fail.park, rep(mean.cost, n.species)) #If running in parallel
return(output)
}
#' Fit occupancy model with one detection method
#'
#' This function fits an occupancy model to simulated detection histories using the package unmarked for species that are detected using one detection method
#' A trend in occupancy is estimated and confidence intervals are calculated depending on the Type I error rate. A one-tailed or two-tailed significance test is then conducted on the trend parameter
#' A one-tailed test looks to see if the upper or lower confidence interval is greater than or less than zero. A two-tailed test assesses whether both the upper and lower confidence
#' intervals have the same sign (i.e. are both positive or negative). If park.power = TRUE, model fitting is repeated on sites from each regional level management unit.
#' @param method The detection method relevant to species ss
#' @param repeats The number of repeat visits for the specified detection method
#' @param s.years A vector specifying the years that monitoring occurs. Note, monitoring must be done in the final year (i.e. Tmax)
#' @param n.sites The number of sites monitored
#' @param xy.sites The XY coordinates of monitored sites
#' @param park.ID A vector specifying that location of each site with sub-level parks
#' @param park.level Set to TRUE is power is estimated within regional level management unit, FALSE otherwise
#' @param powcnt A vector that keeps track of how many times a significant trend in occupancy is detected across the landscape
#' @param fail A vector that keeps track of how many times the occupancy model could not be fitted to simulated detection histories at a landscape level in unmarked
#' @param pow.park A vector that keeps track of how many times a significant trend in occupancy is detected within each park
#' @param fail.park A vector that keeps track of how many times the occupancy model could not be fitted to simulated detection histories at a park level in unmarked
#' @param value The critical value used to calculate confidence intervals around the trend parameter, depending on the Type I error rate and a one-tailed or two-tailed test
#' @param ss An index to loop through each species
#' @param two.tailed Set to TRUE if conducting a two-tailed test, FALSE otherwise
#' @keywords
#' @export
#' @examples
#' fit.occ.1method()
#Function to fit occupancy model when only 1 method is used to detect species s
fit.occ.1method <- function(method, repeats, s.years, n.sites, xy.sites, park.ID, park.level, powcnt, fail, pow.park, fail.park, value, ss, two.tailed, n.park) {
if (repeats == 1) {
y <- aperm(method[,ss,,s.years],c(1,2))
dim(y)<- c(n.sites*length(s.years), repeats)
} else {
y <- aperm(method[,ss,,s.years],c(1,3,2))
dim(y)<- c(n.sites*length(s.years), repeats)
}
siteCovs <- data.frame(matrix(rep(s.years,each=nrow(xy.sites)),nrow(xy.sites)*length(s.years),1))
park.ID.year <- rep(xy.sites[,3], length(s.years))
park.ID.year[park.ID.year==2] <- 0
siteCovs <- cbind(siteCovs, park.ID.year)
colnames(siteCovs) <- c("Time", "Burnt")
siteCovs$Burnt <- factor(siteCovs$Burnt, levels=c(0,1))
#if 1 repeat use logistic regression
if (repeats == 1) {
Time <- siteCovs[,1]
y <- as.vector(y)
mod <- glm(formula = y ~ Time, family=binomial)
if (is(mod,"try-error")) {fail[ss] <- fail[ss] + 1} else {
Time.mean <- summary(mod)$coefficients[2,1]
Time.CI <- summary(mod)$coefficients[2,2] * value
Time.coeff<-summary(mod)$coefficients[2,1]
Time.SE<-summary(mod)$coefficients[2,2]
if (two.tailed == TRUE & sign(Time.mean + Time.CI) == sign(Time.mean - Time.CI)) {
powcnt[ss] <- powcnt[ss] + 1}
if (two.tailed == FALSE & (Time.mean + Time.CI < 0 | Time.mean - Time.CI > 0)) {
powcnt[ss] <- powcnt[ss] + 1}
}
}
if (repeats > 1) {
umf <- unmarkedFrameOccu(y = y, siteCovs = siteCovs, obsCovs = NULL)
#inits<- rbind(c(0,0,0),c(-1,-1,-1),c(1,1,1))
inits<- rbind(c(0,0,0,0,0),c(-1,-1,-1,-1,-1),c(1,1,1,1,1))
for (vv in 1:nrow(inits)) {
mod<- try(occu(~1 ~Time*Burnt, umf, control=list(maxit=1000000), starts=inits[vv,]), silent=TRUE)
if (!is(mod,"try-error")){break}
}
#}
if (is(mod,"try-error")) {fail[ss] <- fail[ss] + 1} else {
if (!is.na(SE(mod['state'])[4])) {
Time.mean <- coef(mod)[4]
Time.CI <- SE(mod)[4] * value
if (two.tailed == TRUE & sign(Time.mean + Time.CI) == sign(Time.mean - Time.CI)) { #Add on-tailed test option here
powcnt[ss] <- powcnt[ss] + 1}
if (two.tailed == FALSE & (Time.mean + Time.CI < 0 | Time.mean - Time.CI > 0)) { #Add on-tailed test option here
powcnt[ss] <- powcnt[ss] + 1}
} else {fail[ss] <- fail[ss] + 1}}
}
if (park.level == TRUE) {
for (pp in n.park) {
park.site <- which(xy.sites[,3] == pp)
if (length(park.site) == 0) {pow.park[pp,ss] <- pow.park[pp,ss]}
if (length(park.site) > 0) {
y.park <- umf[which(park.ID.year == pp),]
inits<- rbind(c(0,0,0),c(-1,-1,-1),c(1,1,1))
for (vv in 1:nrow(inits)) {
mod<- try(occu(~1 ~Time, y.park, control=list(maxit=1000000), starts=inits[vv,]), silent=TRUE)
if (!is(mod,"try-error")){break}
}
if (is(mod,"try-error")) {fail.park[pp,ss] <- fail.park[pp,ss] + 1} else {
if (!is.na(SE(mod['state'])[1])) {
Time.mean <- coef(mod)[2]
Time.CI <- SE(mod)[2] * value
if (two.tailed == TRUE & sign(Time.mean + Time.CI) == sign(Time.mean - Time.CI)) { #Add on-tailed test option here
pow.park[pp,ss] <- pow.park[pp,ss] + 1}
if (two.tailed == FALSE & (Time.mean + Time.CI < 0 | Time.mean - Time.CI > 0)) { #Add on-tailed test option here
pow.park[pp,ss] <- pow.park[pp,ss] + 1}
} else {fail.park[pp,ss] <- fail.park[pp,ss] + 1}}
}
}
}
return(list(powcnt, fail, pow.park, fail.park))
}
#' Fit occupancy model with two detection methods
#'
#' This function fits an occupancy model to simulated detection histories using the package unmarked for species that are detected using two detection methods
#' A trend in occupancy is estimated and confidence intervals are calculated depending on the Type I error rate. A one-tailed or two-tailed significance test is then conducted on the trend parameter
#' A one-tailed test looks to see if the upper or lower confidence interval is greater than or less than zero. A two-tailed test assesses whether both the upper and lower confidence
#' intervals have the same sign (i.e. are both positive or negative). If park.power = TRUE, model fitting is repeated on sites from each regional level management unit.
#' @param method1 The first detection method relevant to species ss
#' @param method2 The second detection method relevant to species ss
#' @param repeats1 The number of repeat visits for the first detection method
#' @param repeats2 The number of repeat visits for the second detection method
#' @param s.years A vector specifying the years that monitoring occurs. Note, monitoring must be done in the final year (i.e. Tmax)
#' @param n.sites The number of sites monitored
#' @param xy.sites The XY coordinates of monitored sites
#' @param park.ID A vector specifying that location of each site with sub-level parks
#' @param park.level Set to TRUE is power is estimated within regional level management unit, FALSE otherwise
#' @param powcnt A vector that keeps track of how many times a significant trend in occupancy is detected across the landscape
#' @param fail A vector that keeps track of how many times the occupancy model could not be fitted to simulated detection histories at a landscape level in unmarked
#' @param pow.park A vector that keeps track of how many times a significant trend in occupancy is detected within each park
#' @param fail.park A vector that keeps track of how many times the occupancy model could not be fitted to simulated detection histories at a park level in unmarked
#' @param value The critical value used to calculate confidence intervals around the trend parameter, depending on the Type I error rate and a one-tailed or two-tailed test
#' @param ss An index to loop through each species
#' @param two.tailed Set to TRUE if conducting a two-tailed test, FALSE otherwise
#' @keywords
#' @export
#' @examples
#' fit.occ.2method()
#Function to fit occupancy model when only 2 methods are used to detect species s
fit.occ.2method <- function(method1, method2, repeats1, repeats2, s.years, n.sites, xy.sites, park.ID, park.level, powcnt, fail, pow.park, fail.park, value, ss, two.tailed, n.park) {
if (repeats1 == 1) {
y1 <- aperm(method1[,ss,,s.years],c(1,2))
dim(y1)<- c(n.sites*length(s.years), repeats1)
} else {
y1 <- aperm(method1[,ss,,s.years],c(1,3,2))
dim(y1)<- c(n.sites*length(s.years), repeats1)
}
if (repeats2 == 1) {
y2 <- aperm(method2[,ss,,s.years],c(1,2))
dim(y2)<- c(n.sites*length(s.years), repeats2)
} else {
y2 <- aperm(method2[,ss,,s.years],c(1,3,2))
dim(y2)<- c(n.sites*length(s.years), repeats2)
}
siteCovs <- data.frame(matrix(rep(s.years,each=nrow(xy.sites)),nrow(xy.sites)*length(s.years),1))
park.ID.year <- rep(xy.sites[,3], length(s.years))
park.ID.year[park.ID.year==2] <- 0
siteCovs <- cbind(siteCovs, park.ID.year)
colnames(siteCovs) <- c("Time", "Burnt")
siteCovs$Burnt <- factor(siteCovs$Burnt, levels=c(0,1))
m1.code <- matrix(factor(1),nrow=nrow(xy.sites)*length(s.years), ncol=repeats1)
m2.code <- matrix(factor(2),nrow=nrow(xy.sites)*length(s.years), ncol=repeats2)
obsCovs <- data.frame(as.matrix(cbind(m1.code,m2.code)))
colnames(obsCovs) <- c(rep("M1",repeats1),rep("M2",repeats2))
umf <- unmarkedFrameOccu(y = cbind(y1, y2), siteCovs = siteCovs, obsCovs = list(METHOD = obsCovs))
#inits<- rbind(c(0,0,0,0),c(-1,-1,-1,-1),c(1,1,1,1))
inits<- rbind(c(0,0,0,0,0,0),c(-1,-1,-1,-1,-1,-1),c(1,1,1,1,1,1))
for (vv in 1:nrow(inits)) {
mod<- try(occu(~METHOD ~Time*Burnt, umf, control=list(maxit=1000000), starts=inits[vv,]), silent=TRUE)
if (!is(mod,"try-error")){break}
}
if (is(mod,"try-error")) {fail[ss] <- fail[ss] + 1} else {
if (!is.na(SE(mod['state'])[4])) {
Time.mean <- coef(mod)[4]
Time.CI <- SE(mod)[4] * value
if (two.tailed == TRUE & sign(Time.mean + Time.CI) == sign(Time.mean - Time.CI)) { #Add on-tailed test option here
powcnt[ss] <- powcnt[ss] + 1}
if (two.tailed == FALSE & (Time.mean + Time.CI < 0 | Time.mean - Time.CI > 0)) { #Add on-tailed test option here
powcnt[ss] <- powcnt[ss] + 1}
} else {fail[ss] <- fail[ss] + 1}}
if (park.level == TRUE) {
for (pp in n.park) {
park.site <- which(xy.sites[,3] == pp)
if (length(park.site) == 0) {pow.park[pp,ss] <- pow.park[pp,ss]}
if (length(park.site) > 0) {
y.park <- umf[which(park.ID.year == pp),]
inits<- rbind(c(0,0,0,0),c(-1,-1,-1,-1),c(1,1,1,1))
for (vv in 1:nrow(inits)) {
mod<- try(occu(~METHOD ~Time, y.park, control=list(maxit=10000), starts=inits[vv,]), silent=TRUE)
if (!is(mod,"try-error")){break}
}
if (is(mod,"try-error")) {fail.park[pp,ss] <- fail.park[pp,ss] + 1} else {
if (!is.na(SE(mod['state'])[1])) {
Time.mean <- coef(mod)[2]
Time.CI <- SE(mod)[2] * value
if (two.tailed == TRUE & sign(Time.mean + Time.CI) == sign(Time.mean - Time.CI)) { #Add on-tailed test option here
pow.park[pp,ss] <- pow.park[pp,ss] + 1}
if (two.tailed == FALSE & (Time.mean + Time.CI < 0 | Time.mean - Time.CI > 0)) { #Add on-tailed test option here
pow.park[pp,ss] <- pow.park[pp,ss] + 1}
} else {fail.park[pp,ss] <- fail.park[pp,ss] + 1}}
}
}
}
return(list(powcnt, fail, pow.park, fail.park))
}
#' Fit occupancy model with three detection methods
#'
#' This function fits an occupancy model to simulated detection histories using the package unmarked for species that are detected using 3 detection methods
#' A trend in occupancy is estimated and confidence intervals are calculated depending on the Type I error rate. A one-tailed or two-tailed significance test is then conducted on the trend parameter
#' A one-tailed test looks to see if the upper or lower confidence interval is greater than or less than zero. A two-tailed test assesses whether both the upper and lower confidence
#' intervals have the same sign (i.e. are both positive or negative). If park.power = TRUE, model fitting is repeated on sites from each regional level management unit.
#' @param method1 The first detection method relevant to species ss
#' @param method2 The second detection method relevant to species ss
#' @param method3 The third detection method relevant to species ss
#' @param repeats1 The number of repeat visits for the first detection method
#' @param repeats2 The number of repeat visits for the second detection method
#' @param repeats3 The number of repeat visits for the third detection method
#' @param s.years A vector specifying the years that monitoring occurs. Note, monitoring must be done in the final year (i.e. Tmax)
#' @param n.sites The number of sites monitored
#' @param xy.sites The XY coordinates of monitored sites
#' @param park.ID A vector specifying that location of each site with sub-level parks
#' @param park.level Set to TRUE is power is estimated within regional level management unit, FALSE otherwise
#' @param powcnt A vector that keeps track of how many times a significant trend in occupancy is detected across the landscape
#' @param fail A vector that keeps track of how many times the occupancy model could not be fitted to simulated detection histories at a landscape level in unmarked
#' @param pow.park A vector that keeps track of how many times a significant trend in occupancy is detected within each park
#' @param fail.park A vector that keeps track of how many times the occupancy model could not be fitted to simulated detection histories at a park level in unmarked
#' @param value The critical value used to calculate confidence intervals around the trend parameter, depending on the Type I error rate and a one-tailed or two-tailed test
#' @param ss An index to loop through each species
#' @param two.tailed Set to TRUE if conducting a two-tailed test, FALSE otherwise
#' @keywords
#' @export
#' @examples
#' fit.occ.3method()
#Function to fit occupancy model when 3 methods are used to detect species s
fit.occ.3method <- function(method1, method2, method3, repeats1, repeats2, repeats3, s.years, n.sites, xy.sites, park.ID, park.level, powcnt, fail, pow.park, fail.park, value, ss, two.tailed, n.park) {
if (repeats1 == 1) {
y1 <- aperm(method1[,ss,,s.years],c(1,2))
dim(y1)<- c(n.sites*length(s.years), repeats1)
} else {
y1 <- aperm(method1[,ss,,s.years],c(1,3,2))
dim(y1)<- c(n.sites*length(s.years), repeats1)
}
if (repeats2 == 1) {
y2 <- aperm(method2[,ss,,s.years],c(1,2))
dim(y2)<- c(n.sites*length(s.years), repeats2)
} else {
y2 <- aperm(method2[,ss,,s.years],c(1,3,2))
dim(y2)<- c(n.sites*length(s.years), repeats2)
}
if (repeats3 == 1) {
y3 <- aperm(method3[,ss,,s.years],c(1,2))
dim(y3)<- c(n.sites*length(s.years), repeats3)
} else {
y3 <- aperm(method3[,ss,,s.years],c(1,3,2))
dim(y3)<- c(n.sites*length(s.years), repeats3)
}
siteCovs <- data.frame(matrix(rep(s.years,each=nrow(xy.sites)),nrow(xy.sites)*length(s.years),1))
park.ID.year <- rep(xy.sites[,3], length(s.years))
park.ID.year[park.ID.year==2] <- 0
siteCovs <- cbind(siteCovs, park.ID.year)
colnames(siteCovs) <- c("Time", "Burnt")
siteCovs$Burnt <- factor(siteCovs$Burnt, levels=c(0,1))
m1.code <- matrix(factor(1),nrow=nrow(xy.sites)*length(s.years), ncol=repeats1)
m2.code <- matrix(factor(2),nrow=nrow(xy.sites)*length(s.years), ncol=repeats2)
m3.code <- matrix(factor(3),nrow=nrow(xy.sites)*length(s.years), ncol=repeats3)
obsCovs <- data.frame(as.matrix(cbind(m1.code, m2.code, m3.code)))
colnames(obsCovs) <- c(rep("M1",repeats1), rep("M2",repeats2), rep("M3",repeats3))
umf <- unmarkedFrameOccu(y = cbind(y1, y2, y3), siteCovs = siteCovs, obsCovs = list(METHOD = obsCovs))
#inits<- rbind(c(0,0,0,0,0),c(-1,-1,-1,-1,-1),c(1,1,1,1,1))
inits<- rbind(c(0,0,0,0,0,0,0),c(-1,-1,-1,-1,-1,-1,-1),c(1,1,1,1,1,1,1))
for (vv in 1:nrow(inits)) {
mod<- try(occu(~METHOD ~Time*Burnt, umf, control=list(maxit=1000000), starts=inits[vv,]), silent=TRUE)
if (!is(mod,"try-error")){break}
}
if (is(mod,"try-error")) {fail[ss] <- fail[ss] + 1} else {
if (!is.na(SE(mod['state'])[4])) {
#Time.mean <- coef(mod)[4]
Time.mean <- coef(mod)[4]
Time.CI <- SE(mod)[4] * value
if (two.tailed == TRUE & sign(Time.mean + Time.CI) == sign(Time.mean - Time.CI)) { #Add on-tailed test option here
powcnt[ss] <- powcnt[ss] + 1}
if (two.tailed == FALSE & (Time.mean + Time.CI < 0 | Time.mean - Time.CI > 0)) { #Add on-tailed test option here
powcnt[ss] <- powcnt[ss] + 1}
} else {fail[ss] <- fail[ss] + 1}}
if (park.level == TRUE) {
for (pp in n.park) {
park.site <- which(xy.sites[,3] == pp)
if (length(park.site) == 0) {pow.park[pp,ss] <- pow.park[pp,ss]}
if (length(park.site) > 0) {
y.park <- umf[which(park.ID.year == pp),]
inits<- rbind(c(0,0,0,0,0),c(-1,-1,-1,-1,-1),c(1,1,1,1,1))
for (vv in 1:nrow(inits)) {
mod<- try(occu(~METHOD ~Time, y.park, control=list(maxit=10000), starts=inits[vv,]), silent=TRUE)
if (!is(mod,"try-error")){break}
}
if (is(mod,"try-error")) {fail.park[pp,ss] <- fail.park[pp,ss] + 1} else {
if (!is.na(SE(mod['state'])[1])) {
Time.mean <- coef(mod)[2]
Time.CI <- SE(mod)[2] * value
if (two.tailed == TRUE & sign(Time.mean + Time.CI) == sign(Time.mean - Time.CI)) { #Add on-tailed test option here
pow.park[pp,ss] <- pow.park[pp,ss] + 1}
if (two.tailed == FALSE & (Time.mean + Time.CI < 0 | Time.mean - Time.CI > 0)) { #Add on-tailed test option here
pow.park[pp,ss] <- pow.park[pp,ss] + 1}
} else {fail.park[pp,ss] <- fail.park[pp,ss] + 1}}
}
}
}
return(list(powcnt, fail, pow.park, fail.park))
}
#Function to fit occupancy model when 4 methods are used to detect species s
fit.occ.4method <- function(method1, method2, method3, method4, repeats1, repeats2, repeats3, repeats4, s.years, n.sites, xy.sites, park.ID, park.level, powcnt, fail, pow.park, fail.park, value, ss, two.tailed, n.park) {
if (repeats1 == 1) {
y1 <- aperm(method1[,ss,,s.years],c(1,2))
dim(y1)<- c(n.sites*length(s.years), repeats1)
} else {
y1 <- aperm(method1[,ss,,s.years],c(1,3,2))
dim(y1)<- c(n.sites*length(s.years), repeats1)
}
if (repeats2 == 1) {
y2 <- aperm(method2[,ss,,s.years],c(1,2))
dim(y2)<- c(n.sites*length(s.years), repeats2)
} else {
y2 <- aperm(method2[,ss,,s.years],c(1,3,2))
dim(y2)<- c(n.sites*length(s.years), repeats2)
}
if (repeats3 == 1) {
y3 <- aperm(method3[,ss,,s.years],c(1,2))
dim(y3)<- c(n.sites*length(s.years), repeats3)
} else {
y3 <- aperm(method3[,ss,,s.years],c(1,3,2))
dim(y3)<- c(n.sites*length(s.years), repeats3)
}
if (repeats4 == 1) {
y4 <- aperm(method4[,ss,,s.years],c(1,2))
dim(y4)<- c(n.sites*length(s.years), repeats4)
} else {
y4 <- aperm(method4[,ss,,s.years],c(1,3,2))
dim(y4)<- c(n.sites*length(s.years), repeats4)
}
siteCovs <- data.frame(matrix(rep(s.years,each=nrow(xy.sites)),nrow(xy.sites)*length(s.years),1))
park.ID.year <- rep(xy.sites[,3], length(s.years))
park.ID.year[park.ID.year==2] <- 0
siteCovs <- cbind(siteCovs, park.ID.year)
colnames(siteCovs) <- c("Time", "Burnt")
siteCovs$Burnt <- factor(siteCovs$Burnt, levels=c(0,1))
m1.code <- matrix(factor(1),nrow=nrow(xy.sites)*length(s.years), ncol=repeats1)
m2.code <- matrix(factor(2),nrow=nrow(xy.sites)*length(s.years), ncol=repeats2)
m3.code <- matrix(factor(3),nrow=nrow(xy.sites)*length(s.years), ncol=repeats3)
m4.code <- matrix(factor(4),nrow=nrow(xy.sites)*length(s.years), ncol=repeats4)
obsCovs <- data.frame(as.matrix(cbind(m1.code, m2.code, m3.code, m4.code)))
colnames(obsCovs) <- c(rep("M1",repeats1), rep("M2",repeats2), rep("M3",repeats3), rep("M4",repeats4))
umf <- unmarkedFrameOccu(y = cbind(y1, y2, y3, y4), siteCovs = siteCovs, obsCovs = list(METHOD = obsCovs))
#inits<- rbind(c(0,0,0,0,0,0),c(-1,-1,-1,-1,-1,-1),c(1,1,1,1,1,1))
inits<- rbind(c(0,0,0,0,0,0,0,0),c(-1,-1,-1,-1,-1,-1,-1,-1),c(1,1,1,1,1,1,1,1))
for (vv in 1:nrow(inits)) {
mod<- try(occu(~METHOD ~Time*Burnt, umf, control=list(maxit=1000000), starts=inits[vv,]), silent=TRUE)
if (!is(mod,"try-error")){break}
}
if (is(mod,"try-error")) {fail[ss] <- fail[ss] + 1} else {
if (!is.na(SE(mod['state'])[4])) {
Time.mean <- coef(mod)[4]
Time.CI <- SE(mod)[4] * value
if (two.tailed == TRUE & sign(Time.mean + Time.CI) == sign(Time.mean - Time.CI)) { #Add on-tailed test option here
powcnt[ss] <- powcnt[ss] + 1}
if (two.tailed == FALSE & (Time.mean + Time.CI < 0 | Time.mean - Time.CI > 0)) { #Add on-tailed test option here
powcnt[ss] <- powcnt[ss] + 1}
} else {fail[ss] <- fail[ss] + 1}}
if (park.level == TRUE) {
for (pp in n.park) {
park.site <- which(xy.sites[,3] == pp)
if (length(park.site) == 0) {pow.park[pp,ss] <- pow.park[pp,ss]}
if (length(park.site) > 0) {
y.park <- umf[which(park.ID.year == pp),]
inits<- rbind(c(0,0,0,0,0,0),c(-1,-1,-1,-1,-1,-1),c(1,1,1,1,1,1))
for (vv in 1:nrow(inits)) {
mod<- try(occu(~METHOD ~Time, y.park, control=list(maxit=10000), starts=inits[vv,]), silent=TRUE)
if (!is(mod,"try-error")){break}
}
if (is(mod,"try-error")) {fail.park[pp,ss] <- fail.park[pp,ss] + 1} else {
if (!is.na(SE(mod['state'])[1])) {
Time.mean <- coef(mod)[2]
Time.CI <- SE(mod)[2] * value
if (two.tailed == TRUE & sign(Time.mean + Time.CI) == sign(Time.mean - Time.CI)) { #Add on-tailed test option here
pow.park[pp,ss] <- pow.park[pp,ss] + 1}
if (two.tailed == FALSE & (Time.mean + Time.CI < 0 | Time.mean - Time.CI > 0)) { #Add on-tailed test option here
pow.park[pp,ss] <- pow.park[pp,ss] + 1}
} else {fail.park[pp,ss] <- fail.park[pp,ss] + 1}}
}
}
}
return(list(powcnt, fail, pow.park, fail.park))
}
#' Plot results of power analysis
#'
#' This function plots results of the power analysis. It first unpacks the list generated by the foreach function and estimates power given the number of simulations
#' and the number of cores used. Power is plotted for each species on a single figure. Users can then scroll through separate plots for power at a park level if it park.power = TRUE
#' @param pwr An array containing the results of the power analysis
#' @param n.species The number of species
#' @param nsims The number of simulations
#' @param effect.size The proportional decline in occupancy
#' @param n.park The number of parks in which to restimate power
#' @param species.list A vector specifying the name of each species analysed
#' @param save.wd A directory to save results and figures
#' @keywords cats
#' @export
#' @examples
#' plot.results()
plot.results <- function(pwr, n.species, nsims, effect.size, n.park, species.list, n.cores) {
Results <- array(dim=c(length(n.park)+1,n.species,length(effect.size)))
new.effect <- matrix(NA, length(effect.size), n.species)
pwr_all <- pwr
for (i in 1:length(effect.size)) {
pwr1 <- pwr_all[,i]
dim(pwr1) <- c(length(pwr1)/n.species, n.species)
results <- matrix(NA,length(n.park)+1,n.species)
results[1,] <- pwr1[1,]/((nsims*n.cores)-pwr1[2,])
results[2:(length(n.park)+1),] <- pwr1[3:(length(n.park)+2),]/((nsims*n.cores)-pwr1[(length(n.park)+3):(length(n.park)*2+2),])
new.effect[i,] <- pwr1[nrow(pwr1),]/n.cores
Results[,,i] <- results
}
mean.total.cost <- mean(new.effect)
if (park.level==TRUE) { #Change back to TRUE
for (v in 1:(length(n.park)+1)) {
cl <- rainbow(n.species)
par(mfcol=c(1,1), mar=c(0.1,0.1,0.1,0.1), oma=c(4,4,4,4), mai=c(0.1,0.1,0.1,2),xpd=NA)
new.effect[,1] <- c(0.1,0.3,0.5,0.7,0.9)
plot(Results[v,1,]~new.effect[,1], type="l",ylim=c(0,1), xlim=c(0,1), lwd=1, main="", col="grey", ylab="Statistical power", xlab="Effect size")
for (i in 1:n.species) {
new.effect[,i] <- c(0.1,0.3,0.5,0.7,0.9)
lines(Results[v,i,]~new.effect[,i], type="l",ylim=c(0,1), xlim=c(0,1), lwd=2, col=cl[i], lty=1)
}
legend("topright", c(as.character(species.list[,1])), inset=c(-0.3,0), lwd=c(2,2,2,2,2,2), cex=0.5, col=cl[1:n.species])
if (v==1) {mtext("Power: landscape level", side = 3, outer=TRUE, adj=0.5, line = 1, cex=1.1)}
else {mtext(paste("Power: Park ", v-1), side = 3, outer=TRUE, adj=0.5, line = 1, cex=1.1)}
locator(1)
}
} else {
cl <- rainbow(n.species)
par(mfcol=c(1,1), mar=c(0.1,0.1,0.1,0.1), oma=c(4,4,4,4), mai=c(0.1,0.1,0.1,2),xpd=NA)
new.effect[,1] <- effect.size
plot(Results[1,1,]~effect.size, type="l",ylim=c(0,1), xlim=c(0,1), lwd=1, main="", col="grey", ylab="Statistical power", xlab="Effect size")
for (i in 1:n.species) {
new.effect[,i] <- effect.size
lines(Results[1,i,]~effect.size, type="l",ylim=c(0,1), xlim=c(0,1), lwd=2, col=cl[i], lty=1)
}
coord<- par("usr")
legend(x= coord[2]*1.05, y = coord[4], c(as.character(species.list[,1])), lwd=c(2,2,2,2,2,2), cex=0.5, col=cl[1:n.species])
}
cat('\n',"##########################################################")
cat('\n',"OUTPUT SUMMARY.....")
cat('\n',"##########################################################")
cat('\n',"Number of species = ", n.species)
cat('\n',"Number of parks = ", max(n.park))
cat('\n',"Number of sites = ", n.sites)
cat('\n',"Fire modelled at sites = ", model.fire)
cat('\n',"Analysis based on prespecified sites = ", existing.sites)
cat('\n',"All prespecified sites surveyed = ", all.existing.sites)
cat('\n',"Number of sites surveyed = ", n.sites)
cat('\n',"Ratio of remote to non-remote sites = ", R)
cat('\n',"Time horizon = ", Tmax, " years")
cat('\n',"Survey years = ", s.years)
cat('\n',"Number of repeat visits (method 1) = ", n.method[1])
cat('\n',"Number of repeat visits (method 2) = ", n.method[2])
cat('\n',"Number of repeat visits (method 3) = ", n.method[3])
cat('\n',"Number of repeat visits (method 4) = ", n.method[4])
cat('\n',"Effect size(s) = ", effect.size)
cat('\n',"Two tailed test = ", two.tailed)
cat('\n',"Type I error rate = ", alpha)
cat('\n',"Number of simulations = ", nsims*n.cores)
return(list(Results, mean.total.cost))
}
###############################################################################################################################
#FUNCTIONS NOT USED FOR NOW
#' Model fire function
#'
#' This function models the incidence of fire at monitoring sites based on a hazard function that depends on time since fire in each cell.
#' At present, separate hazard functions are defined for three different vegetation classes. It returns a vector specifying whether each site burns (1) or not (0) in a given year jj
#' @param time.hist An array specifying the time since fire at each monitoring site prior to simulations
#' @param time.fire An array specifying the time since fire at each monitoring site during simulations
#' @param veg.ID Specifies the different layers with different hazard functions
#' @param jj The year of simulation. Can be a value between 1 and Tmax
#' @keywords
#' @export
#' @examples
#' fire.point.model()
#Model the incidence of fire at selected sites according using a hazard function
fire.point.model <- function(time.hist, time.fire, veg.ID, jj){
burn <- veg.ID
OW <- which(veg.ID==2) #Record which cells are open woodland
CF <- which(veg.ID==3) #Record which cells are open forest
SW <- which(veg.ID==1) #Record which cells are sandstone and woodland
if (jj==1) {
burn[OW] <- 1-((exp(-(time.hist[OW]/2.24)^1.22))/(exp(-((time.hist[OW]-1)/2.24)^1.22))) #Discrete Weibull hazard function for open woodland
burn[CF] <- 1-((exp(-(time.hist[CF]/4.34)^0.96))/(exp(-((time.hist[CF]-1)/4.34)^0.96))) #Discrete Weibull hazard function for closed forest
burn[SW] <- 1-((exp(-(time.hist[SW]/3.56)^1.26))/(exp(-((time.hist[SW]-1)/3.56)^1.26))) #Discrete Weibull hazard function for sandstone and woodland
} else {
burn[OW] <- 1-((exp(-(time.fire[OW,jj-1]/2.24)^1.22))/(exp(-((time.fire[OW,jj-1]-1)/2.24)^1.22))) #Discrete Weibull hazard function for open woodland
burn[CF] <- 1-((exp(-(time.fire[CF,jj-1]/4.34)^0.96))/(exp(-((time.fire[CF,jj-1]-1)/4.34)^0.96))) #Discrete Weibull hazard function for closed forest
burn[SW] <- 1-((exp(-(time.fire[SW,jj-1]/3.56)^1.26))/(exp(-((time.fire[SW,jj-1]-1)/3.56)^1.26))) #Discrete Weibull hazard function for sandstone and woodland
}
burn <- ifelse(runif(n.sites)<burn,1,0)
return(burn)
}
#Model the incidence of fire at selected sites using a hazard function
fire.point.model2 <- function(time.hist, jj){
PP <- c(0.48,0.53,0.42,0.40,0.39,0.26,0.32,0.25,0.28,0.30,0.26,0.21,0.22,0.26,0.05)
#PP[] <- 1
burn <- PP[time.hist]
burn <- ifelse(runif(n.sites)<burn,1,0)
return(burn)
}
#' Refit occupancy raster layers function
#'
#' This function is called only if fire is modelled at sites. It re-fits occupancy raster layers for fire sensitive species given simulated time since fire and number of fire layers
#' It returns a new raster stack with the updated occupancy raster layers for each species
#' @param occ.new A raster stack of occupancy maps. Raster layers for fire sensitive species are updated depending on the simulated fire history at time jj
#' @param layers An array of covararite values at each site. These are used to update the occ.new raster stack
#' @param time.fire A vector specifying the time since fire at each site in year jj given the simulated fire history
#' @param fire.freq A vector specifying the number of fires at sites during a 15 year moving window
#' @param jj The year of the monitoring program
#' @keywords
#' @export
#' @examples
#' refit.occ()
#Function to refit the occupancy models for fire sensitive species should the user choose to model fire at sites
refit.occ <- function(occ.new, layers, time.fire, fire.freq, jj, veg.ID) {
for (i in 1:n.species) {
covr <- as.numeric(species.cov[i,-1])
if (covr[14] | covr[16] !=0) { #Only remap occupancy if fire influences occupancy
freq.scale <- array(scale(fire.freq[,jj])[,1])
time.scale <- array(scale(time.fire[,jj])[,1])
#occ.new[,i,jj] <- rep(covr[1],n.sites) + covr[3]*layers[,1] + covr[4]*layers[,1]^2 + covr[5]*layers[,2] +
#covr[7]*freq.scale + covr[8]*freq.scale^2 + covr[9]*layers[,7] + covr[10]*layers[,7]^2 +
#covr[11]*layers[,3] + covr[12]*layers[,3]^2 + covr[14]*layers[,6] + covr[15]*time.scale + covr[15]*time.scale^2
occ.new[,i,jj] <- rep(covr[1],n.sites) +
covr[2]*layers[,8] + #Clay
covr[3]*layers[,8]^2 +
covr[4]*layers[,11] + #Veg
covr[5]*layers[,11]^2 +
covr[6]*layers[,1] + #DEM
covr[7]*layers[,1]^2 +
covr[8]*layers[,2] + #Creek
covr[9]*layers[,9] + #Ruggedness
covr[10]*layers[,5] + #Temp
covr[11]*layers[,5]^2 +
covr[12]*layers[,10] + #Rain
covr[13]*layers[,10]^2 +
covr[14]*freq.scale + #Fire freq
covr[15]*freq.scale^2 +
covr[16]*time.scale + #Time since fire
covr[17]*time.scale^2
#covr[18]*layers[,1] + #Extent
#covr[19]*layers[,1] #Patch
occ.new[,i,jj] <- exp(occ.new[,i,jj])/(1+exp(occ.new[,i,jj]))
if (i == 5 & nrow(species.list == 20)) {occ.new[veg.ID==0,i,jj] <- 0}
}
}
return(occ.new)
}
#' Refit detectability raster layers function
#'
#' This function is called only if fire is modelled at sites. It re-fits the detectability raster layers for fire sensitive species given simulated time since fire and number of fire layers
#' A new raster stack is returned for each detection method
#' @param det.method1.new A raster stack of detectability under method 1. Raster layers for fire sensitive species are updated depending on the simulated fire history at time jj
#' @param det.method2.new A raster stack of detectability under method 2. Raster layers for fire sensitive species are updated depending on the simulated fire history at time jj
#' @param det.method3.new A raster stack of detectability under method 3. Raster layers for fire sensitive species are updated depending on the simulated fire history at time jj
#' @param layers An array of covararites at each site. These are used to update the detectability raster stacks
#' @param time.fire A vector specifying the time since fire at each site in year jj given the simulated fire history
#' @param fire.freq A vector specifying the number of fires at sites during a 15 year moving window
#' @param jj The year of the monitoring program
#' @keywords
#' @export
#' @examples
#' refit.det()
#Function to refit the detection models should the user choose to model fire in the landscape
refit.det <- function(det.method1.new, det.method2.new, det.method3.new, det.method4.new, layers, time.fire, fire.freq, jj) {
det.method <- rep(1,n.sites)
freq.scale <- array(scale(fire.freq)[,jj])
time.scale <- array(scale(time.fire)[,jj])
obj <- list(det.method1.new, det.method2.new, det.method3.new, det.method4.new)
for (i in 1:n.species) {
covr <- as.numeric(species.cov[i,-1])
det.covr <- covr[20:27]
#Species detected using 1 method
if ((sum(species.list[i,-1]) == 1) & (covr[22] | covr[23] != 0)){
pos <- which(species.list[i,-1]==1)
logit <- det.covr[1] + det.covr[2]*layers[,8] + det.covr[3]*freq.scale + det.covr[4]*time.scale
obj[[pos]][,i,jj] <- exp(logit)/(1+exp(logit))
}
#Species detected using 2 methods
if ((sum(species.list[i,-1]) == 2) & (covr[22] | covr[23] != 0)){
pos <- which(species.list[i,-1]==1)
det.method[] <- 0 #Method 1
logit <- det.covr[1] + det.covr[3]*freq.scale + det.covr[pos[2]+3]*det.method + det.covr[2]*layers[,8] + det.covr[4]*time.scale
obj[[pos[1]]][,i,jj] <- exp(logit)/(1+exp(logit))
det.method[] <- 1 #Method 2
logit <- covr[2] + covr[17]*freq.scale + det.covr[pos[2]+3]*det.method + covr[22]*layers[,6] + covr[23]*time.scale
obj[[pos[2]]][,i,jj] <- exp(logit)/(1+exp(logit))
}
#Species detected using 3 methods
if ((sum(species.list[i,-1]) == 3) & (covr[22] | covr[23] != 0)){
pos <- which(species.list[i,-1]==1)
det.method[] <- 0 #Method 1
logit <- det.covr[1] + det.covr[3]*freq.scale + det.covr[pos[2]+3]*det.method + det.covr[2]*layers[,8] + det.covr[4]*time.scale
obj[[pos[1]]][,i,jj] <- exp(logit)/(1+exp(logit))
det.method[] <- 1 #Method 2
logit <- det.covr[1] + det.covr[3]*freq.scale + det.covr[pos[2]+3]*det.method + det.covr[2]*layers[,8] + det.covr[4]*time.scale
obj[[pos[2]]][,i,jj] <- exp(logit)/(1+exp(logit))
det.method[] <- 1 #Method 3
logit <- det.covr[1] + det.covr[3]*freq.scale + det.covr[pos[3]+3]*det.method + det.covr[2]*layers[,8] + det.covr[4]*time.scale
obj[[pos[3]]][,i,jj] <- exp(logit)/(1+exp(logit))
}
#Species detected using 4 methods
if ((sum(species.list[i,-1]) == 4) & (covr[22] | covr[23] != 0)){
pos <- which(species.list[i,-1]==1)
det.method[] <- 0 #Method 1
logit <- det.covr[1] + det.covr[3]*freq.scale + det.covr[pos[2]+3]*det.method + det.covr[2]*layers[,8] + det.covr[4]*time.scale
obj[[pos[1]]][,i,jj] <- exp(logit)/(1+exp(logit))
det.method[] <- 1 #Method 2
logit <- det.covr[1] + det.covr[3]*freq.scale + det.covr[pos[2]+3]*det.method + det.covr[2]*layers[,8] + det.covr[4]*time.scale
obj[[pos[2]]][,i,jj] <- exp(logit)/(1+exp(logit))
det.method[] <- 1 #Method 3
logit <- det.covr[1] + det.covr[3]*freq.scale + det.covr[pos[3]+3]*det.method + det.covr[2]*layers[,8] + det.covr[4]*time.scale
obj[[pos[3]]][,i,jj] <- exp(logit)/(1+exp(logit))
det.method[] <- 1 #Method 3
logit <- det.covr[1] + det.covr[3]*freq.scale + det.covr[pos[4]+3]*det.method + det.covr[2]*layers[,8] + det.covr[4]*time.scale
obj[[pos[4]]][,i,jj] <- exp(logit)/(1+exp(logit))
}
#if (sp.lst$Method1 == 1 & sp.lst$Method2 == 0 & sp.lst$Method3 == 1 & covr[17] | covr[23] != 0){ #Species detected using method 1 and method 3
#det.method[] <- 1 #Method 1 first
#det.method1.new[,i,jj] <- covr[2] + covr[17]*freq.scale + covr[18]*det.method + covr[22]*layers[,6] + covr[23]*time.scale
#det.method1.new[,i,jj] <- exp(det.method1.new[,i,jj])/(1+exp(det.method1.new[,i,jj]))
#det.method[] <- 0 #Method 3 second
# det.method3.new[,i,jj] <- covr[2] + covr[17]*freq.scale + covr[18]*det.method + covr[22]*layers[,6] + covr[23]*time.scale
#det.method3.new[,i,jj] <- exp(det.method3.new[,i,jj])/(1+exp(det.method3.new[,i,jj]))
# }
# if (sp.lst$Method1 == 0 & sp.lst$Method2 == 1 & sp.lst$Method3 == 1 & covr[17] | covr[23] != 0){ #Species detected using method 2 and method 3
#det.method[] <- 1 #Method 2
# det.method2.new[,i,jj] <- covr[2] + covr[17]*freq.scale + covr[18]*det.method + covr[22]*layers[,6] + covr[23]*time.scale
# det.method2.new[,i,jj] <- exp(det.method2.new[,i,jj])/(1+exp(det.method2.new[,i,jj]))
# det.method[] <- 0 #Method 3
# det.method3.new[,i,jj] <- covr[2] + covr[17]*freq.scale + covr[18]*det.method + covr[22]*layers[,6] + covr[23]*time.scale
# det.method3.new[,i,jj] <- exp(det.method3.new[,i,jj])/(1+exp(det.method3.new[,i,jj]))
# }
# if (sp.lst$Method1 == 1 & sp.lst$Method2 == 1 & sp.lst$Method3 == 1 & covr[17] | covr[23] != 0){ #Species detected using methods 1 and 2 and 3
# det.method[] <- 1 #Method 1
# det.method1.new[,i,jj] <- covr[2] + covr[17]*freq.scale + covr[20]*det.method + covr[22]*layers[,6] + covr[23]*time.scale
# det.method1.new[,i,jj] <- exp(det.method1.new[,i,jj])/(1+exp(det.method1.new[,i,jj]))
# det.method[] <- 1 #Method 2
# det.method2.new[,i,jj] <- covr[2] + covr[17]*freq.scale + covr[19]*det.method + covr[22]*layers[,6] + covr[23]*time.scale
# det.method2.new[,i,jj] <- exp(det.method2.new[,i,jj])/(1+exp(det.method2.new[,i,jj]))
# det.method[] <- 0 #Repeat 3
# det.method3.new[,i,jj] <- covr[2] + covr[17]*freq.scale + covr[19]*det.method + covr[22]*layers[,6] + covr[23]*time.scale
# det.method3.new[,i,jj] <- exp(det.method3.new[,i,jj])/(1+exp(det.method3.new[,i,jj]))
#}
}
return(obj)
}
#Species detected using 1 method
#if (sp.lst$Method1 == 1 & sp.lst$Method2 == 0 & sp.lst$Method3 == 0 & covr[17] | covr[23] != 0){
#det.method1.new[,i,jj] <- covr[2] + covr[17]*freq.scale + covr[22]*layers[,6] + covr[23]*time.scale
#det.method1.new[,i,jj] <- exp(det.method1.new[,i,jj])/(1+exp(det.method1.new[,i,jj]))
# }
#Species detected using method 2 only
# if (sp.lst$Method1 == 0 & sp.lst$Method2 == 1 & sp.lst$Method3 == 0 & covr[17] | covr[23] != 0){
#det.method2.new[,i,jj] <- covr[2] + covr[17]*freq.scale + covr[22]*layers[,6] + covr[23]*time.scale
#det.method2.new[,i,jj] <- exp(det.method2.new[,i,jj])/(1+exp(det.method2.new[,i,jj]))
# }
#Species detected using method 3 only
# if (sp.lst$Method1 == 0 & sp.lst$Method2 == 0 & sp.lst$Method3 == 1 & covr[17] | covr[23] != 0){
#det.method3.new[,i,jj] <- covr[2] + covr[17]*freq.scale + covr[22]*layers[,6] + covr[23]*time.scale
#det.method3.new[,i,jj] <- exp(det.method3.new[,i,jj])/(1+exp(det.method3.new[,i,jj]))
# }
<file_sep>
###############################################################
### SPATIALLY EXPLICIT SIMULATION IN DYNAMIC LANDSCAPES ###
###############################################################
#
# Scripts required for full analysis: 'job_submission.slurm';
# 'batch_submission.slurm';
# '2_VICFireFunctions_SPARTAN.R'
#
# Data inputs required to run analysis: 'occ_speciesGroup.tif';
# 'det.method1_speciesGroup.tif';
# 'det.method2_speciesGroup.tif';
# 'det.method3_speciesGroup.tif';
# 'det.method4_speciesGroup.tif';
# 'species.det.csv';
# 'species.covar.csv';
# 'Z_speciesGroup_5k.CAZ_DEA.rank.compressed.tif';
# 'burnt.tif';
# 'remote.tif';
# 'vic.road.tif';
# 'exisitingSitesSPDF.shp';
# 'repeatVisits.csv.tif';
# 'method.cost.array.csv.tif';
###########################################################################################
### STEP 1: Define command line arguments and indices. Set up the parameter ###
### space for running jobs on Spartan ###
###########################################################################################
# Clear workspace
rm(list=ls())
# Create command line for interacting with job_submission.slurm script.
command_args<- commandArgs(trailingOnly = TRUE)
parameter_index<- as.numeric(command_args[1])
## Possible ID options for each parameter.
max.budget_options = c(5000000, 9000000, 20000000)
all.existing.sites_options = c(TRUE)
group_options = c("Frogs", "Birds", "Mammals", "Reptiles")
repeat.scenario_options = c(1, 2)
method.scenario_options = c(1, 2)
survey.year_options = c(1, 2)
site.ratio_options = c(0.5, 0.8)
# Define grid of all possible parameter combinations. MAKE SURE that the length of the testGrid corresponse to the sequence length in 'batch_submission.slurm' before proceeding.
testGrid<-expand.grid(max.budget_options,
group_options,
repeat.scenario_options,
method.scenario_options,
survey.year_options,
site.ratio_options,
all.existing.sites_options)
# Create indices for interacting with job_submission.slurm script.
max.budget<-testGrid[parameter_index, 1]
group<- testGrid[parameter_index, 2]
repeat.scenario<- testGrid[parameter_index, 3]
method.scenario<- testGrid[parameter_index, 4]
survey.year<- testGrid[parameter_index, 5]
site.ratio<- testGrid[parameter_index, 6]
all.existing.sites<- testGrid[parameter_index, 7]
colnames(testGrid)<- c("max.budget_options", "group_options", "repeat.scenario_options", "method.scenario_options", "survey.year_options", "site.ratio_options", "all.existing.sites_options")
# Check for package dependices and install/load in packages as required. -> Remove when in package <-
.libPaths("/home/asmart1/R/lib/3.6")
lib = .libPaths()[1]
repo<- "https://cran.ms.unimelb.edu.au/" # Set mirror to download packages.
pkgs = c("unmarked", "raster", "rgdal", "doParallel", "foreach", "abind", "sf", "stringr", "dplyr", "parallel", "future", "doFuture") # Define packages.
new.pkgs <- pkgs[!(pkgs %in% installed.packages(lib=lib)[,"Package"])]
if(length(new.pkgs)) install.packages(new.pkgs, lib=lib, repos=repo)
inst = lapply(pkgs, library, character.only = TRUE)
# Load in functions for the analysis.
source("src/functions.R")
###########################################################################################
### STEP 2: Load in occupancy and detectability layer for each species group ###
###########################################################################################
# Simulations require raster layers of occupancy and detectability for each species. These raster layers need to be built beforehand and
# should be loaded into R raster stacks. Each species can be detected with up to 3 detection methods. Any combination of 3 methods is allowed.
# For example, species 1 might be detected with 2 methods. These two methods could be method 1 and 2, method 1 and 3 or method 2 and 3.
# Importantly, if you're evaulating power for only one or two methods, you still must create a raster stack for the third unused method.
# All raster stacks must have the same dimensions and cell resolution. The package will check all raster layers and provide warning if there is a mismatch.
# Cells not considered for monitoriong should be assigned an NA value
group = group
occ<- stack(sprintf("spotR/layers/occ_%s.tif", group)) # Stack species within a group. If loading in raw HDMs make sure to divide by 100 (want a value range of 0 - 1).
occ<-occ/100
det.method1<- stack(paste(sprintf("spotR/layers/det.method1_%s.tif", group))) # Load in species detectability layers for method 1 combined into a raster stack. Note, if you only assess one species this should still be a stack.
det.method2<- stack(paste(sprintf("spotR/layers/det.method2_%s.tif", group)))
det.method3<- stack(paste(sprintf("spotR/layers/det.method3_%s.tif", group)))
det.method4<- stack(paste(sprintf("spotR/layers/det.method4_%s.tif", group)))
#########################################################################################
### STEP 3: Load files specifying which methods apply to each species and a ###
### statistical model relating occupancy and detectability to covariates ###
#########################################################################################
# Simulations require a list that specifies which detection methods are relevant to each species.
# A '1' in the species.list means that detection method is relevant to a species, a '0' means that it is not relevant.
# If you type 'species.list', you will see what is required. The number of rows depends on the number of species in your raster stacks.
# The occupancy and detectability raster stacks loaded above can remain static over time or be updated in response to fire events at monitoring sites.
# The species.cov file specifies the statistical model between occupancy/detectability and environmental covariates.
# Note, if you only want to model a static landscape (i.e. no fire), you still need to provide a species.cov file - just fill it with zero's.
if (method.scenario == 1) {species.detection<- read.csv("spotR/inputs/species.det.csv", stringsAsFactors = FALSE)} else{ # Load in species detecion methods.
species.detection<- read.csv("spotR/inputs/species.det_2.csv", stringsAsFactors = FALSE)}
species.detection.all<- species.detection
species.detection<- subset(species.detection, species.detection[,1]==group) # Subset by target group.
species.detection<-species.detection[,-1] # Remote group col.
species.list<- species.detection
species.list[,2:5]<- data.frame(lapply(species.list[2:5], function(x) as.integer(x!=""))) # Binary method used or not.
# Load in covariates of detection.
species.cov<- read.csv("spotR/inputs/species.covar.csv", header=TRUE,stringsAsFactors=FALSE) #Load in statistical models for each species. This wont be needed for the fire modelling.
names<- colnames(species.cov)
covariats<- as.data.frame(matrix(0, nrow=length(species.detection[,2]), ncol=length(names)-1))
species.cov<- cbind(species.detection[,2], covariats)
colnames(species.cov)<- names
species.cov[,1]<- as.character(species.cov[,1])
#########################################################################################
### STEP 4: Load in additional raster layers for simulations ###
#########################################################################################
#Three additional raster layers are required for simulations - a parks layer, a remote layer and a vegetation layer
#The parks layer is needed if you want to estimate power within smaller level management units (hereafter referred to as parks).
#Each park should be defined by an integer value starting at 1. For instance, if there are 2 parks, all cells in the first park should be given a value of 1, and all cells in the second park should be given a value of 2 and so forth
#Type 'parks' before laoding in your own layer to see what this raster should look like
#If you only want to estimate power at a landscape level, you'll still have to load in a parks layer. In this case, just load in a raster layer with all cells equal to 1
#A remote layer is needed to divide monitoring sites between different regions of the landscape
#The remote layer should contain 1s and 0s only, with 1s defining remote areas, 0s non-remote areas (i.e burnt and un-burnt).
#You might not want to divide your monitoring sites between remote and non-remote areas. In this case, just make all your cells in the remote layer equal to 1
#In the example data, the veg layer is needed to simulate fire at monitoring sites. Type 'veg' to see what it looks like
#If you don't intend on modelling fire, the program still requires a veg layer. Once again, just make all values equal to 1.
parks<- raster("spotR/layers/burnt.tif") # Load in layer of burnt and unburnt areas.
zonationOutput<- raster(sprintf("zonation/Zout/Z_%s_5k.CAZ_DEA.rank.compressed.tif", group)) # Load in Zonation output.
zonationOutput[zonationOutput < 0.9]<- NA #Mask out bottom 90% of Zonation layer.
remote<- raster("spotR/layers/remote.tif") # Load in remote layer - this is a map of the edge of burnt areas. We might load in the top 10% of the landscape here determined with Zonation.
vic.road<- raster("spotR/layers/vic.road.tif") # Load in time to destination layer for cost function.
veg<- remote # Fire severity classes for site stratification.
init.occ.burnt <- 0.01 # Set initial occupancy in burnt cells.
#########################################################################################
### STEP 4: (optional) Decide whether to model fire and load in fire history layer ###
#########################################################################################
# If you model fire at monitoring sites, you have to load in two additional raster stacks - one stack of the environmental covariates in the study region and one stack of the fire history for each cell
# The stack covar is a raster stack of environmental covariates. It is used to update occupancy and detectability layers for fire pronce species given the statistical models
# In the example dataset, the layers correspond to the following covariates - #1=dem, 2=creek, 3-moist, 4=Tfire, 5=Ffire, 6=roughness, 7=temp
# The fire stack defines the fire history over a pre-determined time period, with 1s represting fire events, 0s representing no fires in a cell for that year
# The example fire raster stack has fire history for the proceding 15 years. This is used to simulate further fire events for each new year of simulations
model.fire<- FALSE # Is fire modelled at sites. Set to TRUE to model fire, FALSE otherise.
if (model.fire == TRUE) {
covar<- stack("~/Kakadu/Paper2/Mapsv2/layers2.tif") # Load in covariate raster stack.
fire<- stack("~/Kakadu/Paper2/Mapsv2/fire.tif") # Load in fire history raster stack.
}
###########################################################################################
### STEP 5: Define suite of input parameter for the select sites and cost functions ###
###########################################################################################
n.species<- nlayers(occ) # Calculates the number of species.
n.park<- unique(parks) # Calculates the number of parks.
###########################################################################################
### STEP 6: Define where and how to select monitoring sites ###
###########################################################################################
# A three monitoring scenarios can be evaulated. Power can be assessed through:
# 1) Randomly paired sites - sites are randomly selected across the landscape, but paired across burnt and unburnt zones.
# 2) Zonation paired sites - sites are randomly selected across the top 10% of the occupancy cells defined via the Zonation input layer. Sites are paired across burnt and unburnt areas.
# 3) Pre-selected sites - sites are pre-defined via a shape file.
existing.sites<- FALSE # If you want to simulate monitoring at pre-selected sites, set to TRUE. Otherwise, set to FALSE.
sites<- shapefile("spotR/inputs/exisitingSitesShapefile/exisitingSitesSPDF.shp") # If you specifying TRUE above, load in a shapefile of existing sites (as a spatial points dataframe)
sites<- unique(sites@coords) # Extract site co-ordinates.
include.site<- extract(zonationOutput, sites[,1:2]) # Crop to sites within stuyd area.
sites<- sites[!is.na(include.site),] # Remove NA sites.
all.existing.sites<- all.existing.sites #.If you want to monitor via '(2) Randomly paired sites' set to TRUE. If FALSE sites will be selected in random pairs (option 1).
if (existing.sites == TRUE & all.existing.sites == TRUE) {n.sites<- nrow(sites)} else { #If you're monitoring all pre-selected sites, the number of sites is equal to the number of rows in the XY coordinate list.
n.sites<- 100} #If you're monitoring a subset of the pre-selected sites, enter the MAXIMUM number of sites you wish to survey. Note this can be greater than the number of pre-selected sites.
init.sites <- n.sites # Set global site max parameter.
R<- site.ratio # This defines the ratio of burnt to unburnt sites. For example, R = 0.4 means that 40% of sites will be in burnt areas and 60% will be in non-burnt areas. If you don't have burnt or non-burnt areas, make all cells in your remote layer equal to 1 and make R = 1.
new.site.selection<- "pairs" # If you don't pre-select sites, specify how sites will be selected. Currently pairs is the only option.
###########################################################################################
### STEP 7: Define when to monitor ###
###########################################################################################
# Users can specify the length of the monitoring program, the years in which monitoring occurs, and the number of repeat visits to each site for each detection method.
Tmax<- 10 # Define length of monitoring program in years.
if (survey.year == 1){s.years<- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)} else {s.years<- c(1, 3, 5, 7, 10) } # Reduce the years in which bats surveys occur as they are expensive.
if (repeat.scenario == 1){n.method<- read.csv("spotR/inputs/repeatVisits.csv")} else {n.method<- read.csv("spotR/inputs/repeatVisits_2.csv")} # Set the scenario of repeat visits to a site. The second option has a reduce number of site repeats.
colnames(n.method)<- c("Group", "Method1", "Method2", "Method3", "Method4")
n.method<- as.numeric(n.method[n.method$Group==group, 2:5]) # Set the number of repeats for a given species group.
###########################################################################################
### STEP 7: Define the power analysis parameters ###
###########################################################################################
# Users must now decide whether calculate power within smaller level management units, how species are expected to decline over time, the Type I error rate,
# whether to conduct a one or two tailed test, the magnitude of the reduction in occupancy over the monitoring program and the number of simulations.
park.level<- FALSE # Set to TRUE to estimate power at a park level, FALSE to estimate power just at a landscape-level.
decline<- "random" # Random is the only option - it means we simulate a constant decline in occupancy across space.
trend<- "increasing" # Set to 'decreasing' for a decreasing trend in occupancy and 'increasing' for an increasing trend.
model.variation<- FALSE # Set if the model takes in variation.
variation<- c(0.273, 0.376, 0.523, 0.073, 0.154, 0.035, 0.523, 0.229, 0.073, 0.229, 0.035, 0.376) # Set model variation
alpha<- 0.1 # Set significance level. Choose from 0.01, 0.05 or 0.1.
two.tailed<- FALSE # Decide on a one-tailed or two-tailed signficance test. Set to TRUE for a two tailed test, FALSE for a one-tailed test.
effect.size<- c(0.1, 0.3, 0.5, 0.7, 0.9) # Decide on the proportional reduction in occupancy at Tmax. This can be a vector ranging from a small changes in occupancy to very large changes.
nsims<- 100
###########################################################################################
### STEP 7: Set up monitoring sites ###
###########################################################################################
# This section calls the select.sites function to return monitoring sites for the first simulation given the information provided above.
# Occupancy and detectability values are then extracted from the sites for further processing. If all pre-selected sites are to be surveyed this function is not called again.
plotter<- FALSE # Set to TRUE to plot monitoring sites at the start of each simuation.
xy.sites<- select.sites(sites, n.sites, R, all.existing.sites, existing.sites, new.site.selection, plotter, occ, zonationOutput) # Define monitoring sites.
xy.sites2<- SpatialPoints(xy.sites[,1:2], proj4string = CRS("+proj=lcc +lat_1=-36 +lat_2=-38 +lat_0=-37 +lon_0=145 +x_0=2500000 +y_0=2500000 +ellps=GRS80 +units=m +no_defs ")) # Turn to spatial to allocated site 'zone'.
park.ID<- parks[cellFromXY(parks, xy.sites2)] # Extract park values at monitoring sites.
park.ID[is.na(park.ID)]<- 3
xy.sites<- cbind(xy.sites[,1:3], park.ID) # Combined XY coordinates of sites with park values.
###########################################################################################
### STEP 8: Compute cost to set up sites, and remove sites based on budget ###
###########################################################################################
# This section calls upon cost.to.survey function to return the cost to monitor a site given the species present, travel time and the detection methods used to find each species (taking into account survey duration and repeats),
# Up to four detection methods are assigned from species.detection (Step 3), with costs defined via detection.costs.
# Site locations are taken from xy.sites (Step 10), and travel time to each site is extracted from vic.road within the cost.to.survey.site function.
overhead.cost<- FALSE # Set whether to include set up costs in budgeting.
# Define proportion of monitoring budget for each species group Plants get 40% of budget (correspondance with DELWP).
max.budget<- (max.budget* (n.species/45))
# Load in method cost table.
method.cost.array<- read.csv("spotR/inputs/method.cost.array.csv")
# Run cost function, outputs cost table header and plot of site locations.
project.costs <- cost.to.survey.site(zonationOutput, occ, sites, xy.sites, species.detection, species.detection.all, existing.sites, n.sites, s.years, n.method, group, vic.road, method.cost.array, overhead.cost, max.budget, plotter)
# Remove excess sites over budget.
program.cost <- remove.excess.site(new.site.selection, project.costs, max.budget, all.existing.sites, det.method1.time, det.method2.time, det.method3.time, det.method4.time, occ.time, occ, plotter, xy.sites)
program.cost <- sum(program.cost$program.cost) # Total cost of monitoring program
###########################################################################################
### STEP 9: Define which sites are management, and the benefit of management ###
###########################################################################################
man.effect.size <- 0
prop.man <- 0.5
managed <- rep(0, nrow(xy.sites))
managed[sample(nrow(xy.sites), round(nrow(xy.sites)*prop.man))] <- 1
xy.sites <- cbind(xy.sites, managed)
###########################################################################################
### STEP 10: Perform a pre-simulation check of layers and inputs ###
###########################################################################################
# Check all raster layers have the same dimensions and then run the power analysis.
# A warning message will be displayed if there is a mismatch between rasters.
# This types of analysis can take a long time on a desktop. The time required to run a simulation will increase with the number of species, the number of cells in each raster, the number of sites, whether siets are randomly selected each simulation, whether fire is modelled, whether power is estimated at a park level etc
# Simulations can be sped up by running them in parallel (or via computing clusters). Excessively large datasets should be run on a computer with at least 10 cores .
check.inputs(occ) # This function checks for any mismatches bewteen raster layers. If nothing is returned, everything's OK .
###########################################################################################
### STEP 11: Define inputs for analysis on the HPC computing resource ###
###########################################################################################
n.cores<- 5 # Define the number of cores per node. This needs to reflects the number in 'job_submission.slurm', with one additional core to run background tasks.
start.time<- proc.time() # Record start time for run comparison.
registerDoFuture() # Register the cores via the 'Future' and 'doFuture' R package.
plan(multiprocess, workers = n.cores) # This function detects the OSX and computer specification and automatically set's up the inputs for parralel computing. Set to plan(sequential) to run in sequence locally.
###########################################################################################
### STEP 12: Run the simulation and save out objects for plotting and analysis ###
###########################################################################################
# Run the power analysis. Set %dopar% to run in parallel, %do% otherwise. Note, you cannot track progress in parallel. If you run in sequence first, you can see how long it takes to do each step of the simulation.
pwr<- foreach(i = 1:n.cores,.combine = '+',.packages = c("raster", "rgdal")) %dopar% {
set.seed(1234 + i) # Set unique seed for each node of the analysis.
.libPaths("/home/asmart1/R/lib/3.6") # Point to library on HPC cluster.
library("unmarked") # Load in node specific dependacies.
library("rgdal")
sapply(effect.size, run.power,
nsims = nsims,
alpha = alpha,
decline = decline,
Tmax = Tmax,
s.years = s.years,
trend = trend,
sites = sites,
model.fire = model.fire,
species.list = species.list,
park.level = park.level,
xy.sites = xy.sites,
R = R,
two.tailed = two.tailed,
plotter = plotter,
n.sites = n.sites,
n.species = n.species,
n.park = n.park,
all.existing.sites = all.existing.sites,
existing.sites = existing.sites,
new.site.selection = new.site.selection,
n.method = n.method,
occ = occ,
det.method1 = det.method1,
det.method2 = det.method2,
det.method3 = det.method3,
det.method4 = det.method4,
veg = veg,
remote = remote,
parks = parks,
variation = variation,
model.variation = model.variation,
zonationOutput = zonationOutput,
species.detection = species.detection,
species.detection.all = species.detection.all,
group = group,
vic.road = vic.road,
method.cost.array = method.cost.array,
overhead.cost = overhead.cost,
max.budget = max.budget,
project.costs = project.costs,
init.sites = init.sites,
prop.man = prop.man,
man.effect.size = man.effect.size,
init.occ.burnt = init.occ.burnt,
program.cost = program.cost)
}
time.elapsed<- proc.time() - start.time # Record end time for run comparison.
time.elapsed # Print elapsed time.
plan(sequential) # Close nodes post simulation.
############################################################################################
### STEP 13: Save outputs and plot results ###
############################################################################################
Results<- plot.results(pwr, n.species, nsims, effect.size, n.park, species.list, n.cores)
# Produce table of power values per species.
pwrtble<-matrix(NA, nrow = 5, ncol = nrow(species.list))
for (i in 1:5){
pwrtble[i,]<- Results[[1]][,,i][1,]
}
colnames(pwrtble)<- species.list$Species
row.names(pwrtble)<- c("0.1", "0.3", "0.5", "0.7", "0.9")
powerTable<- t(pwrtble)
# Write table to local.
write.table(powerTable, file = sprintf("out/tabs/powerTable_%04d_group=%s_zonation=%s_site.ratio=%s_repeat.scenario=%s_method.scenario=%s_survey.year=%s.txt", parameter_index, group, all.existing.sites, site.ratio, repeat.scenario, method.scenario, survey.year), sep = ",", row.names = T, col.names = T )
# Save out model object.
save(pwr, file = sprintf("out/output_%04d_group=%s_zonation=%s_site.ratio=%s_repeat.scenario=%s_method.scenario=%s_survey.year=%s.RData", parameter_index, group, all.existing.sites, site.ratio, repeat.scenario, method.scenario, survey.year))
# Save out diagnostic plot.
pdf(file = sprintf("out/figs/power_efs_%04d_group=%s_zonation=%s_site.ratio=%s_repeat.scenario=%s_method.scenario=%s_survey.year=%s.pdf", parameter_index, group, all.existing.sites, site.ratio, repeat.scenario, method.scenario, survey.year), height = 8.5, width = 8.5)
Results<- plot.results(pwr, n.species, nsims, effect.size, n.park, species.list, n.cores)
dev.off()
|
0cbdfe310b67c47ae7c1709d9997b7e559a90bbb
|
[
"R"
] | 2 |
R
|
assma1/VICFire
|
78aad66323de989c815f618e8a4c4b67500dd90f
|
5e93f8af37c702b0c4fb14732752a98e8ed36af0
|
refs/heads/master
|
<file_sep>//
// main.c
// Learning C ansi
//
// Created by <NAME> on 05/02/2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
#include <stdio.h>
/* Вывод таблицы температур по Фаренгейту и Цельсию
для farh = 0, 20, ..., 300 */
/*int main()
{
float fahr, celsius;
int lower, upper, step;
lower = 0;
upper = 300;
step = 20;
printf("Фаренгейт - Цельсий\n");
fahr = lower;
while (fahr <= upper) {
celsius = (5.0/9.0) * (fahr-32.0) ;
printf("%6.0f %10.1f\n", fahr, celsius);
fahr = fahr + step;
}
}
*/
int main()
{
float fahr, celsius;
int lower, upper, step;
lower = -20; /* нижняя граница температур в таблице */
upper = 150; /* верхняя граница */
step = 10; /* величина шага */
printf("Цельсий - Фаренгейт\n");
celsius = lower;
while (celsius <= upper) {
fahr = celsius * (9.0/5.0) + 32.0 ;
printf("%6.0f %10.0f\n", celsius, fahr);
celsius = celsius + step;
}
}
|
ed4bc08a61de8281f88ed9b87b8638ceb98d68c9
|
[
"C"
] | 1 |
C
|
VitalyBesedin/Learning-C-ansi
|
51395a31b1055d926f981cf323103bcdafddb06c
|
3e695d096e2d9e90ea834b9f6b32c92a86e957c2
|
refs/heads/master
|
<file_sep>package com.reduse.quations;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class CheatActivity extends LoggingActivity {
private static final String KEY_CORRECT_ANSWER ="key_correct_answer";
private static final String KEY_CORRECT_ANSWER_WAS_SHOW ="key_correct_answer_was_show";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
Button showCorrectAnswerButton = findViewById(R.id.show_answer_button);
showCorrectAnswerButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
showCorrectAnswer();
}
});
}
private void showCorrectAnswer() {
Intent intent = getIntent();
boolean correctAnswer = intent.getBooleanExtra(KEY_CORRECT_ANSWER,false);
TextView correctAnswerView = findViewById(R.id.correct_answer);
correctAnswerView.setText(String.valueOf(correctAnswer));
setResult(RESULT_OK,makeAnswerShowIntent());
}
private static Intent makeAnswerShowIntent(){
Intent intent =new Intent();
intent.putExtra(KEY_CORRECT_ANSWER_WAS_SHOW,true);
return intent;
}
public static Intent makeIntent (Context context, boolean correctAnswer){
Intent intent = new Intent(context, CheatActivity.class);
intent.putExtra(KEY_CORRECT_ANSWER, correctAnswer);
return intent;
}
public static boolean correctAnswerWasShow(Intent intent){
return intent !=null && intent.getBooleanExtra(KEY_CORRECT_ANSWER_WAS_SHOW,false);
}
}
<file_sep>include ':app'
rootProject.name='Quations'
|
64d659902217ed6236eab04691b670c7a90779c8
|
[
"Java",
"Gradle"
] | 2 |
Java
|
Reduse-git/Java_hw
|
1a9dceae58d9c84f2ef8dd3e7dcb90cb05d631c0
|
21769118a299314c67145dfca2b25175e990df8c
|
refs/heads/master
|
<file_sep>__author__ = 'pelumi'
from textblob import TextBlob
import pandas as pd
PRODUCTS_FILE = "../../../data/products.txt"
LISTINGS_FILE = "../../../data/listings.txt"
all_manufacturers = []
all_model_numbers = []
families = []
def loadJsonToDf(filename):
# read the entire file into a python array
with open(filename, 'rb') as f:
data = f.readlines()
# remove the trailing "\n" from each line
data = map(lambda x: x.rstrip(), data)
data_json_str = "[" + ','.join(data) + "]"
# now, load it into a pandas data frame
df = pd.read_json(data_json_str)
return df
def find_manufacurer(title, set):
tokens = extract_tokens(title)
for token in tokens:
#print(token)
if token in set:
print(token)
return token
def extract_tokens(title):
#take to lower case
blob = TextBlob(title).lower()
#TODO extract bigrams and trigrams also
#bigrams = blob.ngrams(2)
#trigrams = blob.ngrams(3)
#unigrams = blob.ngrams(1)
return blob.words
def describe_data(df):
print df.describe(percentiles=True)
def products_with_2_propertie(df, property1="manufacturer", value1="", property2="family", value2=""):
print df.loc[(df[property1] == value1) & (df[property2] == value2)]
def products_with_property(df, property="manufacturer", value=""):
print df.loc[(df[property] == value) & (df["family"] == "IXUS") ]
def create_data_hash():
global all_manufacturers, families, all_model_numbers
all_manufacturers = set(pd.unique(products_df["manufacturer"].str.lower().ravel()))
#print(all_manufacturers)
all_model_numbers = set(pd.unique(products_df["model"].str.lower().ravel()))
families = set(pd.unique(products_df["family"].str.lower().ravel()))
# print all_manufacturers
# print(all_model_numbers)
# print ("Total manufacturers is: ", all_manufacturers.size)
# print ("Total families is: ", families.size)
# print ("Total models is: ", all_model_numbers.size)
products_df = loadJsonToDf(PRODUCTS_FILE)
create_data_hash()
#describe_data(products_df)
#listings_df = loadJsonToDf(LISTINGS_FILE)
find_manufacurer("Canon PowerShot D10 12.1 MP Waterproof Digital Camera with 3x Optical Image Stabilized Zoom and 2.5-inch LCD (Blue/Silver)", all_model_numbers)
#products_with_property(products_df, "manufacturer", "Canon")
<file_sep>__author__ = 'pelumi'
|
553e8b9377c3216c39ffefe3d3f2fecd8564eade
|
[
"Python"
] | 2 |
Python
|
Pelumi/ProductRecordLinkage
|
cc983c9d253b099c490221a9c59973ea9e77c6de
|
09f5f6b4d72a584068602f1650dd2fe35f50feaf
|
refs/heads/master
|
<file_sep>import csv, os
import xml.etree.ElementTree as ET
default_ns = {'ksj': 'http://nlftp.mlit.go.jp/ksj/schemas/ksj-app', 'jps': 'http://www.gsi.go.jp/GIS/jpgis/standardSchemas'}
# xmlファイルからバス停一覧と位置情報一覧のETオブジェクトを作る。
def load_xml(xml_path = "./xml/P11-10_13/P11-10_13-jgd.xml", ns = default_ns):
tree = ET.parse(xml_path)
root = tree.getroot()
dataset = root.find('dataset')
ksj_object = dataset.find('ksj:object', ns)
ksj_AA01 = ksj_object.find('ksj:AA01', ns)
ksj_OBJ = ksj_AA01.find('ksj:OBJ', ns)
ksj_ED01_list = ksj_OBJ.findall('ksj:ED01', ns)
jps_GM_Point_list = ksj_OBJ.findall('jps:GM_Point', ns)
return ksj_ED01_list, jps_GM_Point_list
# バス停IDに対応する緯度経度のリストを返却する。
def get_latlng(jps_GM_Point_list, id, ns = default_ns):
for jps_GM_Point in jps_GM_Point_list:
if jps_GM_Point.attrib['id'] == id:
jps_GM_Point_position = jps_GM_Point.find('jps:GM_Point.position', ns)
jps_DirectPosition = jps_GM_Point_position.find('jps:DirectPosition', ns)
DirectPosition_coordinate = jps_DirectPosition.find('DirectPosition.coordinate')
return DirectPosition_coordinate.text.split()
# 路線に属するバス停のリストを返却する
def get_bus_stop_list(ksj_ED01_list, bus_operation_company, bus_line_name, ns = default_ns):
bus_stop_list = []
for ksj_ED01 in ksj_ED01_list:
ksj_POS = ksj_ED01.find('ksj:POS', ns)
ksj_BSN = ksj_ED01.find('ksj:BSN', ns)
ksj_BRI_list = ksj_ED01.findall('ksj:BRI', ns)
for ksj_BRI in ksj_BRI_list:
ksj_BLN = ksj_BRI.find('ksj:BLN', ns)
ksj_BOC = ksj_BRI.find('ksj:BOC', ns)
if ksj_BLN.text == bus_line_name and ksj_BOC.text == bus_operation_company:
bus_stop_list.append({'name':ksj_BSN.text, 'id': ksj_POS.attrib['idref']})
return bus_stop_list
# バス事業者と路線の組のリストを返却する。
def get_boc_bln_list(ksj_ED01_list, ns = default_ns):
bcn_bln_list = []
for ksj_ED01 in ksj_ED01_list:
ksj_POS = ksj_ED01.find('ksj:POS', ns)
ksj_BSN = ksj_ED01.find('ksj:BSN', ns)
ksj_BRI_list = ksj_ED01.findall('ksj:BRI', ns)
for ksj_BRI in ksj_BRI_list:
ksj_BLN = ksj_BRI.find('ksj:BLN', ns)
ksj_BOC = ksj_BRI.find('ksj:BOC', ns)
bcn_bln_list.append([ksj_BOC.text, ksj_BLN.text])
seen = []
return [x for x in bcn_bln_list if x not in seen and not seen.append(x)]
# CSVを作成する。
def create_csv(ksj_ED01_list, jps_GM_Point_list, bus_operation_company, bus_line_name):
bus_stop_list = get_bus_stop_list(ksj_ED01_list, bus_operation_company, bus_line_name)
for bus_stop in bus_stop_list:
bus_stop['lat'], bus_stop['lng'] = get_latlng(jps_GM_Point_list, bus_stop['id'])
bus_stops = [[d['id'], d['name'], d['lat'], d['lng']] for d in bus_stop_list]
if len(bus_stops) > 0:
bus_operation_company = bus_operation_company.replace("/", "-")
bus_line_name = bus_line_name.replace("/", "-")
boc_path = f"./csv/{bus_operation_company}"
if not os.path.isdir(boc_path):
os.makedirs(boc_path)
with open(f'./csv/{bus_operation_company}/{bus_line_name}.csv', 'w') as f:
writer = csv.writer(f, lineterminator="\n")
writer.writerows(bus_stops)
print(f'./csv/{bus_operation_company}/{bus_line_name}.csv')
else:
print("エラー")
if __name__ == "__main__":
# バス停一覧と位置情報一覧のリストを取得
ksj_ED01_list, jps_GM_Point_list = load_xml()
# バス事業者と路線のすべての組でCSVを作成する。
boc_bln_list = get_boc_bln_list(ksj_ED01_list)
for boc_bln in boc_bln_list:
print(boc_bln)
bus_operation_company = boc_bln[0]
bus_line_name = boc_bln[1]
create_csv(ksj_ED01_list, jps_GM_Point_list, bus_operation_company, bus_line_name)
<file_sep>import json, os
from dotenv import load_dotenv
import requests
def geocoding(address: str):
return "not supported"
def reverse_geocoding(lat: float, lng: float, key: str,language="ja", format="json"):
url = f"https://maps.googleapis.com/maps/api/geocode/{format}"
payload = {"latlng": f"{lat},{lng}", "key": key, "language": language}
r = requests.get(url, params=payload)
data = r.json()
address = json.dumps(data["results"][0]["formatted_address"])
# ユニコードのおまじない
return address.encode().decode('unicode-escape')
if __name__ == "__main__":
load_dotenv()
key = os.environ["APIKEY"]
address = reverse_geocoding(35.684,139.836,key)
print(address)
|
0062d40477a9e0714abced88d9b6ec2dc47cbd83
|
[
"Python"
] | 2 |
Python
|
tetla/bus_stop_csv
|
d381853496347544e07d8b76c0458132f4f4edeb
|
bb3696909085e5820431782c869d2871df0349cf
|
refs/heads/main
|
<repo_name>AQurexi/Lab3<file_sep>/RepsitoryPattern/Data/Admin.cs
using System;
using System.ComponentModel.DataAnnotations;
namespace RepsitoryPattern.Data
{
public class Admin
{
[Key]
public Guid AdminId { get; set; }
public string AdminName { get; set; }
public string Reputation { get; set; }
}
}<file_sep>/RepsitoryPattern/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using RepsitoryPattern.Data;
using RepsitoryPattern.Models;
namespace RepsitoryPattern.Controllers
{
public class HomeController : Controller
{
public ApplicationDbContext context;
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger, ApplicationDbContext Context)
{
context = Context;
_logger = logger;
}
public IActionResult Index()
{
var books = from products in context.products join admins in context.admins
on products.AdminId equals admins.AdminId
join manufacturer in context.manufacturers on products.manufacturerId equals manufacturer.Id select products;
foreach (var item in books)
{
ProductViewModel model = new ProductViewModel()
{
ProductName = item.ProuctName,
ManufacturerName = item.manufacturer.ManufacturerName,
AdminName = item.admin.AdminName,
};
}
return View(books);
}
public IActionResult AddProduct([FromBody] ProductViewModel product)
{
var admin = new Admin()
{
AdminName = product.AdminName
};
context.Add(admin);
context.SaveChanges();
Product book1 = new Product
{
AdminId = admin.AdminId,
ProuctName = product.ProductName,
Category = product.Categroy
};
context.Add(book1);
context.SaveChanges();
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 });
}
}
}
<file_sep>/RepsitoryPattern/Models/ProductViewModel.cs
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace RepsitoryPattern.Data
{
public class ProductViewModel
{
public int ProductId { get; set; }
public string ProductName { get; set; }
public string AdminName{ get; set; }
public string ManufacturerName{ get; set; }
public string Categroy { get; internal set; }
}
}<file_sep>/RepsitoryPattern/Data/Product.cs
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace RepsitoryPattern.Data
{
public class Product
{
public int ProductId { get; set; }
public string ProuctName { get; set; }
public string Category { get; set; }
public Admin admin { get; set; }
[ForeignKey("Id")]
public Guid AdminId { get; set; }
[ForeignKey("Id")]
public int manufacturerId { get; internal set; }
public Manufacturer manufacturer { get; set; }
}
}
|
bda1b89cf8fe5e4e0dbc9f270fa7c15ed5f5df2a
|
[
"C#"
] | 4 |
C#
|
AQurexi/Lab3
|
5babe923f81c288e84ef4c8e171771998246e30b
|
01c6542120dd35a18f9230a3e51f46432335220c
|
refs/heads/master
|
<file_sep>Do.add('sh-css', {
path: '/css/sh_kwrite.min.css',
type: 'css'
});
Do.add('sh', {
path: '/js/sh_main.min.js',
requires: ['sh-css'],
type: 'js'
});
Do.add('upload', {
path: '/js/upload.min.js',
type: 'js'
});
Do.add('editor', {
path: '/js/editor.js',
requires: ['upload'],
type: 'js'
});
Do.add('comment', {
path: '/js/comment.js',
type: 'js'
});
Do.ready('sh', function() {
window.sh_highlightDocument('/js/lang/', '.min.js');
});
<file_sep>var path = require('path')
, express = require('express')
, mongoose = require('mongoose')
, MongoStore = require('connect-mongo')(express)
, istatic = require('istatic')
, stylus = require('stylus')
, utils = require('./lib/utils')
, noteModels = require('./models/note')
, userModels = require('./models/user')
, config = JSON.parse(require('fs').readFileSync(
__dirname + '/config.json', 'utf8'))
, app = module.exports = express()
, Note, Comment, TrackBack, User, LoginToken
, pathPublic = path.join(__dirname, 'public');
app.configure(function() {
function compile(str, path) {
return stylus(str)
.set('filename', path)
// Data URI image inlining
.define('url', stylus.url({
paths: [pathPublic + '/img'] }))
.set('compress', true);
}
app.set('port', process.env.PORT || 8126);
app.set('view engine', 'jade');
app.use(stylus.middleware({
src: pathPublic,
dest: pathPublic,
compile: compile
}));
app.locals({
istatic: istatic.serve()
});
// set mongodb connection
app.set('connection', config.db.conn);
// Middleware
app.use(express.logger(
//:remote-addr:status:referrer
'\x1b[0m:date \x1b[32m:method\x1b[0m \x1b[33m:url\x1b[31m :response-time ms \x1b[36m:user-agent'));
app.use(express.bodyParser({
keepExtensions: true,
uploadDir: utils.getUploadPath()
}));
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session({
cookie: { maxAge: 43200000 },
store: new MongoStore({ url: app.set('connection') }),
secret: 'nodecat'
}));
app.use(express.static(pathPublic));
app.set('views', __dirname + '/views');
app.use(function(err, req, res, next) {
if (err instanceof utils.NotFound) {
res.render('error/404.jade', {
error: err,
title: err.name
});
} else if (err instanceof utils.InternalServerError) {
res.render('error/500.jade', {
error: err,
title: err.name
});
} else {
console.error(err);
}
});
});
// $ NODE_ENV=development node app.js
app.configure('development', function() {
app.set('port', 7901);
app.use(express.errorHandler({
dumpExceptions: true,
showStack: true
}));
});
// Models
noteModels.define(mongoose, function() {
Note = mongoose.model('Note');
Comment = mongoose.model('Comment');
TrackBack = mongoose.model('TrackBack');
});
userModels.define(mongoose, function() {
User = mongoose.model('User');
LoginToken = mongoose.model('LoginToken');
});
// Connection
mongoose.connect(app.set('connection'));
// Routes
require('./router')(app, Note, Comment, TrackBack, User, LoginToken, config);
if (!module.parent) {
app.listen(app.set('port'));
console.info('Express server listening on port %d', app.get('port'));
}
<file_sep>(function() {
var doc = document
, s = doc.getElementsByTagName('script')[0]
, rdb = doc.createElement('script');
rdb.async = true;
rdb.src = doc.location.protocol
+ '//www.readability.com/embed.js';
s.parentNode.insertBefore(rdb, s);
})();
|
12fc004a27a77ee73396385394fd506799c6b74b
|
[
"JavaScript"
] | 3 |
JavaScript
|
imbugs/nodecat
|
6b65e9c55acb3a419bfb1a383ed45ac458741811
|
cb583dab2db1526b7a5088a47fd14ef124e95ad3
|
refs/heads/main
|
<file_sep>import fetch from "node-fetch";
import requirejs from "requirejs"
const apiKey = "39c3606dee2f4a4f9b5152122212709"// "<KEY>"
const getRequestLink = (latLon, startDate, endDate) => (`http://api.worldweatheronline.com/premium/v1/past-weather.ashx?
key=${apiKey}
&q=${latLon}
&format=json
&date=${startDate}
&enddate=${endDate}`);
const startDate = "2009-01-01"
const findLat = 28.645
const findLon = 77.217 // LatLon of Delhi
const city_distance_km = [20, 100, 500] // North South East West len(..) cities are generated
/** For whole day, got directly */
const directParams = {
"date": (dayData) => dayData["date"],
"Max Temp (c)": (dayData) => dayData["maxtempC"],
"Min Temp (c)": (dayData) => dayData["mintempC"],
"Avg Temp (c)": (dayData) => dayData["avgtempC"],
"Snow (cm)": (dayData) => dayData["totalSnow_cm"],
"Sun Time (Hours)": (dayData) => dayData["sunHour"],
"UV Index": (dayData) => dayData["uvIndex"]
}
/** Derived from hourly, To add more params, insert in this object with value = way of extraction */
const derivedParams = {
"Total Precipitation (MM)":
(hourly) => (
hourly.map((cur) => (parseFloat(cur["precipMM"])))
.reduce((acc, cur) => acc + cur)
),
"Avg Pressure (P)":
(hourly) => (
hourly.map((cur) => (parseFloat(cur["pressure"]) / hourly.length))
.reduce((acc, cur) => acc + cur)
),
"Avg Humidity (%)":
(hourly) => (
hourly.map((cur) => (parseFloat(cur["humidity"]) / hourly.length))
.reduce((acc, cur) => acc + cur)
),
"Avg Cloud Cover":
(hourly) => (
hourly.map((cur) => (parseFloat(cur["cloudcover"]) / hourly.length))
.reduce((acc, cur) => acc + cur)
),
"Avg Resultant Wind vector [E](km/h)": // Vector addition of hourly winds
(hourly) => {
const windVectors = extractWindVectors(hourly);
const resultant = windVectors.reduce((acc, cur) => ([acc[0] + cur[0], acc[1] + cur[1]]));
return (resultant.map(k => k / hourly.length))[0]
},
"Avg Resultant Wind vector [N](km/h)": // Vector addition of hourly winds
(hourly) => {
const windVectors = extractWindVectors(hourly);
const resultant = windVectors.reduce((acc, cur) => ([acc[0] + cur[0], acc[1] + cur[1]]));
return (resultant.map(k => k / hourly.length))[1]
},
}
const fetchAllData = async (latLon, startDate, endDate) => {
if (endDate < startDate) {
return null;
} else {
const response = await fetch(getRequestLink(latLon, startDate, endDate));
return await response.json()
}
}
/** Returns Extracted data and end date */
const processRawData = (rawData) => {
if (rawData["data"]["error"] !== undefined) {
console.error("Error Fetching data, received:", rawData["data"]["error"][0])
return null;
}
if (rawData["data"]["request"][0].type !== 'LatLon') {
console.error("Not a LatLon:", rawData["data"]["request"][0].query)
return null;
}
let extractedData = {
"dayWiseData": []
};
for (let i = 0; i < rawData["data"]["weather"].length; i++) {
let newInsertion = {};
extractedData["dayWiseData"].push(newInsertion);
for (const directParamsKey in directParams) {
newInsertion[directParamsKey] = directParams[directParamsKey](rawData["data"]["weather"][i])
}
for (const derivedParamsKey in derivedParams) {
newInsertion[derivedParamsKey] = derivedParams[derivedParamsKey](rawData["data"]["weather"][i]["hourly"])
}
}
return [
extractedData,
rawData["data"]["weather"]
[(rawData["data"]["weather"]).length - 1]["date"]
]
}
const getAllData = async (latLon) => {
let nextStart = new Date(startDate.replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$3/$1"))
let endDate = new Date();
let answer = null
while (nextStart <= endDate) {
const stringStartDate = nextStart.toISOString().split('T')[0]
const stringEndDate = endDate.toISOString().split('T')[0]
let got = processRawData(
await fetchAllData(latLon, stringStartDate, stringEndDate)
)
if (got === null) {
return null
} else if (answer === null) {
answer=got[0];
} else {
answer["dayWiseData"] = [...answer["dayWiseData"], ...got[0]["dayWiseData"]]
}
nextStart = new Date(got[1].replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$3/$1"))
nextStart.setDate(nextStart.getDate() + 1)
console.log(got[1], latLon)
}
return answer
}
const fs = requirejs("fs");
const saveDataFor = async (fileName, latitude, longitude) =>{
fs.writeFile(`./data/${fileName}.json`, JSON.stringify(await getAllData(
`${latitude.toFixed(3)},${longitude.toFixed(3)}`)), (err) => {
if (err)
console.log(err);
else {
console.log("File written successfully\n");
console.log("The written has the following contents:");
}
});
}
/** Main Function */
(async () => {
//AT GIVEN LAT LON
await saveDataFor("Delhi", findLat, findLon)
// At asked Distances
for (const distanceKey in city_distance_km) {
let distance = city_distance_km[distanceKey]
// North
let newLat = findLat + north_distance_to_latitude_difference(distance)
await saveDataFor(`North_${distance}`, newLat, findLon)
// South
newLat = findLat + north_distance_to_latitude_difference(-distance)
await saveDataFor(`South_${distance}`, newLat, findLon)
// East
let newLon = findLon + east_distance_to_longitude_difference(distance, findLat)
await saveDataFor(`East_${distance}`, findLat, newLon)
// West
newLon = findLon + east_distance_to_longitude_difference(-distance, findLat)
await saveDataFor(`West_${distance}`, findLat, newLon)
}
})()
/** UTILITY */
function sinDeg(degree) {
return Number(Math.sin(degree * Math.PI / 180).toFixed(5));
}
function cosDeg(degree) {
return Number(Math.cos(degree * Math.PI / 180).toFixed(5));
}
function extractWindVectors(hourly) {
return hourly.map((cur) => {
let windD = parseFloat(cur["winddirDegree"]), windS = parseFloat(cur["windspeedKmph"]);
return [windS * cosDeg(windD), windS * sinDeg(windD)]
})
}
function east_distance_to_longitude_difference(distance_km, latitude) {
const R_EARTH = 6378.1 //KM
const K = Math.pow(Math.tan(distance_km / (2* R_EARTH)), 2)
console.log(K)
console.log(K / (Math.pow(cosDeg(latitude), 2)*(K+1)))
const longitude_diff_rad = 2 * Math.asin(Math.sqrt((K) /
(Math.pow(cosDeg(latitude), 2)*(K+1))))
return longitude_diff_rad * 180.0 / Math.PI * Math.sign(distance_km)
}
function north_distance_to_latitude_difference(distance_km) {
return distance_km / 111.0
}<file_sep># Weather_Prediction
Weather Prediction Using Machine Learning
<file_sep>In file main.ipynb, change city.
CSV Data must be present for that city in data folder.<file_sep>### Run FetchWeather.mjs
To Get Data.
### Edit findLat and findLon in FetchWeather.mjs
To change city.
### Edit findLat and findLon in FetchWeather.mjs
To change distances
### Result in
./data folder. (Empty File to prevent github from deleting folder)
### Convert To CSV
Click [here](https://www.convertcsv.com/json-to-csv.htm). (Temporary Fix)
|
024384db2068354f5d8bcf40411a4588e4bf6b50
|
[
"JavaScript",
"Markdown"
] | 4 |
JavaScript
|
EtashTyagi/Weather_Prediction
|
293fdd68c55b873215fba5447646b7ab6a50f71a
|
d7f7d5f0dc8dbe533478ce295c823c09f2d70eee
|
refs/heads/master
|
<repo_name>vaibhavlm/nodejs_post_app<file_sep>/routes/comments.js
const store =require('./store')
const check = require('./validator')
module.exports = {
getComments(req, res) {
if(!check.ispost(req.params.postid, (e)=> res.status(401).send(e))) return
res.status(201).send(store.posts[req.params.postid].comments)
},
addComment(req, res) {
let errorcallback = (e)=> res.status(401).send(e)
if(!check.ispost(req.params.postid, errorcallback)) return
// if(!check.istext(req.body.text, errorcallback)) return
let newComment = req.body.text
let commentarr = store.posts[req.params.postid].comments
id = commentarr.length
console.log(JSON.stringify(req.body, 2));
commentarr.push(newComment)
res.status(201).send({id: id})
},
updateComment(req, res) {
let errorcallback = (e)=> res.status(401).send(e)
if(!check.ispost(req.params.postid,errorcallback)) return
if(!check.iscomment(req.params.commentid, req.params.postid, errorcallback)) return
// if(!check.istext(req.body.text, errorcallback)) return
store.posts[req.params.postid].comments[req.params.commentid] = Object.assign(store.posts[req.params.postid].comments[req.params.commentid], req.body)
res.status(201).send()
},
removeComment(req, res) {
let errorcallback = (e)=> res.status(401).send(e)
if(!check.ispost(req.params.postid, errorcallback)) return
if(!check.iscomment(req.params.commentid, req.params.postid, errorcallback)) return
store.posts[req.params.postid].comments.splice(req.params.commentid, 1)
res.status(201).send()
}
}<file_sep>/routes/posts.js
const store = require('./store')
const check = require('./validator')
module.exports = {
getPosts(req, res) {
res.status(201).send(store.posts)
},
addPost(req, res) {
if(!check.istext(req.body.name, (e)=>res.status(401).send(e))||!check.istext(req.body.url, (e)=>res.status(401).send(e))||!check.istext(req.body.text, (e)=>res.status(401).send(e))) return
let newPost = req.body
id = store.posts.length
store.posts.push(newPost)
res.status(201).send({id: id})
},
updatePost(req, res) {
if(!check.ispost(req.params.postid)) return
if(!check.istext(req.body.name, (e)=>res.status(401).send(e))||!check.istext(req.body.url, (e)=>res.status(401).send(e))||!check.istext(req.body.text, (e)=>res.status(401).send(e))) return
store.posts[req.params.id] = req.body
res.status(201).send(store.posts[req.params.postid])
},
removePost(req, res) {
store.posts.splice(req.params.postid, 1)
res.status(201)
}
}<file_sep>/routes/validator.js
const store = require('./store')
//const {check, vr} = require('express-validator')
module.exports.istext = (p, callback)=>{
if(typeof p !== "string"){
callback("the data is not a string")
return false
}
// if(p.trim()==""){
// callback("the string is empty")
// return false
// }
return true
}
module.exports.ispost = (postid , callback)=>{
if(!store.posts[postid]){
callback("the post doesnt exist")
return false
}
return true
}
module.exports.iscomment = (commentid, postid, callback)=>{
if(!store.posts[postid].comments[commentid]){
callback("the comment doesnt exist")
return false
}
return true
}
|
5a08e1235566d296f7be3c4d7e53d6c3475b8604
|
[
"JavaScript"
] | 3 |
JavaScript
|
vaibhavlm/nodejs_post_app
|
e9d0db72cfbdef2af2293b7d3cd781622384483b
|
68f0e04abee546051f8e3d54bef376282ddcc462
|
refs/heads/master
|
<file_sep># amdgpu_fanspeed
Usage:
python amdgpu_fans.py (-a AdapterNumberSplitbyCommas) -s speed0-100
Needs root privilege
<file_sep>import sys
from os import chdir,system,listdir
import getopt
import re
# vendor id of AMD
amdgpu_vendor_id = '0x1002'
def set_fan_speed(adapter, percent):
chdir('/sys/class/drm/card{}/device'.format(adapter))
vendor_id = '0000'
with open('vendor') as f:
vendor_id = f.readline()
f.close()
vendor_id = vendor_id.strip('\n')
# check if the device is AMD GPU by vendor ID
if vendor_id == amdgpu_vendor_id:
hwmon = listdir('/sys/class/drm/card{}/device/hwmon'.format(adapter))[0]
chdir('/sys/class/drm/card{}/device/hwmon/{}'.format(adapter, hwmon))
pwm_max = 0
pwm_min = 0
pwm = 0
with open('pwm1_max') as f:
pwm_max = int(f.readline().strip('\n'))
f.close()
with open('pwm1_min') as f:
pwm_min = int(f.readline().strip('\n'))
f.close()
pwm_gap = pwm_max - pwm_min
pwm = int( float(pwm_min) + float(pwm_gap) * float (percent/100.0))
system("echo 1 > pwm1_enable")
system("echo {} > pwm1".format(pwm))
# double check pwm
pwm_set = 0
with open('pwm1') as f:
pwm_set = int(f.readline().strip('\n'))
f.close()
if pwm_set > pwm - 6 and pwm_set < pwm + 6:
return True
else:
return False
else:
return False
if __name__ == '__main__':
try:
opts,args = getopt.getopt(sys.argv[1:],"a:s:")
except getopt.GetoptError:
print "Usage: amdgpu_fans.py (-a [Adapter No.]) -s [0-100])"
sys.exit(2)
adapters = '-1'
# read command line arguments
for opt,arg in opts:
if opt == '-a':
adapters = str(arg)
adapters = adapters.split(',')
if opt == '-s':
speed = int(arg)
# if -1 set all GPU speed
if adapters == '-1':
adapters = []
dir_list = listdir('/sys/class/drm')
for directory in dir_list:
reg = r'(?<=card)\d*$'
searchobj = re.search(pattern=reg, string=directory, flags=re.M|re.I)
if searchobj:
adapters.append(searchobj.group())
for adapter in adapters:
if set_fan_speed(int(adapter), speed):
print "Set adapter {} to speed {}%".format(adapter, speed)
else:
print "Set adapter {} failed, maybe not AMD GPU".format(adapter)
|
6b36d961295722fb230a43ab89e23e14e3fabab8
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
zypoi/amdgpu_fanspeed
|
7800f7dc094fad2fe5f0c37f5370ceadb55432f9
|
f4b913a0cd46f73d8af510477000cfd72bd15acb
|
refs/heads/master
|
<repo_name>johnnychiuchiu/blog<file_sep>/postlist.php
<!DOCTYPE html>
<html>
<head>
<title>Johnny's Blog</title>
<link type="text/css" rel="stylesheet" href="css/stylesheet.css" />
<meta charset="UTF-8">
<style>
#header {
background-color:black;
color:white;
text-align:center;
padding:5px;
}
</style>
</head>
<body>
<div id="header">
<h1>Johnny's Blog</h1>
</div>
<div id="nav">
<button onclick="location.href = './create.php';">新增文章</button>
<button href="#">文章列表</button>
</div>
<div id="section">
<?php
// include ("db_conn.php");
// $servername = "localhost";
// $username = "root";
// $password = "";
// $dbname = "blog";
// // Create connection
// $conn = new mysqli($servername, $username, $password, $dbname);
// if ($conn->connect_error) {
// die("Connection failed: " . $conn->connect_error);
// }
// echo "<br>"."Connected successfully";
// $dbhandle=mysql_connect("localhost","root","") or die ("連線失敗");
// $selected = mysql_select_db("blog",$dbhandle)
// or die("Could not select db");
// mysql_set_charset('utf8',$dbhandle);
include('db_conn.php');
$sql = "SELECT id, datetime, title, content FROM blog_post";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0) {
// output data of each row
while ($row = mysql_fetch_array($result)) {
echo "<fieldset>";
echo '<div class="block">';
echo "標題 :".$row["title"].'<br>';
echo "時間 :".$row["datetime"]."<br>";
if(str_word_count($row["content"])<50)
{
echo "內容 :".substr($row["content"],0,50).'<br>';
}
else
{
echo "內容 :".substr($row["content"],0,50).'......more'.'<br>';
}
echo '<font size="1">'.'<span class="pull-left">'.'<a href="edit.php?id=' . $row['id'] . '">繼續閱讀</a>'.'</span>'." ";
echo '<span class="pull-right">'.'<a href="delete.php?id=' . $row['id'] . '">Delete</a>'.'</span>'.'</font>';
echo '</div>';
echo "</fieldset>"."<br>"."<br>";
}
} else {
echo "none";
}
echo "<a href='postlist-paginated.php'>View Paginated</a>";
?>
</div>
</body>
</html>
<file_sep>/edit.php
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderPost($id, $title, $content, $error)
{
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Johnny's Blog</title>
<link type="text/css" rel="stylesheet" href="css/stylesheet.css" />
<meta charset="UTF-8">
<style>
#header {
background-color:black;
color:white;
text-align:center;
padding:5px;
}
</style>
</head>
<body>
<div id="header">
<h1>Johnny's Blog</h1>
</div>
<div id="nav">
<button onclick="location.href = './create.php';">新增文章</button>
<button onclick="location.href = './postlist.php';">文章列表</button>
</div>
<div id="section">
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<div>
<strong>標題: *</strong><br><input type="text" name="title" size="50" value="<?php echo $title; ?>" disabled><br>
<strong>文章內容: *</strong><br>
<textarea name="content" rows="46" cols="50" disabled=""><?php echo $content; ?></textarea>
</div>
</form>
<?php
include('db_conn.php');
$sql = "SELECT commentid, postid, comment, time FROM comment_test WHERE postid=$id";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0) {
// output data of each row
while ($row = mysql_fetch_array($result)) {
echo $row["comment"]." ".$row["time"]."<br>";
}
}
else
{
echo "<br>";
}
?>
<form name="form1" action="" method="post">
<strong>留言:</strong><br>
<textarea name="comment" rows="2" cols="30" value=""></textarea>
<input type="submit" name="submit" value="送出"/>
</form>
<button onclick="location.href = './postlist.php';">返回</button>
</div>
</body>
</html>
<?php
}
// connect to the database
include('db_conn.php');
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
$result = mysql_query("SELECT * FROM blog_post WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$title = $row['title'];
$content = $row['content'];
// show form
renderPost($id, $title, $content, '');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'Error!';
}
?>
<?php
// connect to the database
include('db_conn.php');
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
$id = $_GET['id'];
}
// get form data, making sure it is valid
$comment = $_POST["comment"];
// save the data to the database
mysql_query("INSERT comment_test SET comment='$comment', postid=$id")
or die(mysql_error());
$url="edit.php?id=".$id;
// once saved, redirect back to the view page
header("Location: $url");
}
?><file_sep>/postlist-paginated.php
<!DOCTYPE html>
<html>
<head>
<title>Johnny's Blog</title>
<link type="text/css" rel="stylesheet" href="css/stylesheet.css" />
<meta charset="UTF-8">
<style>
#header {
background-color:black;
color:white;
text-align:center;
padding:5px;
}
</style>
</head>
<body>
<div id="header">
<h1>Johnny's Blog</h1>
</div>
<div id="nav">
<button onclick="location.href = './create.php';">新增文章</button>
<button href="#">文章列表</button>
</div>
<div id="section">
<?php
// include ("db_conn.php");
// $servername = "localhost";
// $username = "root";
// $password = "";
// $dbname = "blog";
// // Create connection
// $conn = new mysqli($servername, $username, $password, $dbname);
// if ($conn->connect_error) {
// die("Connection failed: " . $conn->connect_error);
// }
// echo "<br>"."Connected successfully";
// $dbhandle=mysql_connect("localhost","root","") or die ("連線失敗");
// $selected = mysql_select_db("blog",$dbhandle)
// or die("Could not select db");
// mysql_set_charset('utf8',$dbhandle);
include('db_conn.php');
// number of results to show per page
$per_page = 5;
// figure out the total pages in the database
$sql = "SELECT id, datetime, title, content FROM blog_post";
$result = mysql_query($sql);
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $per_page);
// check if the 'page' variable is set in the URL (ex: view-paginated.php?page=1)
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
// make sure the $show_page value is valid
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
// error - show first set of results
$start = 0;
$end = $per_page;
}
}
else
{
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display pagination
for ($i = $start; $i < $end; $i++){
if ($i == $total_results) { break; }
echo "<fieldset>";
echo '<div class="block">';
echo "標題 :".mysql_result($result, $i, 'title') .'<br>';
echo "時間 :".mysql_result($result, $i, 'datetime')."<br>";
if(str_word_count(mysql_result($result, $i, 'content'))<50)
{
echo "內容 :".substr(mysql_result($result, $i, 'content'),0,50).'<br>';
}
else
{
echo "內容 :".substr(mysql_result($result, $i, 'content'),0,50).'......more'.'<br>';
}
echo '<font size="1">'.'<span class="pull-left">'.'<a href="edit.php?id=' . mysql_result($result, $i, 'id') . '">繼續閱讀</a>'.'</span>'." ";
echo '<span class="pull-right">'.'<a href="delete.php?id=' . mysql_result($result, $i, 'id') . '">Delete</a>'.'</span>'.'</font>';
echo '</div>';
echo "</fieldset>"."<br>"."<br>";
}
echo "<p><a href='postlist.php'>View All</a> | <b>View Page:</b> ";
for ($i = 1; $i <= $total_pages; $i++)
{
echo "<a href='postlist-paginated.php?page=$i'>$i</a> ";
}
echo "</p>";
?>
</div>
</body>
</html>
<file_sep>/db_conn.php
<?php
$dbhandle=mysql_connect("localhost","root","") or die ("連線失敗");
$selected = mysql_select_db("blog",$dbhandle)
or die("Could not select db");
mysql_set_charset('utf8',$dbhandle);
?><file_sep>/process.php
<?php
include ("db_conn.php");
$title = $_POST["title"];
$content = $_POST["content"];
if ($title == '' || $content == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
// if either field is blank, display the form again
echo "<a>"."<alert>".$error."</alert>"."</a>";
}
else
{
$sql="INSERT INTO blog_post (title, content) VALUES ('$title','$content')";
$result=mysql_query($sql);
header('Location: postlist.php');
}
?>
|
7866f6841afe35468a5cecf91e84b1add511bf3f
|
[
"PHP"
] | 5 |
PHP
|
johnnychiuchiu/blog
|
0c4863e4702243c0c85d9dfffa9feca42dd0b699
|
3b4ac675a7133a803eb30f29e80a24fa90686748
|
refs/heads/master
|
<repo_name>Webbpiraten/M7002E_Lab1<file_sep>/src/lab1/Star.java
package lab1;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
public class Star {
public Star(GL2 gl){
DrawStar(gl);
}
public void DrawStar(GL2 gl){
gl.glBegin(GL.GL_LINE_LOOP);
gl.glPushAttrib(GL2.GL_CURRENT_BIT);
gl.glColor3f(0, 1, 0);
gl.glPopAttrib();
gl.glPushMatrix();
gl.glVertex2f(-0.1f, -0.15f);
gl.glVertex2f(-0.1f, 0.1f);
gl.glVertex2f(-0.25f, 0.25f);
gl.glVertex2f(-0.05f, 0.25f);
gl.glVertex2f(0.1f, 0.50f);
gl.glVertex2f(0.25f, 0.25f);
gl.glVertex2f(0.45f, 0.25f);
gl.glVertex2f(0.25f, 0.10f);
gl.glVertex2f(0.35f, -0.15f);
gl.glVertex2f(0.1f, 0.05f);
gl.glPopMatrix();
gl.glEnd();
}
}
|
aebc9b23309014ee29e4b30450fd912ac931b1bd
|
[
"Java"
] | 1 |
Java
|
Webbpiraten/M7002E_Lab1
|
e612e630cb8adc9ac9d5b8c094a4081af49079df
|
ebc55c99df26e8c74526f78a2e9bb82fc26ecd0b
|
refs/heads/master
|
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include "xdrfile.h"
#include "math.h"
#include "time.h"
#include "Cluster_Parameters_SU5_OH.h"
#include "Cluster_Functions_SU5_OH.h"
#define Specify_Cluster_Max_Number_Search_CM 0
#define Max_Cluster_Number 1
#define All_Cluster_Number 0
#define Specify_CM_Max_Cluster_Number_Gyration_Radius 1
#define predefine_max_cluster_number 15
#define TIME 0
#define TIME_FI 200000
#define Deltar 0.001
#define Dotsnumber 2200
#define Pdf_Cutoff 2.2
#define Cluster_Atoms_Distance 0.60
#define Cluster_CM_SU5_OH_Distance 0.9
#define Boundary_Margin 0.7
void SEAL(int i);
int jacobi(int n, double a[],double u[], double eps);
int natoms,step,natom,read_return;
float time_1,prec;
//float prec;
matrix box;
rvec *x;
XDRFILE *xtc;
int cluster;
int i,j;
struct data
{
int label;
int location_x;
int location_y;
int location_z;
};
struct data array[Molnumber_SU5_OH]; /** Notice in this array, the array[0] is also used to store the data! **/
int main ()
{
long t1;
t1=clock();
char path_xtc[]="F:/GMXSimulationData/SuperComputation6202WatersRealSU5/42/traj.xtc";
xtc=xdrfile_open (path_xtc,"r");
read_xtc_natoms (path_xtc,&natoms);
x = calloc(natoms, sizeof (x[0]));
int time_initial=0; /* The starting point of our investigation depends on the real time of the .xtc file! **/
int time_statistic=TIME;
double pdistribution[2201];
for(i=0;i<=Dotsnumber;i++)
pdistribution[i]=0.00;
double All_Cluster[Molnumber_SU5_OH+1];
for(i=0;i<=Molnumber_SU5_OH;i++)
All_Cluster[i]=0.00;
while (1)
{
read_return=read_xtc (xtc,natoms,&step,&time_1,box,x,&prec);
if (read_return!=0) break;
#if 0
for (natom=1;natom<=natoms;natom++)
{
printf ("%d %f %d %f %f %f\n",step,time,natom,x[natom-1][0],x[natom-1][1],x[natom-1][2]);
}
#endif
if(time_statistic==time_initial)
{
j=-1;
for(i=0;i<=Molnumber_SU5_OH*Atomnumber_SU5_OH-1;i+=1)
{
if(i%Atomnumber_SU5_OH==0)
j++;
MOL_SU5_OH_48[j].MOL_SU5_OH_1[i%Atomnumber_SU5_OH].x=x[i][0];
MOL_SU5_OH_48[j].MOL_SU5_OH_1[i%Atomnumber_SU5_OH].y=x[i][1];
MOL_SU5_OH_48[j].MOL_SU5_OH_1[i%Atomnumber_SU5_OH].z=x[i][2];
}
j=-1;
for(i=Molnumber_SU5_OH*Atomnumber_SU5_OH;i<=Molnumber_SU5_OH*Atomnumber_SU5_OH+3*Molnumber_SOL-1;i+=1)
{
if((i-Molnumber_SU5_OH*Atomnumber_SU5_OH)%3==0)
j++;
MOL_SOL_3559[j].MOL_SOL_1[(i-Molnumber_SU5_OH*Atomnumber_SU5_OH)%3].x=x[i][0];
MOL_SOL_3559[j].MOL_SOL_1[(i-Molnumber_SU5_OH*Atomnumber_SU5_OH)%3].y=x[i][1];
MOL_SOL_3559[j].MOL_SOL_1[(i-Molnumber_SU5_OH*Atomnumber_SU5_OH)%3].z=x[i][2];
}
for(i=0;i<=Molnumber_SU5_OH-1;i++)
{
array[i].label=0;
array[i].location_x=0;
array[i].location_y=0;
array[i].location_z=0;
}
/** For the convienience of Computation ***
** we define the CM matrix explicitly ***
** We must to ensure the GMX will set ***
** the molecules in the same way that ***
** keeping the molecules with an entity ***
** ! ***
**/
Position CM_Of_SU5_OH[Molnumber_SU5_OH];
for(i=0;i<=Molnumber_SU5_OH-1;i++)
{
CM_Of_SU5_OH[i].x=CM_SU5_OH_X(&(MOL_SU5_OH_48[i].MOL_SU5_OH_1[0]));
CM_Of_SU5_OH[i].y=CM_SU5_OH_Y(&(MOL_SU5_OH_48[i].MOL_SU5_OH_1[0]));
CM_Of_SU5_OH[i].z=CM_SU5_OH_Z(&(MOL_SU5_OH_48[i].MOL_SU5_OH_1[0]));
}
Position CM_Of_SOL[Molnumber_SOL];
for(i=0;i<=Molnumber_SOL-1;i++)
{
CM_Of_SOL[i].x=CM_SOL_X(&(MOL_SOL_3559[i].MOL_SOL_1[0]));
CM_Of_SOL[i].y=CM_SOL_Y(&(MOL_SOL_3559[i].MOL_SOL_1[0]));
CM_Of_SOL[i].z=CM_SOL_Z(&(MOL_SOL_3559[i].MOL_SOL_1[0]));
}
/** In order to compute the radius of the Max_Cluster_Number, **
** we must first to translate all the CM of the molecules into **
** the central box! **
** The symbol "CM" refers to the center of molecules consisting **
** of the atoms with same mass rather the weighted atoms! **
**/
for(i=0;i<=Molnumber_SU5_OH-1;i++)
{
if(CM_Of_SU5_OH[i].x>box[0][0])
{
CM_Of_SU5_OH[i].x -= box[0][0];
for(j=0;j<=Atomnumber_SU5_OH-1;j++)
MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].x -= box[0][0];
}
if(CM_Of_SU5_OH[i].x<box[0][0])
{
CM_Of_SU5_OH[i].x += box[0][0];
for(j=0;j<=Atomnumber_SU5_OH-1;j++)
MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].x += box[0][0];
}
if(CM_Of_SU5_OH[i].y>box[1][1])
{
CM_Of_SU5_OH[i].y -= box[1][1];
for(j=0;j<=Atomnumber_SU5_OH-1;j++)
MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].y -= box[1][1];
}
if(CM_Of_SU5_OH[i].y<box[1][1])
{
CM_Of_SU5_OH[i].y += box[1][1];
for(j=0;j<=Atomnumber_SU5_OH-1;j++)
MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].y += box[1][1];
}
if(CM_Of_SU5_OH[i].z>box[2][2])
{
CM_Of_SU5_OH[i].z -= box[2][2];
for(j=0;j<=Atomnumber_SU5_OH-1;j++)
MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].z -= box[2][2];
}
if(CM_Of_SU5_OH[i].z<box[2][2])
{
CM_Of_SU5_OH[i].z += box[2][2];
for(j=0;j<=Atomnumber_SU5_OH-1;j++)
MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].z += box[2][2];
}
}
/** Finishing the translation! **
**/
cluster=0;
for(j=0;j<=Molnumber_SU5_OH-1;j++)
{
if(array[j].label==0) /***To prevent the repeated labeling******/
{
cluster++;
SEAL(j);
}
}
/** End of the Cluster Labeling **/
#if 0
for(i=0;i<=Molnumber_SU5_OH-1;i++)
printf(" 1SU5 A %5d%8.3f%8.3f%8.3f\n",i+1,CM_Of_SU5_OH[i].x,CM_Of_SU5_OH[i].y,CM_Of_SU5_OH[i].z);
printf(" %8.3f %8.3f %8.3f\n", box[0][0], box[1][1], box[2][2]);
#endif
#if Max_Cluster_Number
int Recording_Cluster[Molnumber_SU5_OH+1];
int Recording_Label; /** This number can tell us which label corresponds to the max Cluster Number! **/
for(i=0;i<=Molnumber_SU5_OH;i++)
Recording_Cluster[i]=0;
for(i=0;i<=Molnumber_SU5_OH-1;i++)
Recording_Cluster[array[i].label]++;
int max=1;
for(i=0;i<=Molnumber_SU5_OH;i++)
{
if(Recording_Cluster[i]>=max)
{
max=Recording_Cluster[i];
Recording_Label=i;
}
}
//printf("%d %d\n",time_statistic, max);
#endif
#if Specify_CM_Max_Cluster_Number_Gyration_Radius
//if(max==predefine_max_cluster_number)
//{
Position Center_Of_Cluster,Center_Of_Tails,Center_Of_Heads;
Center_Of_Cluster.x=0.00; Center_Of_Cluster.y=0.00; Center_Of_Cluster.z=0.00;
Center_Of_Tails.x=0.00; Center_Of_Tails.y=0.00; Center_Of_Tails.z=0.00;
Center_Of_Heads.x=0.00; Center_Of_Heads.y=0.00; Center_Of_Heads.z=0.00;
Position CG_Of_SU5_OH[Molnumber_SU5_OH], CG_Of_Tails[Molnumber_SU5_OH], CG_Of_Heads[Molnumber_SU5_OH];
for(i=0;i<=Molnumber_SU5_OH-1;i++)
{
CG_Of_SU5_OH[i].x=0.00; CG_Of_SU5_OH[i].y=0.00; CG_Of_SU5_OH[i].z=0.00;
CG_Of_Tails[i].x=0.00; CG_Of_Tails[i].y=0.00; CG_Of_Tails[i].z=0.00;
CG_Of_Heads[i].x=0.00; CG_Of_Heads[i].y=0.00; CG_Of_Heads[i].z=0.00;
}
/** We must first to translate all the relative **
** molecules into a unified form. **
**/
for(i=0;i<=Molnumber_SU5_OH-1;i++)
{
if(array[i].label==Recording_Label)
{
for(j=0;j<=Atomnumber_SU5_OH-1;j++)
{
MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].x += array[i].location_x*box[0][0];
MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].y += array[i].location_y*box[1][1];
MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].z += array[i].location_z*box[2][2];
Center_Of_Cluster.x += MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].x;
Center_Of_Cluster.y += MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].y;
Center_Of_Cluster.z += MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].z;
CG_Of_SU5_OH[i].x += MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].x;
CG_Of_SU5_OH[i].y += MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].y;
CG_Of_SU5_OH[i].z += MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].z;
/** We can also calculate the CG_Of_Tails[] or **
** CG_Of_Heads[]! **
**/
if(j<=3)
{
Center_Of_Tails.x += MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].x;
Center_Of_Tails.y += MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].y;
Center_Of_Tails.z += MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].z;
CG_Of_Tails[i].x += MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].x;
CG_Of_Tails[i].y += MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].y;
CG_Of_Tails[i].z += MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].z;
}
if((j>=4)&&(j<=6))
{
Center_Of_Heads.x += MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].x;
Center_Of_Heads.y += MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].y;
Center_Of_Heads.z += MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].z;
CG_Of_Heads[i].x += MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].x;
CG_Of_Heads[i].y += MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].y;
CG_Of_Heads[i].z += MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].z;
}
}
CG_Of_SU5_OH[i].x /= Atomnumber_SU5_OH;
CG_Of_SU5_OH[i].y /= Atomnumber_SU5_OH;
CG_Of_SU5_OH[i].z /= Atomnumber_SU5_OH;
CG_Of_Tails[i].x /= 4;
CG_Of_Tails[i].y /= 4;
CG_Of_Tails[i].z /= 4;
CG_Of_Heads[i].x /= 3;
CG_Of_Heads[i].y /= 3;
CG_Of_Heads[i].z /= 3;
}
}
/** End of the easy translation! **
**/
/** We can now calculate the CM of the Cluster! **
**/
Center_Of_Cluster.x /= max*Atomnumber_SU5_OH;
Center_Of_Cluster.y /= max*Atomnumber_SU5_OH;
Center_Of_Cluster.z /= max*Atomnumber_SU5_OH;
Center_Of_Tails.x /= max*4;
Center_Of_Tails.y /= max*4;
Center_Of_Tails.z /= max*4;
Center_Of_Heads.x /= max*3;
Center_Of_Heads.y /= max*3;
Center_Of_Heads.z /= max*3;
/** In order to compute the CG of Tails and **
** Heads, we newly create the 2 array! **
** These two arrays are the copies of the **
** MOL_SU5_OH_48[].MOL_SU5_OH_1[]... **
**/
double Tails[Molnumber_SU5_OH][Atomnumber_SU5_OH][3], Heads[Molnumber_SU5_OH][Atomnumber_SU5_OH][3];
for(i=0;i<=Molnumber_SU5_OH-1;i++)
{
for(j=0;j<=Atomnumber_SU5_OH-1;j++)
{
Tails[i][j][0]=MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].x;
Tails[i][j][1]=MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].y;
Tails[i][j][2]=MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].z;
Heads[i][j][0]=MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].x;
Heads[i][j][1]=MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].y;
Heads[i][j][2]=MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].z;
}
}
for(i=0;i<=Molnumber_SU5_OH-1;i++)
{
if(array[i].label==Recording_Label)
{
/** The CG of the molecules, Tails and **
** Heads have been subjected to the **
** translations! **
**/
CG_Of_SU5_OH[i].x -= Center_Of_Cluster.x;
CG_Of_SU5_OH[i].y -= Center_Of_Cluster.y;
CG_Of_SU5_OH[i].z -= Center_Of_Cluster.z;
CG_Of_Tails[i].x -= Center_Of_Tails.x;
CG_Of_Tails[i].y -= Center_Of_Tails.y;
CG_Of_Tails[i].z -= Center_Of_Tails.z;
CG_Of_Heads[i].x -= Center_Of_Heads.x;
CG_Of_Heads[i].y -= Center_Of_Heads.y;
CG_Of_Heads[i].z -= Center_Of_Heads.z;
for(j=0;j<=Atomnumber_SU5_OH-1;j++)
{
MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].x -= Center_Of_Cluster.x;
MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].y -= Center_Of_Cluster.y;
MOL_SU5_OH_48[i].MOL_SU5_OH_1[j].z -= Center_Of_Cluster.z;
Tails[i][j][0] -= Center_Of_Tails.x;
Tails[i][j][1] -= Center_Of_Tails.y;
Tails[i][j][2] -= Center_Of_Tails.z;
Heads[i][j][0] -= Center_Of_Heads.x;
Heads[i][j][1] -= Center_Of_Heads.y;
Heads[i][j][2] -= Center_Of_Heads.z;
}
}
}
#if 0
printf("This is a gro file!\n");
printf("%d\n",max);
j=0;
for(i=0;i<=Molnumber_SU5_OH-1;i++)
{
if(array[i].label==Recording_Label)
{
j++;
printf(" 1SU5 A %5d%8.3f%8.3f%8.3f\n",j,CG_Of_SU5_OH[i].x,CG_Of_SU5_OH[i].y,CG_Of_SU5_OH[i].z);
}
}
printf(" %8.3f %8.3f %8.3f\n", box[0][0], box[1][1], box[2][2]);
#endif
#if 0
double TEMP_CENTER[3];
for(j=0;j<=2;j++)
TEMP_CENTER[j]=0.00;
TEMP_CENTER[0]=Center_Of_Cluster.x;
TEMP_CENTER[1]=Center_Of_Cluster.y;
TEMP_CENTER[2]=Center_Of_Cluster.z;
#endif
//printf("%d %lf %lf %lf\n",time_statistic, Center_Of_Cluster.x, Center_Of_Cluster.y, Center_Of_Cluster.z);
double Gyration[3][3],Gyration_Tails[3][3],Gyration_Heads[3][3];
for(i=0;i<=2;i++)
for(j=0;j<=2;j++)
{
Gyration[i][j]=0.00;
Gyration_Tails[i][j]=0.00;
Gyration_Heads[i][j]=0.00;
}
/** For the convienience of computation, we **
** store the labels.x, .y, .z into the **
** matrix! **
**/
int var_1,var_2;
double TEMP_MOL[Molnumber_SU5_OH][Atomnumber_SU5_OH][3];
for(var_1=0;var_1<=Molnumber_SU5_OH-1;var_1++)
{
for(var_2=0;var_2<=Atomnumber_SU5_OH-1;var_2++)
{
TEMP_MOL[var_1][var_2][0]=MOL_SU5_OH_48[var_1].MOL_SU5_OH_1[var_2].x;
TEMP_MOL[var_1][var_2][1]=MOL_SU5_OH_48[var_1].MOL_SU5_OH_1[var_2].y;
TEMP_MOL[var_1][var_2][2]=MOL_SU5_OH_48[var_1].MOL_SU5_OH_1[var_2].z;
}
}
for(i=0;i<=2;i++)
{
for(j=0;j<=2;j++)
{
for(var_1=0;var_1<=Molnumber_SU5_OH-1;var_1++)
{
if(array[var_1].label==Recording_Label)
{
/** Calculation of the whole molecule ! **
**/
for(var_2=0;var_2<=Atomnumber_SU5_OH-1;var_2++)
{
Gyration[i][j] += (TEMP_MOL[var_1][var_2][i])*(TEMP_MOL[var_1][var_2][j]);
/** Tails are from 0 to 3 ! **
**/
if(var_2<=3)
Gyration_Tails[i][j] += Tails[var_1][var_2][i]*Tails[var_1][var_2][j];
/** Heads are from 4 to 6 ! **
**/
if(var_2>=4)
Gyration_Heads[i][j] += Heads[var_1][var_2][i]*Heads[var_1][var_2][j];
}
}
}
Gyration[i][j] /= max*Atomnumber_SU5_OH;
Gyration_Tails[i][j] /= max*4.0;
Gyration_Heads[i][j] /= max*3.0;
}
}
/** The codes below are cited from a professional **
** programming book! It is designed specially to **
** digonalizing a matrix of which for our aim is **
** named Gyration[i][j]! **
**/
double vv[3][3],vv_tail[3][3], vv_head[3][3];
double eps=0.000001;
int calnumber,calnumber_Tails,calnumber_Heads;
calnumber=jacobi(3,&Gyration[0][0],&vv[0][0],eps);
calnumber_Tails=jacobi(3,&Gyration_Tails[0][0],&vv_tail[0][0],eps);
calnumber_Heads=jacobi(3,&Gyration_Heads[0][0],&vv_head[0][0],eps);
//printf("%d %d %d\n", calnumber, calnumber_Tails, calnumber_Heads);
if((calnumber<10000)&&(calnumber_Tails<10000)&&(calnumber_Heads<10000))
{
int s1,s2;
double temp=0.00;
for(s1=0;s1<=1;s1++)
{
if(Gyration[s1+1][s1+1]<Gyration[s1][s1])
{
temp=Gyration[s1][s1];
Gyration[s1][s1]=Gyration[s1+1][s1+1];
Gyration[s1+1][s1+1]=temp;
}
}
if(Gyration[0][0]>Gyration[1][1])
{
temp=Gyration[0][0];
Gyration[0][0]=Gyration[1][1];
Gyration[1][1]=temp;
}
double asphericity=0.00,acylindricity=0.00,eccentricity=0.00,alpha=0.00,belta=0.00,kai=0.00;
asphericity=Gyration[2][2]-0.5*(Gyration[1][1]+Gyration[0][0]);
acylindricity=Gyration[1][1]-Gyration[0][0];
eccentricity=1-(sqrt(Gyration[0][0])/sqrt((Gyration[0][0]+Gyration[1][1]+Gyration[2][2])*0.3333));
kai=(asphericity*asphericity+0.75*acylindricity*acylindricity)/pow((Gyration[0][0]+Gyration[1][1]+Gyration[2][2]),2);
//alpha=Gyration[1][1]/Gyration[2][2];
//belta=Gyration[0][0]/Gyration[2][2];
//printf("%d %lf %lf %lf %lf %lf %lf\n",time_statistic, sqrt(Gyration[0][0]+Gyration[1][1]+Gyration[2][2]),alpha,belta,eccentricity,asphericity, acylindricity);
//printf("%d %d %lf %lf %lf %lf\n",time_statistic, max, sqrt(Gyration[0][0]+Gyration[1][1]+Gyration[2][2]),eccentricity,asphericity, acylindricity);
for(s1=0;s1<=1;s1++)
{
if(Gyration_Tails[s1+1][s1+1]<Gyration_Tails[s1][s1])
{
temp=Gyration_Tails[s1][s1];
Gyration_Tails[s1][s1]=Gyration_Tails[s1+1][s1+1];
Gyration_Tails[s1+1][s1+1]=temp;
}
}
if(Gyration_Tails[0][0]>Gyration_Tails[1][1])
{
temp=Gyration_Tails[0][0];
Gyration_Tails[0][0]=Gyration_Tails[1][1];
Gyration_Tails[1][1]=temp;
}
for(s1=0;s1<=1;s1++)
{
if(Gyration_Heads[s1+1][s1+1]<Gyration_Heads[s1][s1])
{
temp=Gyration_Heads[s1][s1];
Gyration_Heads[s1][s1]=Gyration_Heads[s1+1][s1+1];
Gyration_Heads[s1+1][s1+1]=temp;
}
}
if(Gyration_Heads[0][0]>Gyration_Heads[1][1])
{
temp=Gyration_Heads[0][0];
Gyration_Heads[0][0]=Gyration_Heads[1][1];
Gyration_Heads[1][1]=temp;
}
printf("%d %d %lf %lf %lf %lf %lf\n",time_statistic, max, sqrt(Gyration[0][0]+Gyration[1][1]+Gyration[2][2]),sqrt(Gyration_Tails[0][0]+Gyration_Tails[1][1]+Gyration_Tails[2][2]), sqrt(Gyration_Heads[0][0]+Gyration_Heads[1][1]+Gyration_Heads[2][2]),kai, asphericity);
}
//}
/** End of the predefine_max_cluster_number
**/
#endif
#if All_Cluster_Number
int Recording_Cluster[Molnumber_SU5_OH+1]; /** The label begins from 1 ! **/
int Recording_Label; /** This number can tell us which label corresponds to the max Cluster Number! **/
for(i=0;i<=Molnumber_SU5_OH;i++)
Recording_Cluster[i]=0;
for(i=0;i<=Molnumber_SU5_OH-1;i++)
Recording_Cluster[array[i].label]++;
for(i=0;i<=Molnumber_SU5_OH;i++)
{
if(Recording_Cluster[i]!=0)
All_Cluster[Recording_Cluster[i]]++;
}
#endif
/** Here is the end of the labeling! **/
time_statistic++;
if(time_statistic==TIME_FI+1)
break;
} /** End of the time_statistic ***/
time_initial++;
} /** End of the loops ***/
#if All_Cluster_Number
for(i=0;i<=Molnumber_SU5_OH;i++)
{
if(All_Cluster[i]!=0)
printf("%d %f\n",i,All_Cluster[i]/((double)(TIME_FI-TIME)));
}
#endif
xdrfile_close (xtc);
free(x);
//getchar();
long t2;
t2=clock();
printf("%d\n",t2-t1);
return 0;
} /** End of the main() ***/
/****The sub-code below is the coral codes for labeling********/
void SEAL( int s)
{
array[s].label=cluster;
int neighbour[Molnumber_SU5_OH];
for(i=0;i<=Molnumber_SU5_OH-1;i++)
neighbour[i]=-1;
int u=0;
int t_1;
Position TEMP_1[Atomnumber_SU5_OH];
for(t_1=0;t_1<=Atomnumber_SU5_OH-1;t_1++)
{
TEMP_1[t_1].x=MOL_SU5_OH_48[s].MOL_SU5_OH_1[t_1].x+array[s].location_x*box[0][0];
TEMP_1[t_1].y=MOL_SU5_OH_48[s].MOL_SU5_OH_1[t_1].y+array[s].location_y*box[1][1];
TEMP_1[t_1].z=MOL_SU5_OH_48[s].MOL_SU5_OH_1[t_1].z+array[s].location_z*box[2][2];
}
for(i=0;i<=Molnumber_SU5_OH-1;i++) /****We try to judge whether the molecules can be relative to objetive atom*****/
{
if(i==s)
continue;
else
{
int px;
int py;
int pz;
int PX;
int PY;
int PZ;
double Dis=20.0;
int v1,v2;
for(v1=0;v1<=3;v1++)
{
for(v2=0;v2<=3;v2++)
{
for(px=-1;px<=1;px++) /****We must take the peoredical boxes into considerations******/
{
for(py=-1;py<=1;py++)
{
for(pz=-1;pz<=1;pz++)
{
if(distance(TEMP_1[v1].x,TEMP_1[v1].y,TEMP_1[v1].z,MOL_SU5_OH_48[i].MOL_SU5_OH_1[v2].x+px*box[0][0],MOL_SU5_OH_48[i].MOL_SU5_OH_1[v2].y+py*box[1][1],MOL_SU5_OH_48[i].MOL_SU5_OH_1[v2].z+pz*box[2][2])<=Dis)
{
Dis=distance(MOL_SU5_OH_48[s].MOL_SU5_OH_1[v1].x,MOL_SU5_OH_48[s].MOL_SU5_OH_1[v1].y,MOL_SU5_OH_48[s].MOL_SU5_OH_1[v1].z,MOL_SU5_OH_48[i].MOL_SU5_OH_1[v2].x+px*box[0][0],MOL_SU5_OH_48[i].MOL_SU5_OH_1[v2].y+py*box[1][1],MOL_SU5_OH_48[i].MOL_SU5_OH_1[v2].z+pz*box[2][2]);
PX=px;
PY=py;
PZ=pz;
}
}
}
}
}
}
if((Dis<=Cluster_Atoms_Distance)&&(array[i].label==0))
/****The condition at the last can ensure the finity of loops. And it is very important!**************/
{
array[i].location_x=PX;
array[i].location_y=PY;
array[i].location_z=PZ;
neighbour[u]=i;
array[i].label=cluster;
u++;
}
}
}
int k;
for(k=0;k<=Molnumber_SU5_OH-1;k++)
{
if(array[neighbour[k]].label==-1)
break;
if(array[neighbour[k]].label==cluster)
SEAL(neighbour[k]);
}
}
|
751c77b824a225b249ec59feb3599776a9c44f40
|
[
"C"
] | 1 |
C
|
zhaoliangfly/Gyration_of_Cluster
|
4e5459cc4511ecc78bfc82cc3dcf0073b4e5a64f
|
6cdd23261b0bb5feffff4f935cc2c6e4daf5e9ed
|
refs/heads/master
|
<repo_name>GATAKAWAKACHICO/quiz-view<file_sep>/static.js
var socket_url = 'http://192.168.127.12:4649';
<file_sep>/README.md
# Getting started (Ubuntu)
```bash
$ sudo apt-get update
$ sudo apt-get -y install git
$ sudo apt-get -y install apache2
$ cd /var/www/html
$ sudo git clone https://github.com/GATAKAWAKACHICO/quiz-view.git
$ cd quiz-view
```
```bash
$ vim static.js
```
Change your IP or Hostname, Do not change port.
```js
var socket_url = 'http://xxxx:4649';
```
```bash
$ sudo chown ubuntu:ubuntu quizlist.csv
$ sudo apt-get install vsftpd
```
# if you need ftp
```bash
$ sudo apt-get update
```
<file_sep>/quizinfo.rb
# coding: utf-8
ip = ARGV[0]
pw = ARGV[1]
quiz_info = "IP: #{ip}\n"
quiz_info += "http://#{ip}/quiz-view/admin/admin.html\n"
quiz_info += "http://#{ip}/quiz-view/admin/quiz.html\n"
quiz_info += "http://#{ip}/quiz-view/admin/worst10.html\n"
quiz_info += "http://#{ip}/quiz-view/admin/best10.html\n"
quiz_info += "http://#{ip}/quiz-view/quizlist.csv\n"
quiz_info += "http://#{ip}/quiz-view/guest.html\n"
quiz_info += "Password: #{<PASSWORD>"
quiz_info += "/var/www/html/quiz-viewにFTPでquizlist.csv(問題データ)をアップ"
puts quiz_info
<file_sep>/worker.js
onmessage = function(socket) {
socket.emit('chat message', {"admin":false, "type":"answered", "name" : Math.random().toString(36).slice(-8), "answer" : Math.floor( Math.random() * (4 - 1 + 1) ) + 1, "time": Math.random()*10 } );
console.log("send");
}
|
ebb03969e48b23884607d5c4f1e3a660f66002e4
|
[
"JavaScript",
"Ruby",
"Markdown"
] | 4 |
JavaScript
|
GATAKAWAKACHICO/quiz-view
|
e70d1257685d42e8a9ca5e9228619b37bcc92732
|
9f58bad7939e71f1c3500a8a5792953b385da616
|
refs/heads/main
|
<repo_name>aj910/kanban-fire<file_sep>/src/environments/environment.prod.ts
export const environment = {
production: true,
firebase: {
apiKey: "<KEY>",
authDomain: "kanbanfire-3e3ed.firebaseapp.com",
projectId: "kanbanfire-3e3ed",
storageBucket: "kanbanfire-3e3ed.appspot.com",
messagingSenderId: "600529840060",
appId: "1:600529840060:web:6e30dac03e0a9b840d2db9",
measurementId: "G-7WYSKN9S2M"
}
};
|
6b9e0c2ef49133ba9a90f8270b370c50de03eebe
|
[
"TypeScript"
] | 1 |
TypeScript
|
aj910/kanban-fire
|
e0533a2f08c5d158694292fcc41848d5621c502a
|
050e217cd9297f37c140bd64409799e3af9d24ea
|
refs/heads/master
|
<repo_name>Inedo/inedo-wordpresscicd<file_sep>/index.php
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<title><?php bloginfo( 'name' ); ?></title>
<?php wp_head() ?>
</head>
<body <?php body_class(); ?>>
<h1>Inedo Custom Theme Example</h1>
<?php
if ( have_posts() ) :
while ( have_posts() ) : the_post(); ?>
<h2><?php the_title() ?></h2>
<?php the_content() ?>
<?php endwhile;
else :
echo '<p>There are no posts!</p>';
endif;
?>
</body><file_sep>/README.md
# WordPress Sample Theme
A small, simple WordPress theme used for DevOps training and workshops.
|
39f039e699bd1464be8422e756fad955432e9d50
|
[
"Markdown",
"PHP"
] | 2 |
PHP
|
Inedo/inedo-wordpresscicd
|
692ca4f0da3208e0fe0087c1171d71abde1a5e3d
|
6569dff8634d06893b12ae78780c7cfdc59b806d
|
refs/heads/master
|
<file_sep>Code in this directory is based on work from the course [Learn React for free](https://scrimba.com/playlist/p7P5Hd) on Scrimba.
<file_sep>import React from "react"
function Footer(){
return(
<footer>My Awesome Website 2019</footer>
)
}
export default Footer<file_sep>import React from "react"
function MainComponent(){
return(
<main>
<h2>To do:</h2>
<ul id="to-do-list">
<li><input type="checkbox"/> Eat breakfast</li>
<li><input type="checkbox"/> Make the bed</li>
<li><input type="checkbox"/> Conquer the world</li>
</ul>
</main>
)
}
export default MainComponent<file_sep># scrimba
Code from courses on Scrimba
|
c40fb8de8ed9d325a080b3052bc0b11615d3d361
|
[
"Markdown",
"JavaScript"
] | 4 |
Markdown
|
PollockCR/scrimba
|
7f277b892e4eefd7ea7fba333331f6ee53c32a52
|
b0f788f44594607823b5e1b61e29f35acb748d14
|
refs/heads/master
|
<file_sep>package main
import (
"encoding/json"
"fmt"
"net/http"
"realtime-chat/services"
"github.com/gorilla/websocket"
uuid "github.com/satori/go.uuid"
)
var appName = "Message Service"
func main() {
fmt.Printf("Starting %v\n", appName)
startWebServer()
startKafkaClient()
}
func WSPage(res http.ResponseWriter, req *http.Request) {
conn, error := (&websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }}).Upgrade(res, req, nil)
if error != nil {
http.NotFound(res, req)
return
}
client := &services.Client{
Id: uuid.Must(uuid.NewV4(), error).String(),
Socket: conn,
Send: make(chan []byte)}
services.Manager.Register(client)
go client.Read()
go client.Write()
}
func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
// A very simple health check.
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
// In the future we could report back on the status of our DB, or our cache and include them in the response.
response := `{alive: true}`
data, _ := json.Marshal(response)
w.Write(data)
}
func startWebServer() {
services.Manager = &services.WebSocketClientManager{
BroadcastChannel: make(chan []byte),
RegisterChannel: make(chan *services.Client),
UnregisterChannel: make(chan *services.Client),
Clients: make(map[*services.Client]bool),
}
go services.Manager.Start()
http.HandleFunc("/ws", WSPage)
http.HandleFunc("/health-check", healthCheckHandler)
http.ListenAndServe(":12345", nil)
}
func startKafkaClient() {
services.Kafka = services.KafkaClient{
Topic: "messages",
}
go services.Kafka.ConsumeTopic(true, 10000000)
}
<file_sep># MessageSocketSevice
The MessageSocketService microservice provides a single websocket endpoint:
- localhost:12345
A new *Client* object is created to track every browser connection and these are registered with the *ClientManager* object.
Clients will listen for incoming messages and pass them to the ClientManager, which broadcasts them out to all resgistered clients for display.
Messages are also put onto a Kafka queue for dispersal to other application instances.
We listen for incoming messages on the same kafka queue and give them to the ClientManager to broadcast to our registered clients.
Messages are tagged with a unique location code, so we can discard messages that originate locally that we've already broadcast.
## Prerequisites
Install Golang as per the install instructions here: https://golang.org/doc/install
## Running the code
Clone the project and make sure its part of the $GOPATH
From the command line run *go run main.go*
You should see a confirmation message that the service is up and running
<file_sep>package main
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"realtime-chat/model"
"realtime-chat/services"
"strings"
"testing"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{}
func TestSimpleSendReceiveSingleClient(t *testing.T) {
services.Manager = &services.WebSocketClientManager{
BroadcastChannel: make(chan []byte),
RegisterChannel: make(chan *services.Client),
UnregisterChannel: make(chan *services.Client),
Clients: make(map[*services.Client]bool),
}
go services.Manager.Start()
// Create test server with the echo handler.
s := httptest.NewServer(http.HandlerFunc(WSPage))
defer s.Close()
// Convert http://127.0.0.1 to ws://127.0.0.
u := "ws" + strings.TrimPrefix(s.URL, "http")
// Connect to the server
ws, _, err := websocket.DefaultDialer.Dial(u, nil)
if err != nil {
t.Fatalf("%v", err)
}
defer ws.Close()
// Send message to server, read response and check to see if it's what we expect.
for i := 0; i < 10; i++ {
if err := ws.WriteMessage(websocket.TextMessage, []byte("hello")); err != nil {
t.Fatalf("%v", err)
}
_, p, err := ws.ReadMessage()
if err != nil {
t.Fatalf("%v", err)
}
var message model.Message
err = json.Unmarshal(p, &message)
fmt.Printf("%+v", message)
expectedMessage := model.Message{
Id: "",
Sender: "",
Recipient: "",
Content: "hello",
SourceLocation: "",
}
if message != expectedMessage {
t.Fatalf("bad message")
}
}
}
func TestSimpleSendReceiveMultipleClient(t *testing.T) {
services.Manager = &services.WebSocketClientManager{
BroadcastChannel: make(chan []byte),
RegisterChannel: make(chan *services.Client),
UnregisterChannel: make(chan *services.Client),
Clients: make(map[*services.Client]bool),
}
go services.Manager.Start()
// Create test server with the echo handler.
s := httptest.NewServer(http.HandlerFunc(WSPage))
defer s.Close()
// Convert http://127.0.0.1 to ws://127.0.0.
u := "ws" + strings.TrimPrefix(s.URL, "http")
// Connect Client one to the server
wsOne, _, err := websocket.DefaultDialer.Dial(u, nil)
if err != nil {
t.Fatalf("%v", err)
}
defer wsOne.Close()
// Connect client two to the server
wsTwo, _, err := websocket.DefaultDialer.Dial(u, nil)
if err != nil {
t.Fatalf("%v", err)
}
defer wsTwo.Close()
//-- check that client one is notified of the new user
_, p, err := wsOne.ReadMessage()
if err != nil {
t.Fatalf("%v", err)
}
expectedMessage := model.Message{
Id: "",
Sender: "",
Recipient: "",
Content: "/A new user has connected.",
SourceLocation: "",
}
if !compare(p, expectedMessage) {
t.Fatalf("Incorrect message. Expected %v, got %v", expectedMessage, p)
}
// Send messages to the server from client one, test that both client one and client two get the messages
for i := 0; i < 10; i++ {
if err := wsOne.WriteMessage(websocket.TextMessage, []byte("hello")); err != nil {
t.Fatalf("%v", err)
}
expectedMessage := model.Message{
Id: "",
Sender: "",
Recipient: "",
Content: "hello",
SourceLocation: "",
}
_, clientTwoMsg, err := wsTwo.ReadMessage()
if err != nil {
t.Fatalf("%v", err)
}
if !compare(clientTwoMsg, expectedMessage) {
t.Fatalf("Incorrect message. Expected %v, got %v", expectedMessage, clientTwoMsg)
}
_, clientOneMsg, err := wsOne.ReadMessage()
if err != nil {
t.Fatalf("%v", err)
}
if !compare(clientOneMsg, expectedMessage) {
t.Fatalf("Incorrect message. Expected %v, got %v", expectedMessage, clientOneMsg)
}
}
//-- disconnect client two
wsTwo.Close()
//-- check that client one is notified of user leaving
_, p, err = wsOne.ReadMessage()
if err != nil {
t.Fatalf("%v", err)
}
expectedMessage = model.Message{
Id: "",
Sender: "",
Recipient: "",
Content: "/A user has disconnected.",
SourceLocation: "",
}
if !compare(p, expectedMessage) {
t.Fatalf("Incorrect message. Expected %v, got %v", expectedMessage, p)
}
}
func compare(incomingMessage []byte, expectedMessage model.Message) bool {
var message model.Message
_ = json.Unmarshal(incomingMessage, &message)
fmt.Printf("%+v", message)
return message == expectedMessage
}
<file_sep># consignment-service/Dockerfile
# We use the official golang image, which contains all the
# correct build tools and libraries. Notice `as builder`,
# this gives this container a name that we can reference later on.
#FROM golang:1.10.3-alpine as builder
FROM golang:1.9 as builder
ENV LIBRDKAFKA_VERSION 1.0.0
#RUN apt-get -y update \
# && apt-get install -y --no-install-recommends upx-ucl zip \
# && apt-get clean \
# && rm -rf /var/lib/apt/lists/*
#RUN curl -Lk -o /root/librdkafka-${LIBRDKAFKA_VERSION}.tar.gz https://github.com/edenhill/librdkafka/archive/v${LIBRDKAFKA_VERSION}.tar.gz && \
# tar -xzf /root/librdkafka-${LIBRDKAFKA_VERSION}.tar.gz -C /root && \
# cd /root/librdkafka-${LIBRDKAFKA_VERSION} && \
# ./configure --prefix /usr && make && make install && make clean && ./configure --clean
# Set our workdir to our current service in the gopath
WORKDIR /go/src/realtime-chat
# Copy the current code into our workdir
COPY . .
# Here we're pulling in godep, which is a dependency manager tool,
# we're going to use dep instead of go get, to get around a few
# quirks in how go get works with sub-packages.
# Download and install the latest release of dep
ADD https://github.com/golang/dep/releases/download/v0.4.1/dep-linux-amd64 /usr/bin/dep
RUN chmod +x /usr/bin/dep
# Create a dep project, and run `ensure`, which will pull in all
# of the dependencies within this directory.
RUN dep init && dep ensure
# Build the binary, with a few flags which will allow
# us to run this binary in Alpine.
#RUN GOOS=linux GOARCH=amd64 go build
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo .
FROM alpine:latest
EXPOSE 12345
# Security related package, good to have.
RUN apk --no-cache add ca-certificates
# Same as before, create a directory for our app.
RUN mkdir /app
WORKDIR /app
# Here, instead of copying the binary from our host machine,
# we pull the binary from the container named `builder`, within
# this build context. This reaches into our previous image, finds
# the binary we built, and pulls it into this container. Amazing!
COPY --from=builder /go/src/realtime-chat .
CMD "./realtime-chat"<file_sep>package test
import (
"encoding/json"
"fmt"
"realtime-chat/model"
"realtime-chat/services"
"strconv"
"testing"
"time"
)
type MockClientManager struct {
messages []model.Message
}
func (m *MockClientManager) Broadcast(message []byte) {
model := model.Message{}
json.Unmarshal(message, &model)
m.messages = append(m.messages, model)
fmt.Printf("Broadcast called %v", model)
}
func (m *MockClientManager) Start() {
fmt.Println("Start called")
}
func (m *MockClientManager) Unregister(c *services.Client) {
fmt.Println("Unregister called")
}
func (m *MockClientManager) Register(c *services.Client) {
fmt.Println("Register called")
}
/*
Test that when we send (produce) a message to Kafka we receive (consume) the message with the correct content
*/
func TestConsumingMessageCorrectContentReturned(t *testing.T) {
mockClientManager := &MockClientManager{
messages: make([]model.Message, 0),
}
services.Manager = mockClientManager
services.Kafka = services.KafkaClient{
Topic: "test",
}
message := model.Message{
Content: strconv.FormatInt(time.Now().UnixNano(), 10),
}
services.Kafka.SendMessage(message)
//-- test that we get the correct content
services.Kafka.ConsumeTopic(false, 1)
if mockClientManager.messages[0].Content != message.Content {
t.Errorf("Unexpected message! Got %v want %v", message.Content, mockClientManager.messages[0].Content)
}
}
/*
Tests that messages sent from the local location are not re-broadcast when they're consumed from Kafka.
Messages that come through the local instance are automatically broadcast to attached web sockets before being published to Kafka
If we pick up messages that we've already sent, then the users will see duplicates
*/
func TestConsumingMessageSourceMessagesIgnored(t *testing.T) {
mockClientManager := &MockClientManager{}
services.Manager = mockClientManager
services.Kafka = services.KafkaClient{
Topic: "test",
}
message := model.Message{
Content: strconv.FormatInt(time.Now().UnixNano(), 10),
}
services.Kafka.SendMessage(message)
//-- test that we ignore the message as it comes from the local source
services.Kafka.ConsumeTopic(true, 1)
if mockClientManager.messages != nil {
t.Errorf("Unexpected message! Got %v want %v", message.Content, "")
}
}
/*
Test that we can handle multiple messages, and that they're broadcast in the correct order
*/
func TestConsumingMultipleMessages(t *testing.T) {
mockClientManager := &MockClientManager{}
services.Manager = mockClientManager
services.Kafka = services.KafkaClient{
Topic: "test",
}
var messages []model.Message
//-- write 10 messages, each with a unique timestamp
for i := 0; i < 10; i++ {
message := model.Message{
Content: strconv.FormatInt(time.Now().UnixNano(), 10),
}
messages = append(messages, message)
services.Kafka.SendMessage(message)
}
//-- consume 10 messages
services.Kafka.ConsumeTopic(false, 10)
//-- verify that the messages are received in the order they're sent
for i := range messages {
if messages[i].Content != mockClientManager.messages[i].Content {
t.Errorf("Unexpected message! Got %v want %v", messages[i].Content, mockClientManager.messages[i].Content)
}
}
}
/*
Test sending a message, and that it gets set with the correct location ID
*/
func TestSendingMessage(t *testing.T) {
mockClientManager := &MockClientManager{}
services.Manager = mockClientManager
services.Kafka = services.KafkaClient{
Topic: "test",
}
message := model.Message{
Content: "Hello world",
}
services.Kafka.SendMessage(message)
//-- consume 1 message
services.Kafka.ConsumeTopic(false, 1)
//-- verify that the location ID is what we expect
if services.LocationID != mockClientManager.messages[0].SourceLocation {
t.Errorf("Unexpected location ID! Got %v want %v", mockClientManager.messages[0].SourceLocation, services.LocationID)
}
//-- verify that the payload is correct
if message.Content != mockClientManager.messages[0].Content {
t.Errorf("Unexpected message! Got %v want %v", mockClientManager.messages[0].Content, message.Content)
}
}
<file_sep>package model
type Message struct {
Id string `json:"id,omitempty"`
Sender string `json:"sender,omitempty"`
Recipient string `json:"recipient,omitempty"`
Content string `json:"content,omitempty"`
SourceLocation string `json:"location,omitempty"`
}
<file_sep>package services
import (
"realtime-chat/model"
//"github.com/confluentinc/confluent-kafka-go/kafka"
"github.com/rs/xid"
)
type KafkaClient struct {
Topic string
}
var LocationID = xid.New().String()
func (kc *KafkaClient) ConsumeTopic(ignoreMessagesFromSource bool, numMessages int) {
/* c, err := kafka.NewConsumer(&kafka.ConfigMap{
"bootstrap.servers": "localhost",
"group.id": "myGroup",
"client.id": "client",
"auto.offset.reset": "latest",
})
if err != nil {
panic(err)
}
log.Println("Consuming from Topic", kc.Topic)
c.Subscribe(kc.Topic, nil)
c.Poll(0)
n := 0
for n < numMessages {
message := model.Message{}
msg, err := c.ReadMessage(-1)
n++
if err != nil {
// The client will automatically try to recover from all errors.
log.Printf("Consumer error: %v (%v)\n", err, msg)
} else {
log.Printf("Message on %s: %s\n", msg.TopicPartition, string(msg.Value))
err = json.Unmarshal(msg.Value, &message)
if err != nil {
log.Printf("Unable to parse messages %s = %s\n", string(msg.Key), string(msg.Value))
}
//-- we may choose to ignore messages that this location has posted to Kafka since they may have already been broadcast
if ignoreMessagesFromSource {
if message.SourceLocation != LocationID {
Manager.Broadcast(msg.Value)
} else {
log.Printf("Ignoring message from source location. \n")
}
} else {
Manager.Broadcast(msg.Value)
}
}
}
c.Close()
*/
}
func (kc *KafkaClient) SendMessage(message model.Message) error {
/* p, err := kafka.NewProducer(&kafka.ConfigMap{"bootstrap.servers": "localhost"})
if err != nil {
panic(err)
}
defer p.Close()
// Delivery report handler for produced messages
go func() {
for e := range p.Events() {
switch ev := e.(type) {
case *kafka.Message:
if ev.TopicPartition.Error != nil {
fmt.Printf("Delivery failed: %v\n", ev.TopicPartition)
} else {
fmt.Printf("Delivered message to %v\n", ev.TopicPartition)
}
}
}
}()
// Produce messages to topic (asynchronously)
message.Id = xid.New().String()
message.SourceLocation = LocationID
jsonBytes, _ := json.Marshal(message)
p.Produce(&kafka.Message{
TopicPartition: kafka.TopicPartition{Topic: &kc.Topic, Partition: kafka.PartitionAny},
Value: []byte(jsonBytes),
Key: []byte(message.Id),
}, nil)
// Wait for message deliveries before shutting down
p.Flush(1 * 1000)
return nil
*/
return nil
}
<file_sep>package services
import (
"encoding/json"
"fmt"
"realtime-chat/model"
"github.com/gorilla/websocket"
)
type ClientManager interface {
Broadcast(message []byte)
Start()
Unregister(c *Client)
Register(c *Client)
}
var Manager ClientManager
var Kafka KafkaClient
type WebSocketClientManager struct {
Clients map[*Client]bool
BroadcastChannel chan []byte
RegisterChannel chan *Client
UnregisterChannel chan *Client
}
type Client struct {
Id string
Socket *websocket.Conn
Send chan []byte
}
func (manager *WebSocketClientManager) Broadcast(message []byte) {
manager.send(message, nil)
}
func (manager *WebSocketClientManager) Unregister(c *Client) {
manager.UnregisterChannel <- c
}
func (manager *WebSocketClientManager) Register(c *Client) {
manager.RegisterChannel <- c
}
func (manager *WebSocketClientManager) Start() {
for {
select {
case conn := <-manager.RegisterChannel:
manager.Clients[conn] = true
jsonMessage, _ := json.Marshal(&model.Message{Content: "/A new user has connected."})
manager.send(jsonMessage, conn)
case conn := <-manager.UnregisterChannel:
if _, ok := manager.Clients[conn]; ok {
close(conn.Send)
delete(manager.Clients, conn)
jsonMessage, _ := json.Marshal(&model.Message{Content: "/A user has disconnected."})
manager.send(jsonMessage, conn)
}
case message := <-manager.BroadcastChannel:
for conn := range manager.Clients {
select {
case conn.Send <- message:
default:
close(conn.Send)
delete(manager.Clients, conn)
}
}
}
}
}
func (manager *WebSocketClientManager) send(message []byte, ignore *Client) {
for conn := range manager.Clients {
if conn != ignore {
conn.Send <- message
}
}
}
func (c *Client) Read() {
defer func() {
Manager.Unregister(c)
c.Socket.Close()
}()
for {
_, message, err := c.Socket.ReadMessage()
if err != nil {
Manager.Unregister(c)
c.Socket.Close()
break
}
messagea := model.Message{Content: string(message)}
jsonMessage, _ := json.Marshal(&messagea)
Manager.Broadcast(jsonMessage)
err = Kafka.SendMessage(messagea)
if err != nil {
fmt.Println("Error writing to Kafka.")
}
}
}
func (c *Client) Write() {
defer func() {
c.Socket.Close()
}()
for {
select {
case message, ok := <-c.Send:
if !ok {
c.Socket.WriteMessage(websocket.CloseMessage, []byte{})
return
}
c.Socket.WriteMessage(websocket.TextMessage, message)
}
}
}
|
23c59ccb6747fdac35c567a16b723687f668d5f1
|
[
"Markdown",
"Go",
"Dockerfile"
] | 8 |
Go
|
dotmastery-com/messageservice
|
cd55e018c1c038334d0fe7318c685da15dc0cbea
|
50c5fba41c77fbadfc1a68a60ec23074ed6d641c
|
refs/heads/main
|
<repo_name>jvedder/CncLeveler<file_sep>/src/cncleveler/GCodeParser.java
package cncleveler;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.logging.Logger;
/**
* Reads and parses a text file of G Code commands. Processes each line (called a block in G code terminology)
* into a State object and returns a list of States objects that represents the G code file.
*/
public class GCodeParser
{
/**
* Logger for reporting status
*/
private static final Logger logger = Logger.getLogger((Main.class.getName()));
/**
* List of characters allowed in a number
*/
private static final Set<Character> NUMBER_CHARS = Set.of('+', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', '.');
/**
* List of valid G code state letters. These correspond to letters in the Mode enum.
*
* <pre>
* G = General Command
* M = Miscellaneous function
* </pre>
*/
public static final Set<Character> MODE_LETTERS = Set.of('G', 'M');
/**
* List of valid G code axis letters. These correspond to letters in the Axis enum, which
* includes both axes and parameters.
*
* <pre>
* N = Line Number or G10 parameter number
* F = Feed Rate
* S = (Spindle) Speed
* X,Y,Z = Axis Position
* I,J,K = Arc Center
* R = Radius
* L = Loop Count or G10 register number
* P = Parameter address
* T = Tool Selection
* </pre>
*/
public static final Set<Character> AXIS_LETTERS = Set.of('N', 'F', 'S', 'X', 'Y', 'Z', 'I', 'J', 'K', 'R', 'L', 'P',
'T');
/**
* Character buffer to hold the current line being parsed.
*/
protected char[] buffer;
/**
* Index into the character buffer.
*/
protected int index;
/**
* Current line number in the file. Used as a debug aid.
*/
protected int lineNum;
/**
* Initial letter of the current code word being parsed.
*/
char letter = '*';
/**
* The numerical portion of the current code word being parsed.
*/
double value = 0.0D;
/**
* The integer portion of the number in the current code word being parsed.
*/
int intValue = 0;
/**
* Reads and parses a G code file.
*
* @param filename The filename (and path) to the G code file
* @return An ordered list of states that contain the parsed information from the G code file.
* @throws IOException on any I/O error
*/
public List<State> read(String filename) throws IOException
{
// Show progress
logger.info("Opening: " + filename);
// Open input file for reading
Path inFile = Paths.get(filename);
List<State> states = new ArrayList<State>();
// BufferedReader supports readLine()
BufferedReader in = Files.newBufferedReader(inFile, StandardCharsets.UTF_8);
lineNum = 0;
String line;
while ((line = in.readLine()) != null)
{
lineNum++;
// Create a new State for this line
State state = new State();
state.lineNum = lineNum;
state.originalText = line;
states.add(state);
// Get a character buffer for parsing the line
buffer = line.trim().toUpperCase().toCharArray();
index = 0;
while (index < buffer.length)
{
if (MODE_LETTERS.contains(buffer[index]))
{
parseValue();
String code = State.format(letter, value);
Mode mode = Mode.find(code);
if (mode == null)
{
logError("Unrecognized code word:", code);
}
if (state.getGroup(mode.group()) != null)
{
logError("Duplicate Mode Group:", mode.code() + " to " + mode.group().name());
}
state.setGroup(mode.group(), mode);
}
else if (AXIS_LETTERS.contains(buffer[index]))
{
parseValue();
Axis axis = Axis.find(letter);
if (axis == null)
{
logError("Unrecognized code word:", State.format(letter, value));
}
if (state.getAxis(axis) != null)
{
logError("Duplicate Axis:", Character.toString(axis.letter()));
}
state.setAxis(axis, value);
}
else if (buffer[index] == '(')
{
String comment = parseComment();
if (state.getComment() != null)
{
logError("Duplicate Comment: ", comment);
}
state.setComment(comment);
}
else if (buffer[index] <= ' ')
{
// skip over white space
index++;
}
else if ((buffer[index] == '%'))
{
// skip over %
index++;
}
else
{
logError("Unrecognized code letter: ", Character.toString(buffer[index]));
}
}
}
in.close();
logger.info("Parsed " + lineNum + " lines");
return states;
}
/**
* Parses the value portion of a G-Code Word and sets the class-level letter, value and intValue
* fields as a return value.
*/
protected void parseValue()
{
letter = buffer[index];
index++;
if (endOfLine())
{
logError("Reached end of line; expected letter", null);
}
// Assume white space allowed before number
skipWhitespace();
if (endOfLine())
{
logError("Reached end of line; expected number", null);
}
// Put all number characters into a string
StringBuilder number = new StringBuilder();
while (!endOfLine() && NUMBER_CHARS.contains(buffer[index]))
{
number.append(buffer[index]);
index++;
}
// Parse the string into a double
value = 0.0;
try
{
value = Double.parseDouble(number.toString());
}
catch (NumberFormatException ex)
{
logError("Unable to parse number: ", number.toString());
}
intValue = (int) Math.floor(value);
}
/**
* Utility method to check if the index is at or past the end of the line buffer. This is
* implemented as a method for code readability.
*
* @return True is at or past the end of the line buffer. False otherwise,
*/
protected boolean endOfLine()
{
return index >= buffer.length;
}
/**
* Utility method to skip over white space in the line. Any character less than a space (' ') is
* considered white space. That includes tab, CR, and LF.
*/
protected void skipWhitespace()
{
while (!endOfLine() && (buffer[index] <= ' '))
index++;
}
/**
* Parses a comment field and returns it as a string.
*
*/
protected String parseComment()
{
StringBuilder text = new StringBuilder();
while (!endOfLine() && (buffer[index] != ')'))
{
text.append(buffer[index]);
index++;
}
if (endOfLine())
{
logError("Reached end of line inside comment", null);
}
text.append(buffer[index]);
index++;
return text.toString();
}
/**
* Formats an error message, adds file position, and log it to the log file.
*/
private void logError(String msg, String value)
{
StringBuilder sb = new StringBuilder();
sb.append(msg);
if (value != null)
{
sb.append(" ");
sb.append(value);
}
sb.append(" at line ");
sb.append(lineNum);
sb.append(", char ");
sb.append(index);
logger.severe(sb.toString());
// throw new RuntimeException(sb.toString());
}
}
<file_sep>/src/cncleveler/ProbeLogReader.java
package cncleveler;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
/**
* Reads a GRBL log file saved from UniversalGCodeSender console window and parses out the probe
* values.
*
*/
public class ProbeLogReader
{
private static final Logger logger = Logger.getLogger((Main.class.getName()));
/**
* Reads the specified probe log file and returns a list of probe values in file order.
*
* @param filename the filename of the probe log file.
* @return a list of the probe values.
* @throws IOException on IO errors
*/
public static List<Point3> read(String filename) throws IOException
{
// Show progress
logger.info("Reading: " + filename);
// Open input file for reading
Path inFile = Paths.get(filename);
// BufferedReader supports readLine()
BufferedReader in = Files.newBufferedReader(inFile, StandardCharsets.UTF_8);
String line;
List<Point3> probes = new ArrayList<Point3>();
while ((line = in.readLine()) != null)
{
if (line.startsWith("[PRB:"))
{
//
// Typical Line formated as:
// [PRB:-262.500,-150.000,-20.966:1]
//
try
{
// Pull out values between colons, then split at commas
String subline = line.split(":")[1];
String values[] = subline.split(",");
Point3 probe = new Point3();
probe.x = Double.parseDouble(values[0]);
probe.y = Double.parseDouble(values[1]);
probe.z = Double.parseDouble(values[2]);
probes.add(probe);
}
catch (Exception ex)
{
System.out.println("Error parsing: " + line);
}
}
}
in.close();
logProbeValues(probes);
// Show progress
logger.info("Reading complete");
return probes;
}
/**
* Reports the raw probe points to the logger for debug.
*
* @param probes the list of raw probe point values
*/
private static void logProbeValues(List<Point3> probes)
{
logger.info(" Raw Probe Points: " + probes.size());
for (Point3 probe : probes)
{
logger.fine(" " + probe.toString());
}
}
}
<file_sep>/src/cncleveler/Config.java
package cncleveler;
/**
* Defines the offset of the probe data in machine coordinates to work coordinates coordinates. This should be taken from the G54-G59 or G28, G30 settings.
*
* Hard-coded for now. TODO: implement a config file reader.
*
* <pre>
* Examples from GRBL $# command:
* [G54:-278.000,-155.000,-1.000]
* [G55:-232.000,-152.000,-15.000]
* [G28:-238.000,-155.000,-1.000]
* [G30:-278.000,-155.000,-1.000]
* </pre>
*/
public class Config
{
/* Setting for probe-results-4.txt */
public static Point3 probe_offset = new Point3( -272.5, -152.0, 0.0);
}
<file_sep>/src/cncleveler/logging/CncLogFormatter.java
package cncleveler.logging;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
/**
* A formatter for java.util.logging that outputs each log record as a simple, single line with a
* time stamp.
*/
public class CncLogFormatter extends Formatter
{
/**
* Format string for printing the log record
*/
private static final String FORMAT = "[%1$td-%1$tb-%1$tY %1$tT] %2$s%3$s%4$s%n";
/**
* Local variable used to hold and the time stamp of the log record in date and time format.
*/
private final Date timeStamp = new Date();
/**
* Formats the given LogRecord in the format:
*
* <pre>
* [20-Oct-2016 13:25:30] The application started
* [20-Oct-2016 13:25:31] This is application info status
* [20-Oct-2016 13:25:33] WARNING: This is some warning message
* [20-Oct-2016 13:28:10] ERROR: This is a severe message
* [20-Oct-2016 13:28:15] ERROR: This is a severe message with exception
* java.lang.IllegalArgumentException: invalid argument
* at MyClass.mash(MyClass.java:9)
* at MyClass.crunch(MyClass.java:6)
* at MyClass.main(MyClass.java:3)
* </pre>
*
* Adapted from the Oracle implementation of java.util.logging.SimpleFormatter (which is shared
* under GNU General Public License version 2)
*
* @param record the log record to be formatted.
* @return a formatted log record
*/
@Override
public synchronized String format(LogRecord record)
{
timeStamp.setTime(record.getMillis());
String level = "";
if (record.getLevel() == Level.WARNING) level = "WARNING: ";
if (record.getLevel() == Level.SEVERE) level = "ERROR: ";
String throwable = "";
if (record.getThrown() != null)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.println();
record.getThrown().printStackTrace(pw);
pw.close();
throwable = sw.toString();
}
return String.format(FORMAT, timeStamp, level, record.getMessage(), throwable);
}
}
<file_sep>/README.md
# CncLeveler
Work in Progress.: Auto-leveler for GRBL CNC mill. Reads probe data and modifies Z values in G-code file.
<file_sep>/src/cncleveler/Group.java
package cncleveler;
public enum Group
{
/**
* Values for modal G-Codes.
*/
// Motion modes: {G0, G1, G2, G3}
MOTION,
// plane modes: {G17, G18, G19}
PLANE,
// distance modes: {G90, G91}
DISTANCE,
// feed rate modes: {G93, G94}
RATE_MODE,
// units modes: {G20, G21}
UNITS,
// cutter radius compensation: {G40, G41, G42}
CUTTER_COMP,
// tool length offsets modes: {G43, G44, G49}
TOOL_LENGTH,
// work coordinate system modes: {G54, G55, G56, G57, G58, G59}
WORK_COORDINATES,
// spindle turning modes: {M3, M4, M5}
SPINDLE,
// coolant modes: {M7, M8, M9}
COOLANT,
// stopping modes: {M0, M1, M2, M30, M60}
STOPPING
}
<file_sep>/src/cncleveler/PyPlotGrid.java
package cncleveler;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Logger;
public class PyPlotGrid
{
private static Logger logger = Logger.getLogger((Main.class.getName()));
public void plot(ProbeGrid probeGrid) throws IOException
{
logger.info("Creating plot.py");
// Open output file for writing
Path outFile = Paths.get("plot.py");
BufferedWriter out = Files.newBufferedWriter(outFile, StandardCharsets.UTF_8);
// Python imports
out.write("import numpy as np\n");
out.write("import matplotlib.pyplot as plt\n");
out.write("from matplotlib import cm\n");
out.write("from mpl_toolkits.mplot3d import Axes3D\n");
out.write("\n");
// Build X Array
out.write("x=[\n");
for (int y = 0; y <= 50; y++)
{
out.write("[");
for (int x = 0; x <= 78; x++)
{
if (x > 0) out.write(',');
out.write(Integer.toString(x));
}
out.write("],\n");
}
out.write("]\n");
// Build y Array
out.write("y=[\n");
for (int y = 0; y <= 50; y++)
{
out.write("[");
for (int x = 0; x <= 78; x++)
{
if (x > 0) out.write(',');
out.write(Integer.toString(y));
}
out.write("],\n");
}
out.write("]\n");
// Build Z Array
out.write("z=[\n");
for (int y = 0; y <= 50; y++)
{
out.write("[");
for (int x = 0; x <= 78; x++)
{
if (x > 0) out.write(',');
double z = probeGrid.getProbeHeight((double) x, (double) y);
out.write(String.format("%.3f", z));
}
out.write("],\n");
}
out.write("]\n");
// Plot the surface
out.write("# Plot the surface.\n");
out.write("X = np.array(x)\n");
out.write("Y = np.array(y)\n");
out.write("Z = np.array(z)\n");
out.write("fig = plt.figure()\n");
out.write("ax = fig.gca(projection='3d')\n");
out.write("surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm)\n");
out.write("fig.colorbar(surf, shrink=0.5, aspect=5)\n");
// X Lines
out.write("# X Lines\n");
for (int j = 0; j < probeGrid.ysize; j++)
{
out.write("x=[");
for (int i = 0; i < probeGrid.xsize; i++)
{
if (i > 0) out.write(',');
out.write(String.format("%.3f", probeGrid.xgrid[i]));
}
out.write("]\n");
out.write("y=[");
for (int i = 0; i < probeGrid.xsize; i++)
{
if (i > 0) out.write(',');
out.write(String.format("%.3f", probeGrid.ygrid[j]));
}
out.write("]\n");
out.write("z=[");
for (int i = 0; i < probeGrid.xsize; i++)
{
if (i > 0) out.write(',');
out.write(String.format("%.3f", probeGrid.zprobe[j][i]));
}
out.write("]\n");
out.write("ax.plot(np.array(x),np.array(y),np.array(z),linewidth=2,color='black')\n");
}
// Y Lines
out.write("# Y Lines\n");
for (int i = 0; i < probeGrid.xsize; i++)
{
out.write("x=[");
for (int j = 0; j < probeGrid.ysize; j++)
{
if (j > 0) out.write(',');
out.write(String.format("%.3f", probeGrid.xgrid[i]));
}
out.write("]\n");
out.write("y=[");
for (int j = 0; j < probeGrid.ysize; j++)
{
if (j > 0) out.write(',');
out.write(String.format("%.3f", probeGrid.ygrid[j]));
}
out.write("]\n");
out.write("z=[");
for (int j = 0; j < probeGrid.ysize; j++)
{
if (j > 0) out.write(',');
out.write(String.format("%.3f", probeGrid.zprobe[j][i]));
}
out.write("]\n");
out.write("ax.plot(np.array(x),np.array(y),np.array(z),linewidth=2,color='black')\n");
}
out.write("plt.show()\n");
out.close();
logger.info("plot.py complete");
}
}
<file_sep>/src/cncleveler/logging/MessageFormatter.java
package cncleveler.logging;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
/**
* A formatter for java.util.logging that outputs just the message text for each
* log record as a single line. Warning and Severe messages are prefixed with
* their level. If a throwable exception is provided, it is printed on the line
* after the message.
* <p>
* This format is useful for simple run-time status logging to the console or
* status window.
*/
public class MessageFormatter extends Formatter
{
/**
* Format string for printing the log record
*/
private static final String FORMAT = "%1$s%2$s%3$s%n";
/**
* Formats the given LogRecord in the format:
*
* <pre>
* The application started
* This is application status
* WARNING: This is some warning message
* SEVERE: This is a severe message with exception
* java.lang.IllegalArgumentException: invalid argument
* at MyClass.mash(MyClass.java:9)
* at MyClass.crunch(MyClass.java:6)
* at MyClass.main(MyClass.java:3)
* </pre>
*
* @param record
* the log record to be formatted.
* @return a formatted log record
*/
@Override
public synchronized String format(LogRecord record)
{
String level = "";
if (record.getLevel() == Level.WARNING) level = "WARNING: ";
if (record.getLevel() == Level.SEVERE) level = "ERROR: ";
String throwable = "";
if (record.getThrown() != null)
{
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
pw.println();
record.getThrown().printStackTrace(pw);
pw.close();
throwable = sw.toString();
}
return String.format(FORMAT, level, record.getMessage(), throwable);
}
}
<file_sep>/src/cncleveler/Mode.java
package cncleveler;
/**
* Defines labels for each supported modal G code word. Also defines the modal group
* that the G code belongs to.
*/
public enum Mode
{
// Motion modes: {G0, G1, G2, G3}
RAPID ("G0", Group.MOTION),
LINEAR ("G1", Group.MOTION),
CIRCULAR_CW ("G2",Group.MOTION),
CIRCULAR_CCW ("G3",Group.MOTION),
// plane modes: {G17, G18, G19}
XY_PLANE ("G17",Group.PLANE),
XZ_PLANE ("G18",Group.PLANE),
YZ_PLANE ("G19",Group.PLANE),
// distance modes: {G90, G91}
ABSOLUTE ("G90",Group.DISTANCE),
INCREMENTAL ("G91",Group.DISTANCE),
// feed rate modes: {G93, G94}
STROKES_PER_MIN ("G93", Group.RATE_MODE),
FEED_PER_MIN ("G94", Group.RATE_MODE),
// units modes: {G20, G21}
INCHES ("G20", Group.UNITS),
MILLIMETERS ("G21", Group.UNITS),
// cutter radius compensation: {G40, G41, G42}
CUTTER_COMP_OFF ("G40", Group.CUTTER_COMP),
CUTTER_COMP_LEFT ("G41", Group.CUTTER_COMP),
CUTTER_COMP_RIGHT ("G42", Group.CUTTER_COMP),
// tool length offsets modes: {G43, G44, G49}
TOOL_LENGTH_NEG ("G43", Group.TOOL_LENGTH),
TOOL_LENGTH_POS ("G44", Group.TOOL_LENGTH),
TOOL_LENGTH_OFF ("G49", Group.TOOL_LENGTH),
// work coordinate system modes: {G54, G55, G56, G57, G58, G59}
WCS_G54 ("G54", Group.WORK_COORDINATES),
WCS_G55 ("G55", Group.WORK_COORDINATES),
WCS_G56 ("G56", Group.WORK_COORDINATES),
WCS_G57 ("G57", Group.WORK_COORDINATES),
WCS_G58 ("G58", Group.WORK_COORDINATES),
WCS_G59 ("G59", Group.WORK_COORDINATES),
// spindle turning modes: {M3, M4, M5}
SPINDLE_CW ("M3", Group.SPINDLE),
SPINDLE_CCW ("M4", Group.SPINDLE),
SPINDLE_OFF ("M5", Group.SPINDLE),
// coolant modes: {M7, M8, M9}
COOLANT_MIST ("M7", Group.COOLANT),
COOLANT_FLOOD ("M8", Group.COOLANT),
COOLANT_OFF ("M9", Group.COOLANT),
// stopping modes: {M0, M1, M2, M30, M60}
STOP ("M0", Group.STOPPING),
OPTIONAL_STOP ("M1", Group.STOPPING),
END ("M2", Group.STOPPING),
END_RETURN ("M30", Group.STOPPING),
PALLET_CHANGE ("M60", Group.STOPPING);
private final String code;
private final Group group;
/*
* Private constructor only used by the enum definitions themselves.
*
* @param code
* The full G code word that the enum represents
* @param group
* The modal group that this G code belongs to
*/
private Mode(String code , Group group)
{
this.code = code;
this.group = group;
}
/* Getters */
public String code() { return code; }
public Group group() { return group; }
/**
* Utility method to find and return the enum value for a specific G code word.
* Returns null if not found.
*
* @param code
* the code word to search for
* @return the matching enum or null if not found
*/
public static Mode find(String code)
{
for (Mode m : Mode.values())
{
if(m.code().equals(code)) return m;
}
return null;
}
}<file_sep>/src/cncleveler/Axis.java
package cncleveler;
/**
* Defines labels for each supported axis or parameter. Also flags if the value
* is modal -- true if the value carries forward to the next G code line (block).
*/
public enum Axis
{
// Line Number
LINE_NUM('N', true),
// Feed and Speed
FEED('F', true),
SPEED('S', true),
//Cartesian Axes
X('X', true),
Y('Y', true),
Z('Z', true),
// Arc Center Offset
I('I', false),
J('J', false),
K('K', false),
// Radius
RADIUS('R', false),
// Loop Count or G10 register number
LOOP('L', false),
// Parameter address
PARAM('P', false),
// Tool Selection
TOOL('T', false);
private final char letter;
private final boolean modal;
/*
* Private constructor only used by the enum definitions themselves.
*
* @param letter
* The G code letter that this enum represents
* @param modal
* True if this G code is modal
*/
private Axis(char letter, boolean modal)
{
this.letter = letter;
this.modal = modal;
}
/* Getters */
public char letter() { return letter; }
public boolean modal() { return modal; }
/**
* Utility method to find and return the enum value for a specific letter.
* Returns null if not found.
*
* @param letter
* the letter to search for
* @return the matching enum or null if not found
*/
public static Axis find(char letter)
{
for (Axis a : Axis.values())
{
if(a.letter() == letter) return a;
}
return null;
}
}
<file_sep>/src/cncleveler/Main.java
package cncleveler;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.FileHandler;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import cncleveler.logging.CncLogFormatter;
public class Main
{
private static final Logger logger = Logger.getLogger((Main.class.getName()));
private static FileHandler logFileHander;
private static ConsoleHandler consoleHandler;
public static void main(String[] args) throws Exception
{
setupLogger();
logger.info("Starting");
List<Point3> probes = ProbeLogReader.read("probe-results-4.txt");
ProbeGrid grid = new ProbeGrid(probes);
//ProbeGrid grid = new ProbeGrid(testProbes());
PyPlotGrid plot = new PyPlotGrid();
plot.plot(grid);
GCodeParser parser = new GCodeParser();
List<State> states = parser.read("gcode.nc");
parser = null;
Leveler.level(states, grid);
//replayStates(states);
GCodeWriter.write("gcode_leveled.nc", states);
logger.info("Done.");
}
protected static void replayStates(List<State> states)
{
State globalState = new State();
for (State state : states)
{
globalState.mergeWith(state);
System.out.println("----------------------------------");
System.out.println("Orig: " + state.originalText);
System.out.println("State: " + state.toString());
System.out.println("Global: " + globalState.toString());
// globalState.print();
}
}
protected static List<Point3> testProbes()
{
List<Point3> probes = new ArrayList<>();
probes.add(new Point3(2, 2, 0.003));
probes.add(new Point3(24, 2, -0.121));
probes.add(new Point3(50, 2, -0.143));
probes.add(new Point3(74, 2, -0.143));
probes.add(new Point3(2, 25, 0.035));
probes.add(new Point3(24, 25, -0.065));
probes.add(new Point3(50, 25, -0.1));
probes.add(new Point3(74, 25, -0.104));
probes.add(new Point3(2, 48, 0));
probes.add(new Point3(24, 48, -0.036));
probes.add(new Point3(50, 48, -0.041));
probes.add(new Point3(74, 48, -0.038));
return probes;
}
/**
* Sets up the application logging to a file
*/
private static void setupLogger() throws SecurityException, IOException
{
LogManager.getLogManager().reset();
logFileHander = new FileHandler("CncLeveler.%u.log");
logFileHander.setFormatter(new CncLogFormatter());
logger.addHandler(logFileHander);
consoleHandler = new ConsoleHandler();
consoleHandler.setFormatter(new CncLogFormatter());
logger.addHandler(consoleHandler);
logger.setLevel(Level.ALL);
}
}
|
985bf299bb987066fd2a549baa11e71cc01acb78
|
[
"Markdown",
"Java"
] | 11 |
Java
|
jvedder/CncLeveler
|
852f376307296b97068ad5dc145f98bbb4bb9831
|
6229fabb5d4579b454b1c250b3b264c0c1774242
|
refs/heads/main
|
<repo_name>ssunil007/SUNIL-SREENIVASA<file_sep>/monefy_automation/src/main/java/com/monefy/app/lite/pages/ExpensePage.java
/**
* @author sunil_s
* @created on 06/26/2021
*/
package com.monefy.app.lite.pages;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.safari.ConnectionClosedException;
import com.monefy.app.lite.common.DriverSetup;
import com.monefy.app.lite.objectrepo.BaseObjRepo;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidKeyCode;
public class ExpensePage extends BasePage {
String platFormName = DriverSetup.getPlatform();
/**
* @author sunil_s
* @description Method to verify home screen validations
* @param TC
* @return
*/
public boolean HomeScreenValidations(String TC,WebDriver dr, BaseObjRepo obj, String month,String actRes, String expRes){
String[] actResult = actRes.split("\\|");
String[] expResult = expRes.split("\\|");
try {
obj.getHomeScreen_OpenNavigationBtn(dr, actResult[0]).getText().trim().equalsIgnoreCase(expResult[0]);
obj.getHomeScreen_HomeScreenTitle(dr, actResult[1]).getText().trim().equalsIgnoreCase(expResult[1]);
obj.getHomeScreen_AllAccountsTxt(dr, actResult[2]).getText().trim().equalsIgnoreCase(expResult[2]);
obj.getHomeScreen_SearchBtn(dr, actResult[3]).getText().trim().equalsIgnoreCase(expResult[3]);
obj.getHomeScreen_TransferBtn(dr, actResult[4]).getText().trim().equalsIgnoreCase(expResult[4]);
obj.getHomeScreen_SettingsBtn(dr, actResult[5]).getText().trim().equalsIgnoreCase(expResult[5]);
obj.getHomeScreen_MonthTxt(dr, month).isDisplayed();
obj.getHomeScreen_IncomeAmtTxt(dr).getText().trim().equalsIgnoreCase(expResult[6]);
obj.getHomeScreen_ExpenseAmtTxt(dr).getText().trim().equalsIgnoreCase(expResult[6]);
obj.getHomeScreen_BalanceAmtTxt(dr).getText().trim().equalsIgnoreCase(expResult[7]);
obj.getHomeScreen_IncomeBtn(dr).getText().trim().equalsIgnoreCase(expResult[8]);
obj.getHomeScreen_ExpenseBtn(dr).getText().trim().equalsIgnoreCase(expResult[9]);
System.out.println("TestCase : PASS");
return true;
} catch (TimeoutException te) {
te.printStackTrace();
System.out.println("TestCase: FAIL <Timeout Exception> " + te.getMessage());
return false;
} catch (NoSuchElementException nse) {
nse.printStackTrace();
System.out.println("TestCase: FAIL <NoSuchElement Exception> " + nse.getMessage());
return false;
} catch (ConnectionClosedException cce) {
cce.printStackTrace();
System.out.println("TestCase: FAIL <ConnectionClosed Exception> " + cce.getMessage());
return false;
} catch (Exception ie) {
ie.printStackTrace();
System.out.println("TestCase: FAIL <Exception> " + ie.getMessage());
return false;
}
}
/**
* @author sunil_s
* @description Method to verify expense screen validations
* @param TC
* @return
*/
public boolean ExpenseScreenValidations(String TC,WebDriver dr, BaseObjRepo obj,String actRes, String expRes){
String[] actResult = actRes.split("\\|");
String[] expResult = expRes.split("\\|");
try {
waitforElementToLoad(2);
obj.getHomeScreen_ExpenseBtn(dr).click();
waitforElementToLoad(3);
obj.getExpenseScreen_AlertToastMsg(dr, actResult[0]).getText().trim().equalsIgnoreCase(expResult[0]);
obj.getExpenseScreen_AlertToastMsg(dr, actResult[0]).click();
obj.getExpenseScreen_NavigateUpBtn(dr).isDisplayed();
obj.getExpenseScreen_Title(dr, actResult[1]).getText().trim().equalsIgnoreCase(expResult[1]);
obj.getExpenseScreen_RepeatBtn(dr).getText().trim().equalsIgnoreCase(expResult[2]);
obj.getExpenseScreen_DatePicker(dr).isDisplayed();
obj.getExpenseScreen_CurrencyIcon(dr).isDisplayed();
obj.getExpenseScreen_CurrencyTxt(dr).getText().trim().equalsIgnoreCase(expResult[3]);
obj.getExpenseScreen_AmtTxtFld(dr).isDisplayed();
obj.getExpenseScreen_KeyboardClearBtn(dr).isDisplayed();
obj.getExpenseScreen_NoteTxtFld(dr).getText().trim().equalsIgnoreCase(expResult[4]);
obj.getExpenseScreen_ChooseCategoryBtn(dr).getText().trim().equalsIgnoreCase(expResult[5]);
System.out.println("TestCase : PASS");
return true;
} catch (TimeoutException te) {
te.printStackTrace();
System.out.println("TestCase: FAIL <Timeout Exception> " + te.getMessage());
return false;
} catch (NoSuchElementException nse) {
nse.printStackTrace();
System.out.println("TestCase: FAIL <NoSuchElement Exception> " + nse.getMessage());
return false;
} catch (ConnectionClosedException cce) {
cce.printStackTrace();
System.out.println("TestCase: FAIL <ConnectionClosed Exception> " + cce.getMessage());
return false;
} catch (Exception ie) {
ie.printStackTrace();
System.out.println("TestCase: FAIL <Exception> " + ie.getMessage());
return false;
}
}
/**
* @author sunil_s
* @description Method to verify Repeat Button Functionality
* @param TC
* @return
*/
public boolean ExpenseScreen_RepeatButtonFunctionality(String TC,WebDriver dr, BaseObjRepo obj,String actRes, String expRes){
String[] actResult = actRes.split("\\|");
String[] expResult = expRes.split("\\|");
try {
waitforElementToLoad(2);
obj.getExpenseScreen_RepeatBtn(dr).click();
waitforElementToLoad(2);
obj.getMonefyProScreen_Title(dr).getText().trim().equalsIgnoreCase(expResult[1]);
obj.getMonefyProScreen_BuyBtn(dr).getText().trim().equalsIgnoreCase(expResult[2]);
obj.getMonefyProScreen_ProFeaturesTxt(dr).getText().trim().equalsIgnoreCase(expResult[3]);
obj.getMonefyProScreen_ProFeatureList(dr).get(0).getText().trim().equalsIgnoreCase(expResult[4]);
obj.getMonefyProScreen_ProFeatureList(dr).get(1).getText().trim().equalsIgnoreCase(expResult[5]);
obj.getMonefyProScreen_ProFeatureList(dr).get(2).getText().trim().equalsIgnoreCase(expResult[6]);
obj.getMonefyProScreen_ProFeatureList(dr).get(3).getText().trim().equalsIgnoreCase(expResult[7]);
((AndroidDriver<?>)dr).sendKeyEvent(AndroidKeyCode.BACK);waitforElementToLoad(2);
obj.getExpenseScreen_Title(dr, actResult[0]).getText().trim().equalsIgnoreCase(actResult[0]);
System.out.println("TestCase : PASS");
return true;
} catch (TimeoutException te) {
te.printStackTrace();
System.out.println("TestCase: FAIL <Timeout Exception> " + te.getMessage());
return false;
} catch (NoSuchElementException nse) {
nse.printStackTrace();
System.out.println("TestCase: FAIL <NoSuchElement Exception> " + nse.getMessage());
return false;
} catch (ConnectionClosedException cce) {
cce.printStackTrace();
System.out.println("TestCase: FAIL <ConnectionClosed Exception> " + cce.getMessage());
return false;
} catch (Exception ie) {
ie.printStackTrace();
System.out.println("TestCase: FAIL <Exception> " + ie.getMessage());
return false;
}
}
/**
* @author sunil_s
* @description Method to verify Date Picker Functionality
* @param TC
* @return
*/
public boolean ExpenseScreen_DatePickerFunctionality(String TC,WebDriver dr, BaseObjRepo obj,String actRes, String expRes){
String[] expResult = expRes.split("\\|");
Date date = commonUtils.getDate(1);
final String MMDDYYY = new SimpleDateFormat("MM/dd/yyyy").format(date);
final String MMMDDYYYY = new SimpleDateFormat("MMM dd, yyyy").format(date);
final String EEEEDDMM = new SimpleDateFormat("EEEE, dd MMM").format(date);
try {
obj.getExpenseScreen_DatePicker(dr).click();waitforElementToLoad(2);
obj.getDatePicker_SelectDateTxt(dr).getText().trim().equalsIgnoreCase(expResult[1]);
obj.getDataPicker_EditIcon(dr).click(); waitforElementToLoad(1);
obj.getDataPicker_CalendarIcon(dr).isDisplayed();
WebElement element = obj.getDataPicker_DateTxtFld(dr);
element.clear();
element.sendKeys(MMDDYYY);
((AndroidDriver<?>)dr).sendKeyEvent(AndroidKeyCode.ENTER);
obj.getDatePicker_DateTxt(dr).getText().trim().equalsIgnoreCase(MMMDDYYYY);
obj.getDataPicker_OkBtn(dr).click();waitforElementToLoad(2);
obj.getExpenseScreen_DatePicker(dr).getText().trim().equalsIgnoreCase(EEEEDDMM);
System.out.println("TestCase : PASS");
return true;
} catch (TimeoutException te) {
te.printStackTrace();
System.out.println("TestCase: FAIL <Timeout Exception> " + te.getMessage());
return false;
} catch (NoSuchElementException nse) {
nse.printStackTrace();
System.out.println("TestCase: FAIL <NoSuchElement Exception> " + nse.getMessage());
return false;
} catch (ConnectionClosedException cce) {
cce.printStackTrace();
System.out.println("TestCase: FAIL <ConnectionClosed Exception> " + cce.getMessage());
return false;
} catch (Exception ie) {
ie.printStackTrace();
System.out.println("TestCase: FAIL <Exception> " + ie.getMessage());
return false;
}
}
/**
* @author sunil_s
* @description Method to verify Change Payment Method
* @param TC
* @return
*/
public boolean ExpenseScreen_ChangePaymentMethod(String TC,WebDriver dr, BaseObjRepo obj,String actRes, String expRes){
String[] actResult = actRes.split("\\|");
String[] expResult = expRes.split("\\|");
try {
obj.getExpenseScreen_CurrencyIcon(dr).isDisplayed();
obj.getExpenseScreen_CurrencyTxt(dr).getText().trim().equalsIgnoreCase(expResult[1]);
obj.getExpenseScreen_CurrencyTxt(dr).click(); waitforElementToLoad(1);
obj.getExpenseScreen_PaymentMethod(dr, actResult[2]).getText().trim().equalsIgnoreCase(expResult[2]);
obj.getExpenseScreen_PaymentMethod(dr, actResult[3]).getText().trim().equalsIgnoreCase(expResult[3]);
obj.getExpenseScreen_CurrencyIcon(dr).isDisplayed();
obj.getExpenseScreen_CurrencyTxt(dr).isDisplayed();
if(TC.equalsIgnoreCase("TC_01")){
obj.getExpenseScreen_PaymentMethod(dr, actResult[2]).click(); waitforElementToLoad(2);
}else{
obj.getExpenseScreen_PaymentMethod(dr, actResult[3]).click(); waitforElementToLoad(2);
}
System.out.println("TestCase : PASS");
return true;
} catch (TimeoutException te) {
te.printStackTrace();
System.out.println("TestCase: FAIL <Timeout Exception> " + te.getMessage());
return false;
} catch (NoSuchElementException nse) {
nse.printStackTrace();
System.out.println("TestCase: FAIL <NoSuchElement Exception> " + nse.getMessage());
return false;
} catch (ConnectionClosedException cce) {
cce.printStackTrace();
System.out.println("TestCase: FAIL <ConnectionClosed Exception> " + cce.getMessage());
return false;
} catch (Exception ie) {
ie.printStackTrace();
System.out.println("TestCase: FAIL <Exception> " + ie.getMessage());
return false;
}
}
/**
* @author sunil_s
* @description Method to verify Amount Input Field Functionality
* @param TC
* @return
*/
public boolean ExpenseScreen_AmountInputFieldFunctionality(String TC,WebDriver dr, BaseObjRepo obj,String actRes, String expRes){
String[] actResult = actRes.split("\\|");
String[] expResult = expRes.split("\\|");
try {
commonUtils.enter_amount_using_keypad(dr, actResult[1]);
commonUtils.enter_amount_using_keypad(dr, actResult[2]);
commonUtils.enter_amount_using_keypad(dr, actResult[3]);
commonUtils.enter_amount_using_keypad(dr,actResult[4]);
waitforElementToLoad(2);
String actualAmount = obj.getExpenseScreen_AmtTxtFld(dr).getText();
if(Integer.compare(Integer.parseInt(actualAmount), Integer.parseInt(expResult[1])) !=0){
System.out.println("TestCase : FAIL Actual Amount : "+ actualAmount + " Expected Amount : "+ expResult[1]);
while(!obj.getExpenseScreen_AmtTxtFld(dr).getText().trim().equalsIgnoreCase(expResult[2])){
obj.getExpenseScreen_KeyboardClearBtn(dr).click();
}
return false;
}
while(!obj.getExpenseScreen_AmtTxtFld(dr).getText().trim().equalsIgnoreCase(expResult[2])){
obj.getExpenseScreen_KeyboardClearBtn(dr).click();
}
waitforElementToLoad(2);
System.out.println("TestCase : PASS");
return true;
} catch (TimeoutException te) {
te.printStackTrace();
System.out.println("TestCase: FAIL <Timeout Exception> " + te.getMessage());
return false;
} catch (NoSuchElementException nse) {
nse.printStackTrace();
System.out.println("TestCase: FAIL <NoSuchElement Exception> " + nse.getMessage());
return false;
} catch (ConnectionClosedException cce) {
cce.printStackTrace();
System.out.println("TestCase: FAIL <ConnectionClosed Exception> " + cce.getMessage());
return false;
} catch (Exception ie) {
ie.printStackTrace();
System.out.println("TestCase: FAIL <Exception> " + ie.getMessage());
return false;
}
}
/**
* @author sunil_s
* @description Method to verify undo added expense
* @param TC
* @return
*/
public boolean ExpenseScreen_UndoAddedExpense(String TC,WebDriver dr, BaseObjRepo obj,String actRes, String expRes){
String[] actResult = actRes.split("\\|");
String[] expResult = expRes.split("\\|");
try {
commonUtils.enter_amount_using_keypad(dr, actResult[1]);
commonUtils.enter_amount_using_keypad(dr, actResult[2]);
commonUtils.enter_amount_using_keypad(dr, actResult[3]);
commonUtils.enter_amount_using_keypad(dr,actResult[4]);
waitforElementToLoad(2);
obj.getExpenseScreen_NoteTxtFld(dr).sendKeys(actResult[5]); waitforElementToLoad(2);
((AndroidDriver<?>)dr).hideKeyboard();
obj.getExpenseScreen_NoteTxtFld(dr).getText().trim().equalsIgnoreCase(expResult[2]);
obj.getExpenseScreen_ChooseCategoryBtn(dr).click();
obj.getExpenseScreen_CategoryBtn(dr, actResult[6]).click();
obj.getHomeScreen_BillsToastMsg(dr).getText().trim().equalsIgnoreCase(expResult[3]);
obj.getHomeScreen_ExpenseAmtTxt(dr).getText().trim().equalsIgnoreCase(expResult[4]);
obj.getHomeScreen_BalanceAmtTxt(dr).getText().trim().equalsIgnoreCase(expResult[5]);
obj.getHomeScreen_CancelButton(dr).click();waitforElementToLoad(2);
obj.getHomeScreen_ExpenseAmtTxt(dr).getText().trim().equalsIgnoreCase(expResult[6]);
obj.getHomeScreen_BalanceAmtTxt(dr).getText().trim().equalsIgnoreCase(expResult[7]);
System.out.println("TestCase : PASS");
return true;
} catch (TimeoutException te) {
te.printStackTrace();
System.out.println("TestCase: FAIL <Timeout Exception> " + te.getMessage());
return false;
} catch (NoSuchElementException nse) {
nse.printStackTrace();
System.out.println("TestCase: FAIL <NoSuchElement Exception> " + nse.getMessage());
return false;
} catch (ConnectionClosedException cce) {
cce.printStackTrace();
System.out.println("TestCase: FAIL <ConnectionClosed Exception> " + cce.getMessage());
return false;
} catch (Exception ie) {
ie.printStackTrace();
System.out.println("TestCase: FAIL <Exception> " + ie.getMessage());
return false;
}
}
/**
* @author sunil_s
* @description Method to verify adding expense
* @param TC
* @return
*/
public boolean ExpenseScreen_AddingExpense(String TC,WebDriver dr, BaseObjRepo obj,String actRes, String expRes){
String[] actResult = actRes.split("\\|");
String[] expResult = expRes.split("\\|");
Date date = commonUtils.getDate(2);
final String MMDDYYY = new SimpleDateFormat("MM/dd/yyyy").format(date);
final String MMMDDYYYY = new SimpleDateFormat("MMM dd, yyyy").format(date);
final String EEEEDDMM = new SimpleDateFormat("EEEE, dd MMM").format(date);
try {
obj.getHomeScreen_ExpenseBtn(dr).click();waitforElementToLoad(2);
obj.getExpenseScreen_DatePicker(dr).click();waitforElementToLoad(2);
obj.getDatePicker_SelectDateTxt(dr).getText().trim().equalsIgnoreCase(expResult[1]);
obj.getDataPicker_EditIcon(dr).click(); waitforElementToLoad(1);
obj.getDataPicker_CalendarIcon(dr).isDisplayed();
WebElement element = obj.getDataPicker_DateTxtFld(dr);
element.clear();
element.sendKeys(MMDDYYY);
((AndroidDriver<?>)dr).sendKeyEvent(AndroidKeyCode.ENTER);
obj.getDatePicker_DateTxt(dr).getText().trim().equalsIgnoreCase(MMMDDYYYY);
obj.getDataPicker_OkBtn(dr).click();waitforElementToLoad(2);
obj.getExpenseScreen_DatePicker(dr).getText().trim().equalsIgnoreCase(EEEEDDMM);
commonUtils.enter_amount_using_keypad(dr, actResult[2]);
commonUtils.enter_amount_using_keypad(dr, actResult[3]);
commonUtils.enter_amount_using_keypad(dr, actResult[4]);
commonUtils.enter_amount_using_keypad(dr,actResult[5]);
waitforElementToLoad(2);
obj.getExpenseScreen_NoteTxtFld(dr).sendKeys(actResult[6]); waitforElementToLoad(2);
((AndroidDriver<?>)dr).hideKeyboard();
obj.getExpenseScreen_NoteTxtFld(dr).getText().trim().equalsIgnoreCase(expResult[3]);
obj.getExpenseScreen_ChooseCategoryBtn(dr).click();
obj.getExpenseScreen_CategoryBtn(dr, actResult[7]).click(); waitforElementToLoad(2);
obj.getHomeScreen_BillsToastMsg(dr).getText().trim().equalsIgnoreCase(expResult[4]);
obj.getHomeScreen_ExpenseAmtTxt(dr).getText().trim().equalsIgnoreCase(expResult[5]);
obj.getHomeScreen_BalanceAmtTxt(dr).getText().trim().equalsIgnoreCase(expResult[6]);
System.out.println("TestCase : PASS");
return true;
} catch (TimeoutException te) {
te.printStackTrace();
System.out.println("TestCase: FAIL <Timeout Exception> " + te.getMessage());
return false;
} catch (NoSuchElementException nse) {
nse.printStackTrace();
System.out.println("TestCase: FAIL <NoSuchElement Exception> " + nse.getMessage());
return false;
} catch (ConnectionClosedException cce) {
cce.printStackTrace();
System.out.println("TestCase: FAIL <ConnectionClosed Exception> " + cce.getMessage());
return false;
} catch (Exception ie) {
ie.printStackTrace();
System.out.println("TestCase: FAIL <Exception> " + ie.getMessage());
return false;
}
}
}
<file_sep>/monefy_automation/src/test/java/com/monefy/app/lite/dataprovider/IncomeDP.java
package com.monefy.app.lite.dataprovider;
import org.testng.annotations.DataProvider;
import com.monefy.app.lite.common.CommonCV;
import com.monefy.app.lite.common.DriverSetup;
public class IncomeDP extends CommonCV {
public static String platFormName = DriverSetup.getPlatform();
// Test Data to verify Income Screen Validations
@DataProvider(name = "IncomeScreenValidations")
public static Object[][] IncomeScreenValidations() {
return new Object[][] { { "TC_01",
"Recurring records are now available in Monefy Pro!|New income|Repeat|USD|Note|CHOOSE CATEGORY",
"Recurring records are now available in Monefy Pro!|New income|Repeat|USD|Note|CHOOSE CATEGORY" } };
}
// Test Data to verify Income Screen - Repeat Button Functionality
@DataProvider(name = "IncomeScreen_RepeatButtonFunctionality")
public static Object[][] IncomeScreen_RepeatButtonFunctionality() {
return new Object[][] { { "TC_01", "New income|Repeat",
"New income|Monefy Pro|Buy|Pro Features|Recurring Records|Multi-Currency|Synchronization|Passcode Protection" } };
}
// Test Data to verify Income Screen - Date Picker Functionality
@DataProvider(name = "IncomeScreen_DatePickerFunctionality")
public static Object[][] IncomeScreen_DatePickerFunctionality() {
return new Object[][] { { "TC_01", "New income|SELECT DATE", "New income|SELECT DATE" } };
}
// Test Data to verify Income Screen - Change Payment Method
@DataProvider(name = "IncomeScreen_ChangePaymentMethod")
public static Object[][] IncomeScreen_ChangePaymentMethod() {
return new Object[][] { { "TC_01", "New income|USD|Payment card|Cash", "New income|USD|Payment card|Cash" },
{ "TC_02", "New income|USD|Payment card|Cash", "New income|USD|Payment card|Cash" } };
}
// Test Data to verify Income Screen - Amount InputField Functionality
@DataProvider(name = "IncomeScreen_AmountInputFieldFunctionality")
public static Object[][] IncomeScreen_AmountInputFieldFunctionality() {
return new Object[][] { { "TC_01", "New income|100|×|10|=", "New income|1000|0" },
{ "TC_02", "New income|800|+|200|=", "New income|1000|0" },
{ "TC_03", "New income|1200|-|200|=", "New income|1000|0" },
{ "TC_04", "New income|10000|÷|10|=", "New income|1000|0" } };
}
// Test Data to verify Income Screen - Undo Added Income
@DataProvider(name = "IncomeScreen_UndoAddedIncome")
public static Object[][] IncomeScreen_UndoAddedIncome() {
return new Object[][] { { "TC_01", "New income|1000|×|10|=|Test Note Input Functionality|Salary",
"New income|10000|Test Note Input Functionality|Salary: $10,000.00 added|$20,000.00|Balance $10,000.00|$0.00|Balance $0.00" } };
}
// Test Data to verify Income Screen - Adding Income
@DataProvider(name = "IncomeScreen_AddingIncome")
public static Object[][] IncomeScreen_AddingIncome() {
return new Object[][] { { "TC_01", "New income|SELECT DATE|1000|×|10|=|Test Note Input Functionality|Salary",
"New income|SELECT DATE|10000|Test Note Input Functionality|Salary: $10,000.00 added|$10,000.00|Balance $10,000.00" } };
}
}
<file_sep>/monefy_automation/README.md
Mobile Automation Framework
=======================
## Testing Mobile App using Open Source Tools
## Objective
Intent of this proect is to illustrate how wide range of **Open Source Tools** can be used to test mobile applications both **Android** or **iOS** and parallelise the test suite with multiple connected devices.
## Snapshot
This is a simple **Maven** project designed as a hybrid framwork with combination of Page Object Model and Data Driven Framework and is created using various **Open Source Tools** such as
* Appium - Open Source Tool for cross platform testing
* Selenium WebDriver - WebDriver API used to to perform mobile gestures
* Maven - Dependency Management
* TestNG - Test Annotation to organize test suite and parameterization
## Installations
1. Download and Install JDK8 from the below link
[https://adoptopenjdk.net/]
2. Download and Install Android Studio from the below link
[https://developer.android.com/studio?gclid=CjwKCAjww-CGBhALEiwAQzWxOhsAUZlMWuodNM3WgYZUY82q1QILJoGWT2AW5ESns35NwSgD60pYfxoCjkwQAvD_BwE&gclsrc=aw.ds]
3. Download and Install Appium Desktop from the below link
[https://github.com/appium/appium-desktop/releases/]
>Note: Appium version above 1.17.0 is preferrable
4. Setting Envirnoment variables JAVA_HOME & ANDRIOD_HOME
## Steps for Execution
1. Clone the repository into any IDE ( Eclipse or IntelliJ )
2. Open **Android Studio**, configure an _emulator_ in AVD Manager and launch it
3. Launch the **Appium Deskop** and start the server
4. Build the Project using **Maven** to update the dependencies
5. Run the below command from project directory to start execution
```
mvn clean test -Drelease.arguments=testng_android3.xml -Dplatform=Android -DdeviceName=Android -DplatformVersion=9.0 -DappPath=/src/test/resources/AppFile/com.monefy.app.lite_2021-06-15.apk -DlogFilePath=/src/test/resources/Screenshots
```
<file_sep>/monefy_automation/src/main/java/com/monefy/app/lite/objectrepo/ObjRepoIOS.java
/**
* @author sunil_s
* @created on 06/26/2021
* @description Class containing locators for iOS Elements
*/
package com.monefy.app.lite.objectrepo;
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
public class ObjRepoIOS extends BaseObjRepo {
private static WebElement element = null;
private static List<WebElement> elements = null;
WebDriverWait wait = null;
@Override
public WebElement getHomeScreen_OpenNavigationBtn(WebDriver dr, String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getHomeScreen_HomeScreenTitle(WebDriver dr, String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getHomeScreen_AllAccountsTxt(WebDriver dr, String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getHomeScreen_SearchBtn(WebDriver dr, String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getHomeScreen_TransferBtn(WebDriver dr, String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getHomeScreen_SettingsBtn(WebDriver dr, String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getHomeScreen_MonthTxt(WebDriver dr, String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getHomeScreen_IncomeAmtTxt(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getHomeScreen_ExpenseAmtTxt(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getHomeScreen_BalanceAmtTxt(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getHomeScreen_ExpenseBtn(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getHomeScreen_IncomeBtn(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getExpenseScreen_AlertToastMsg(WebDriver dr, String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getExpenseScreen_NavigateUpBtn(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getExpenseScreen_Title(WebDriver dr, String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getExpenseScreen_DatePicker(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getExpenseScreen_CurrencyIcon(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getExpenseScreen_CurrencyTxt(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getExpenseScreen_AmtTxtFld(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getExpenseScreen_KeyboardClearBtn(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getExpenseScreen_NoteTxtFld(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getExpenseScreen_KeyboardBtn(WebDriver dr, String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getExpenseScreen_ChooseCategoryBtn(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getHomeScreen_BillsToastMsg(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getHomeScreen_CancelButton(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getExpenseScreen_RepeatBtn(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getExpenseScreen_PaymentMethod(WebDriver dr, String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getExpenseScreen_CategoryBtn(WebDriver dr, String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getMonefyProScreen_Title(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getMonefyProScreen_BuyBtn(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getMonefyProScreen_ProFeaturesTxt(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<WebElement> getMonefyProScreen_ProFeatureList(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getDatePicker_SelectDateTxt(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getDatePicker_DateTxt(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getDataPicker_EditIcon(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getDataPicker_OkBtn(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getDataPicker_CancelBtn(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getDataPicker_CalendarIcon(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getDataPicker_DateTxtFld(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getIncomeScreen_AlertToastMsg(WebDriver dr, String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getIncomeScreen_NavigateUpBtn(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getIncomeScreen_Title(WebDriver dr, String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getIncomeScreen_RepeatBtn(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getIncomeScreen_DatePicker(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getIncomeScreen_CurrencyIcon(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getIncomeScreen_CurrencyTxt(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getIncomeScreen_PaymentMethod(WebDriver dr, String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getIncomeScreen_AmtTxtFld(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getIncomeScreen_KeyboardClearBtn(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getIncomeScreen_NoteTxtFld(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getIncomeScreen_KeyboardBtn(WebDriver dr, String value) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getIncomeScreen_ChooseCategoryBtn(WebDriver dr) {
// TODO Auto-generated method stub
return null;
}
@Override
public WebElement getIncomeScreen_CategoryBtn(WebDriver dr, String value) {
// TODO Auto-generated method stub
return null;
}
}
<file_sep>/monefy_automation/src/test/java/com/monefy/app/lite/scenarios/IncomeScenarioTest.java
/**
* @author sunil_s
* @created on 06/26/2021
* @description Class containing Test Scripts for Income Charter
*/
package com.monefy.app.lite.scenarios;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.logging.Level;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.logging.LogEntry;
import org.testng.Assert;
import org.testng.ITestResult;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.monefy.app.lite.common.DriverSetup;
import com.monefy.app.lite.dataprovider.IncomeDP;
import com.monefy.app.lite.objectrepo.BaseObjRepo;
import com.monefy.app.lite.pages.IncomePage;
public class IncomeScenarioTest extends DriverSetup {
String platFormName, logFilePath;
@BeforeMethod
public void setUp() throws Exception {
driverSet();
platFormName = DriverSetup.getPlatform();
logFilePath = DriverSetup.getLogfilePath();
}
@AfterMethod
public void tearDown(ITestResult result) throws Exception {
try {
if (!result.isSuccess()) {
SimpleDateFormat formater = new SimpleDateFormat("ddMMyyyy_HHmmss");
Calendar calendar = Calendar.getInstance();
String classname1 = this.getClass().getName();
int clsname2 = classname1.lastIndexOf('.') + 1;
String className = classname1.substring(clsname2);
String methodName = result.getName();
String parameter = String.format("TestNG Debugger : %s() running with parameters %s.",
result.getMethod().getConstructorOrMethod().getName(), Arrays.toString(result.getParameters()));
System.out.println("parameter: " + parameter);
String tcName = parameter.substring(parameter.indexOf("[") + 1, parameter.indexOf("[") + 6);
// To capture the screenshot for the failure case(s)
File scrFile = ((TakesScreenshot) getDriver()).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File((logFilePath + className + "_" + methodName + "_"
+ tcName + "_" + formater.format(calendar.getTime()) + ".png")));
if ("ANDROID".equalsIgnoreCase(platFormName)) {
// To capture the logs for the failure case(s)
System.out.println("Saving device log - start");
List<LogEntry> logEntries = getDriver().manage().logs().get("logcat").filter(Level.ALL);
File logFile = new File(logFilePath + className + "_" + methodName + "_" + tcName + "_"
+ formater.format(calendar.getTime()) + ".txt");
@SuppressWarnings("resource")
PrintWriter log_file_writer = new PrintWriter(logFile);
for (LogEntry logEntry : logEntries) {
if (logEntry.getMessage().toLowerCase().contains("com.monefy.app.lite")) {
log_file_writer.println(logEntry);
log_file_writer.flush();
}
}
System.out.println("Saving device log - finish");
}
}
// getDriver().quit();
} catch (IOException e1) {
e1.printStackTrace();
}
}
@AfterClass
public void suiteTearDown() throws Exception {
getDriver().quit();
}
/**
* @author sunil_s
* @description Test Method to verify income screen
* @param TC
*/
@Test(description = "Test to verify Income Screen", dataProvider = "IncomeScreenValidations", dataProviderClass = IncomeDP.class)
public void verifyIncomeScreen(String TC, String ActResult, String ExpResult) {
try {
BaseObjRepo baseOR = getSetupor().getbaseobjrep();
WebDriver dr = getDriver();
printTestScriptExecutionInfo(TC);
IncomePage page = new IncomePage();
Assert.assertTrue(page.IncomeScreenValidations(TC,dr, baseOR,ActResult,ExpResult));
} catch (Exception e) {
e.printStackTrace();
Assert.assertTrue(false);
}
}
/**
* @author sunil_s
* @description Test Method to verify repeat button click functionality
* @param TC
*/
@Test(description = "Test to verify repeat button click functionality", dataProvider = "IncomeScreen_RepeatButtonFunctionality", dataProviderClass = IncomeDP.class)
public void verifyIncomeScreen_RepeatButtonFunctionality(String TC, String ActResult, String ExpResult) {
try {
BaseObjRepo baseOR = getSetupor().getbaseobjrep();
WebDriver dr = getDriver();
printTestScriptExecutionInfo(TC);
IncomePage page = new IncomePage();
Assert.assertTrue(page.IncomeScreen_RepeatButtonFunctionality(TC,dr, baseOR,ActResult,ExpResult));
} catch (Exception e) {
e.printStackTrace();
Assert.assertTrue(false);
}
}
/**
* @author sunil_s
* @description Test Method to verify date picker functionality
* @param TC
*/
@Test(description = "Test to verify date picker functionality", dataProvider = "IncomeScreen_DatePickerFunctionality", dataProviderClass = IncomeDP.class)
public void verifyIncomeScreen_DatePickerFunctionality(String TC, String ActResult, String ExpResult) {
try {
BaseObjRepo baseOR = getSetupor().getbaseobjrep();
WebDriver dr = getDriver();
printTestScriptExecutionInfo(TC);
IncomePage page = new IncomePage();
Assert.assertTrue(page.IncomeScreen_DatePickerFunctionality(TC,dr, baseOR,ActResult,ExpResult));
} catch (Exception e) {
e.printStackTrace();
Assert.assertTrue(false);
}
}
/**
* @author sunil_s
* @description Test Method to verify date picker functionality
* @param TC
*/
@Test(description = "Test to verify change payment method", dataProvider = "IncomeScreen_ChangePaymentMethod", dataProviderClass = IncomeDP.class)
public void verifyIncomeScreen_ChangePaymentMethod(String TC, String ActResult, String ExpResult) {
try {
BaseObjRepo baseOR = getSetupor().getbaseobjrep();
WebDriver dr = getDriver();
printTestScriptExecutionInfo(TC);
IncomePage page = new IncomePage();
Assert.assertTrue(page.IncomeScreen_ChangePaymentMethod(TC,dr, baseOR,ActResult,ExpResult));
} catch (Exception e) {
e.printStackTrace();
Assert.assertTrue(false);
}
}
/**
* @author sunil_s
* @description Test Method to verify amount input field functionality
* @param TC
*/
@Test(description = "Test to verify amount input field functionality", dataProvider = "IncomeScreen_AmountInputFieldFunctionality", dataProviderClass = IncomeDP.class)
public void verifyIncomeScreen_AmountInputFieldFunctionality(String TC, String ActResult, String ExpResult) {
try {
BaseObjRepo baseOR = getSetupor().getbaseobjrep();
WebDriver dr = getDriver();
printTestScriptExecutionInfo(TC);
IncomePage page = new IncomePage();
Assert.assertTrue(page.IncomeScreen_AmountInputFieldFunctionality(TC,dr, baseOR,ActResult,ExpResult));
} catch (Exception e) {
e.printStackTrace();
Assert.assertTrue(false);
}
}
/**
* @author sunil_s
* @description Test Method to verify undo added expenses
* @param TC
*/
@Test(description = "Test to verify undo added expense", dataProvider = "IncomeScreen_UndoAddedIncome", dataProviderClass = IncomeDP.class)
public void verifyIncomeScreen_UndoAddedIncome(String TC, String ActResult, String ExpResult) {
try {
BaseObjRepo baseOR = getSetupor().getbaseobjrep();
WebDriver dr = getDriver();
printTestScriptExecutionInfo(TC);
IncomePage page = new IncomePage();
Assert.assertTrue(page.IncomeScreen_UndoAddedIncome(TC,dr, baseOR,ActResult,ExpResult));
} catch (Exception e) {
e.printStackTrace();
Assert.assertTrue(false);
}
}
}
<file_sep>/monefy_automation/src/test/java/com/monefy/app/lite/dataprovider/ExpenseDP.java
package com.monefy.app.lite.dataprovider;
import org.testng.annotations.DataProvider;
import com.monefy.app.lite.common.CommonCV;
import com.monefy.app.lite.common.DriverSetup;
public class ExpenseDP extends CommonCV {
public static String platFormName = DriverSetup.getPlatform();
// Test Data to verify Home Screen Validations
@DataProvider(name = "HomeScreenValidations")
public static Object[][] HomeScreenValidations() {
return new Object[][] { { "TC_01",month,
"Open navigation|Monefy|All accounts|Search records|Transfer|Settings|$0.00|Balance $0.00|INCOME|EXPENSE",
"Open navigation|Monefy|All accounts|Search records|Transfer|Settings|$0.00|Balance $0.00|INCOME|EXPENSE" } };
}
// Test Data to verify Expense Screen Validations
@DataProvider(name = "ExpenseScreenValidations")
public static Object[][] ExpenseScreenValidations() {
return new Object[][] { { "TC_01", "Recurring records are now available in Monefy Pro!|New expense|Repeat|USD|Note|CHOOSE CATEGORY",
"Recurring records are now available in Monefy Pro!|New expense|Repeat|USD|Note|CHOOSE CATEGORY" } };
}
// Test Data to verify Expense Screen - Repeat Button Functionality
@DataProvider(name = "ExpenseScreen_RepeatButtonFunctionality")
public static Object[][] ExpenseScreen_RepeatButtonFunctionality() {
return new Object[][] { { "TC_01", "New expense|Repeat",
"New expense|Monefy Pro|Buy|Pro Features|Recurring Records|Multi-Currency|Synchronization|Passcode Protection" } };
}
// Test Data to verify Expense Screen - Date Picker Functionality
@DataProvider(name = "ExpenseScreen_DatePickerFunctionality")
public static Object[][] ExpenseScreen_DatePickerFunctionality() {
return new Object[][] { { "TC_01", "New expense|SELECT DATE", "New expense|SELECT DATE" } };
}
// Test Data to verify Expense Screen - Change Payment Method
@DataProvider(name = "ExpenseScreen_ChangePaymentMethod")
public static Object[][] ExpenseScreen_ChangePaymentMethod() {
return new Object[][] { { "TC_01", "New expense|USD|Payment card|Cash", "New expense|USD|Payment card|Cash" },
{ "TC_02", "New expense|USD|Payment card|Cash", "New expense|USD|Payment card|Cash" } };
}
// Test Data to verify Expense Screen - Amount Input Field Functionality
@DataProvider(name = "ExpenseScreen_AmountInputFieldFunctionality")
public static Object[][] ExpenseScreen_AmountInputFieldFunctionality() {
return new Object[][] { { "TC_01", "New expense|100|×|10|=", "New expense|1000|0" },
{ "TC_02", "New expense|800|+|200|=", "New expense|1000|0" },
{ "TC_03", "New expense|1200|-|200|=", "New expense|1000|0" },
{ "TC_04", "New expense|10000|÷|10|=", "New expense|1000|0" }};
}
// Test Data to verify Expense Screen - Undo Added Expense
@DataProvider(name = "ExpenseScreen_UndoAddedExpense")
public static Object[][] ExpenseScreen_UndoAddedExpense() {
return new Object[][] { { "TC_01", "New expense|100|×|10|=|Test Note Input Functionality|Bills",
"New expense|1000|Test Note Input Functionality|Bills: $1,000.00 added|$1,000.00|Balance -$1,000.00|$0.00|Balance $0.00" } };
}
// Test Data to verify Expense Screen - Adding I
@DataProvider(name = "ExpenseScreen_AddingIncome")
public static Object[][] ExpenseScreen_AddingIncome() {
return new Object[][] { { "TC_01", "New income|SELECT DATE|100|×|10|=|Test Note Input Functionality|Bills",
"New income|SELECT DATE|1000|Test Note Input Functionality|Bills: $1,000.00 added|$1,000.00|Balance $9,000.00" } };
}
}
<file_sep>/monefy_automation/src/main/java/com/monefy/app/lite/objectrepo/BaseObjRepo.java
/**
* @author sunil_s
* @created on 06/26/2021
* @description Class containing declarations of Locator Elements
*/
package com.monefy.app.lite.objectrepo;
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public abstract class BaseObjRepo {
// Locators of Home Scren
public abstract WebElement getHomeScreen_OpenNavigationBtn(WebDriver dr, String value);
public abstract WebElement getHomeScreen_HomeScreenTitle(WebDriver dr, String value);
public abstract WebElement getHomeScreen_AllAccountsTxt(WebDriver dr, String value);
public abstract WebElement getHomeScreen_SearchBtn(WebDriver dr, String value);
public abstract WebElement getHomeScreen_TransferBtn(WebDriver dr, String value);
public abstract WebElement getHomeScreen_SettingsBtn(WebDriver dr, String value);
public abstract WebElement getHomeScreen_MonthTxt(WebDriver dr, String value);
public abstract WebElement getHomeScreen_IncomeAmtTxt(WebDriver dr);
public abstract WebElement getHomeScreen_ExpenseAmtTxt(WebDriver dr);
public abstract WebElement getHomeScreen_BalanceAmtTxt(WebDriver dr);
public abstract WebElement getHomeScreen_ExpenseBtn(WebDriver dr);
public abstract WebElement getHomeScreen_IncomeBtn(WebDriver dr);
public abstract WebElement getHomeScreen_BillsToastMsg(WebDriver dr);
public abstract WebElement getHomeScreen_CancelButton(WebDriver dr);
// Locator of Expense Module
public abstract WebElement getExpenseScreen_AlertToastMsg(WebDriver dr,String value);
public abstract WebElement getExpenseScreen_NavigateUpBtn(WebDriver dr);
public abstract WebElement getExpenseScreen_Title(WebDriver dr,String value);
public abstract WebElement getExpenseScreen_RepeatBtn(WebDriver dr);
public abstract WebElement getExpenseScreen_DatePicker(WebDriver dr);
public abstract WebElement getExpenseScreen_CurrencyIcon(WebDriver dr);
public abstract WebElement getExpenseScreen_CurrencyTxt(WebDriver dr);
public abstract WebElement getExpenseScreen_PaymentMethod(WebDriver dr,String value);
public abstract WebElement getExpenseScreen_AmtTxtFld(WebDriver dr);
public abstract WebElement getExpenseScreen_KeyboardClearBtn(WebDriver dr);
public abstract WebElement getExpenseScreen_NoteTxtFld(WebDriver dr);
public abstract WebElement getExpenseScreen_KeyboardBtn(WebDriver dr,String value);
public abstract WebElement getExpenseScreen_ChooseCategoryBtn(WebDriver dr);
public abstract WebElement getExpenseScreen_CategoryBtn(WebDriver dr, String value);
// Locators of Moenfy Pro Screen
public abstract WebElement getMonefyProScreen_Title(WebDriver dr);
public abstract WebElement getMonefyProScreen_BuyBtn(WebDriver dr);
public abstract WebElement getMonefyProScreen_ProFeaturesTxt(WebDriver dr);
public abstract List<WebElement> getMonefyProScreen_ProFeatureList(WebDriver dr);
// Locators of Date Picker
public abstract WebElement getDatePicker_SelectDateTxt(WebDriver dr);
public abstract WebElement getDatePicker_DateTxt(WebDriver dr);
public abstract WebElement getDataPicker_EditIcon(WebDriver dr);
public abstract WebElement getDataPicker_OkBtn(WebDriver dr);
public abstract WebElement getDataPicker_CancelBtn(WebDriver dr);
public abstract WebElement getDataPicker_CalendarIcon(WebDriver dr);
public abstract WebElement getDataPicker_DateTxtFld(WebDriver dr);
// Locator of Income Module
public abstract WebElement getIncomeScreen_AlertToastMsg(WebDriver dr, String value);
public abstract WebElement getIncomeScreen_NavigateUpBtn(WebDriver dr);
public abstract WebElement getIncomeScreen_Title(WebDriver dr, String value);
public abstract WebElement getIncomeScreen_RepeatBtn(WebDriver dr);
public abstract WebElement getIncomeScreen_DatePicker(WebDriver dr);
public abstract WebElement getIncomeScreen_CurrencyIcon(WebDriver dr);
public abstract WebElement getIncomeScreen_CurrencyTxt(WebDriver dr);
public abstract WebElement getIncomeScreen_PaymentMethod(WebDriver dr, String value);
public abstract WebElement getIncomeScreen_AmtTxtFld(WebDriver dr);
public abstract WebElement getIncomeScreen_KeyboardClearBtn(WebDriver dr);
public abstract WebElement getIncomeScreen_NoteTxtFld(WebDriver dr);
public abstract WebElement getIncomeScreen_KeyboardBtn(WebDriver dr, String value);
public abstract WebElement getIncomeScreen_ChooseCategoryBtn(WebDriver dr);
public abstract WebElement getIncomeScreen_CategoryBtn(WebDriver dr, String value);
}
<file_sep>/monefy_automation/src/main/java/com/monefy/app/lite/common/CommonCV.java
/**
* @author sunil_s
* @created on 06/26/2021
* @description Class containing common validations
*/
package com.monefy.app.lite.common;
import java.time.LocalDate;
public class CommonCV {
// Validations on Home Menu
public static String hamburger_menu = "Open navigation";
public static String title = "Monefy";
public static String income = "INCOME";
public static String expense = "EXPENSE";
public static String transfer = "Transfer";
public static String settings = "Settings";
public static String search = "Search records";
static String getMonth = LocalDate.now().getMonth().toString();
public static String month = getMonth.charAt(0) + getMonth.substring(1 ).toLowerCase();
//Validations on Expense Menu
public static String newExpense = "New expense";
public static String repeat = "Repeat";
public static String chooseCategory = "CHOOSE CATEGORY";
public static String note = "Note";
public static String usd = "USD";
}
|
e07d5f7b04e3b399e9be700024dc0363adcc951a
|
[
"Markdown",
"Java"
] | 8 |
Java
|
ssunil007/SUNIL-SREENIVASA
|
e85a6212022573fdf11c195a4a3284c528efe8ef
|
40c4d94041e4fd6d74713f46533bd1fdbf7e1625
|
refs/heads/master
|
<repo_name>Gvo3d/http_site_parser<file_sep>/README.md
ABOUTYOU PARSER
by <NAME>
<EMAIL>
11.10.2017
Target site: https://www.aboutyou.de
Manual test:
You can test algoritm manually, by accessing link: https://www.aboutyou.de/suche?term=Premium&category=138113
for now it has a 18 products.
Valid command for starting algoritm:
java -jar parser.jar Premium&category=138113
Launch:
You can launch parser in two algoritm variants - keyword search and full site map.
Second one will make the full site map, choose all products from that data and will save that info in file, but full site map may cost to you some memory, so I suggest you to launch parser that way with key: -Xmx4096M.
To launch parser in second modem just don't enter any keyword, or enter it like "".
Program options:
No. Type Description
0 (String) search keyword
1 (int) connection timeout
2 (int) request timeout
3 (int) socket timeout
4 (boolean) attach pretty headers
Software fetching data from site with multiple threads, writing memory usage, products and pages counters and elapsed time statistics. It uses one http request to get data for parsing and most of the data parsed from HTML code, only color parsed from JSON with page load data.
MultiThreading class - HttpDataFetcher, it simultaneously reads, parses data and collecting it in concurrent hash set. The count of threads that are working at a single time is up to your physical and virtual cores count;
P.S. If you have problems with socket timeout connection or else - add the custom timeouts like:
${searcheable} 8000 8000 8000 true
or for full algo:
"" 10000 10000 10000 true <file_sep>/src/main/java/algoritms/FullProductMapGenerator.java
package algoritms;
import connector.HttpRequestSender;
import models.Offer;
import models.SitePage;
import support.HttpDataFetcher;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class FullProductMapGenerator implements IProductMapGenerator {
private final static String FILE_NAME = "full_offers.xml";
private Set<SitePage> pagesSet;
private Integer connectionTimeout;
private Integer requestTimeout;
private Integer socketTimeout;
private AtomicInteger executedPages = new AtomicInteger();
private Map<String, String> headers = Collections.EMPTY_MAP;
public FullProductMapGenerator(Integer connectionTimeout, Integer requestTimeout, Integer socketTimeout) {
this.connectionTimeout = connectionTimeout;
this.requestTimeout = requestTimeout;
this.socketTimeout = socketTimeout;
pagesSet = ConcurrentHashMap.newKeySet();
}
@Override
public void generateSiteMap(String url) {
LOGGER.info("Generating first page from " + url);
preGenerateFirstPage(url, pagesSet, true);
Runtime rnt = Runtime.getRuntime();
int cpus = rnt.availableProcessors();
ExecutorService threadPool = Executors.newFixedThreadPool(cpus);
for (int i = 0; i < cpus; i++) {
HttpDataFetcher fetcher = new HttpDataFetcher("Thread_" + i, url, pagesSet, executedPages, getSender(), true, Thread.currentThread());
threadPool.execute(fetcher);
}
synchronized (Thread.currentThread()) {
try {
Thread.currentThread().wait();
} catch (InterruptedException e) {
threadPool.shutdown();
}
}
List<Offer> offers = getOffersList(this.pagesSet);
afterExecutionSerialization(offers, FILE_NAME);
}
@Override
public String getFirstFetchPrefix() {
return "";
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
@Override
public Map<String, String> getHeaders() {
return headers;
}
@Override
public HttpRequestSender getSender() {
return new HttpRequestSender(connectionTimeout, requestTimeout, socketTimeout);
}
@Override
public int incrementExecutedCounter() {
return executedPages.incrementAndGet();
}
@Override
public int getExecutedCounter() {
return executedPages.get();
}
}<file_sep>/src/main/java/parsers/DataParser.java
package parsers;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.stream.JsonReader;
import models.DescriptionData;
import models.Offer;
import models.SitePage;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.StringReader;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class DataParser {
private final static String PRODUCT_NAME_PREFIX = "/p/";
private final static String PRODUCT_ENDING_REGEX = ".*\\d$";
private final static List<String> notLinkStartsRules = new ArrayList<>(4);
private final static List<String> notLinkEqualsRules = new ArrayList<>(1);
private final static List<String> notLinkEndsRules = new ArrayList<>(2);
private final static List<String> notLinkMatchesRules = new ArrayList<>(2);
private StringLengthComparator comparator;
private final ColorJsonSearcher searcher;
public DataParser() {
comparator = new StringLengthComparator();
searcher = new ColorJsonSearcher();
notLinkStartsRules.add("//");
notLinkStartsRules.add("http");
notLinkStartsRules.add("www");
notLinkStartsRules.add("mailto");
notLinkEqualsRules.add("/");
notLinkEndsRules.add(".css");
notLinkEndsRules.add(".js");
notLinkMatchesRules.add(".*#.*");
}
public boolean hasAProduct(String pageName) {
return pageName.startsWith(PRODUCT_NAME_PREFIX) && pageName.matches(PRODUCT_ENDING_REGEX);
}
public List<SitePage> getAllUrls(String page) {
Document doc = Jsoup.parse(page);
Elements links = doc.select("a[href]");
List<SitePage> pages = new ArrayList<>();
links.eachAttr("href").stream().filter(this::check).forEach(x -> pages.add(new SitePage(x)));
return pages;
}
public List<SitePage> getKeywordSpecificUrls(String page) {
Document doc = Jsoup.parse(page);
Elements links = doc.select("div[class*=row list-wrapper product-image-list]").select("div[class*=col-xs-4 isLayout]");
List<SitePage> pages = new ArrayList<>();
links.select("div[class*=product-image] a[href]").eachAttr("href").stream().filter(this::check).forEach(x -> pages.add(new SitePage(x)));
links = doc.select("ul[id*=pl-pager-bottom]").select("li[class=page]");
links.select("a[href]").eachAttr("href").stream().filter(this::check).forEach(x -> pages.add(new SitePage(x)));
return pages;
}
private boolean check(String o) {
for (String rule : notLinkStartsRules) {
if (o.startsWith(rule)) {
return false;
}
}
for (String rule : notLinkEqualsRules) {
if (o.equals(rule)) {
return false;
}
}
for (String rule : notLinkEndsRules) {
if (o.endsWith(rule)) {
return false;
}
}
for (String rule : notLinkMatchesRules) {
if (o.matches(rule)) {
return false;
}
}
return true;
}
public Offer getProductData(String page) {
try {
Document doc = Jsoup.parse(page);
Elements elements = doc.getElementsByClass("container");
Offer offer = new Offer();
String[] brandAndName = getBrandAndName(doc);
offer.setBrand(brandAndName[0]);
offer.setName(brandAndName[1]);
Element initialPrice = elements.select("span[class*=finalPrice]").select("span[class*=from]").first();
offer.setInitialPrice(initialPrice != null ? initialPrice.text() : "");
offer.setPrice(getPrice(elements));
offer.setArticleId(getArticle(elements));
offer.setColor(getColor(doc.children()));
offer.setSizes(getSizes(elements));
offer.setShippingCosts(getShippingCost(elements));
offer.setDescription(getDescription(elements));
return offer;
} catch (NullPointerException e) {
return null;
}
}
private String[] getBrandAndName(Document doc){
Element elem = doc.getElementsByClass("container").select("h1[class*=productName]").first();
if (elem!=null) {
return elem.text().split(" \\| ");
} else {
elem = doc.getElementById("app");
Elements elements1 = elem.select("section[class*=layout]").select("div[data-reactid=576]");
elem = elements1.last();
elements1 = elem.select("div div div[class*=outerWrapper]").select("h1[class*=productName]");
elem = elements1.first();
return elem.text().split(" \\| ");
}
}
private String getPrice(Elements elements) {
String result = null;
Element priceElement = elements.select("span[class*=finalPrice]").first();
if (priceElement.select("span:not([class])").first() != null) {
result = priceElement.select("span:not([class])").first().text();
} else {
result = priceElement.text();
}
if (elements.select("div[class*=tax]").first() != null) {
result = result + " " + elements.select("div[class*=tax]").first().text();
}
return result;
}
private String getArticle(Elements elements) {
List<String> result = elements.select("div[class*=container]").stream().filter(x -> x.hasText() && x.text().contains("Artikel-Nr: ")).map(Element::text).collect(Collectors.toList());
return Stream.of(result.get(result.size() - 1).split("Artikel-Nr: ")).min(comparator).orElse("NONE");
}
private List<DescriptionData> getDescription(Elements elements) {
List<DescriptionData> result = new ArrayList<>();
for (Element element : elements.select("div[class*=wrapper]").select("div[class*=container]")) {
if (element.select("p[class*=subline]").first() != null) {
DescriptionData data = new DescriptionData(getSubline(element));
Element description = element.select("p[class*=productDescriptionText]").first();
if (description != null) {
data.setData(element.text());
} else {
data.setData(getAttributes(element.select("div[class*=attributeWrapper]").first()));
}
result.add(data);
}
Element materialContainer = element.select("div[class*=materialCareAttributeWrapper]").first();
if (materialContainer != null) {
DescriptionData data = new DescriptionData(getSubline(materialContainer));
data.setData(getAttributes(materialContainer.select("div[class*=materialAttributeWrapper] div").select("div").first()));
materialContainer = materialContainer.select("div[class*=careSymbolWrapper]").first();
if (materialContainer != null) {
data.addData(getSymbolAttributes(materialContainer));
}
result.add(data);
}
Element extrasWrapper = element.select("div[class*=extrasWrapper]").first();
if (extrasWrapper != null) {
DescriptionData data = new DescriptionData(getSubline(extrasWrapper));
data.setData(getAttributes(extrasWrapper.select("div[class*=attributeWrapper]").first()));
result.add(data);
}
}
return result;
}
private String getColor(Elements elements) {
String color = "NO";
Elements colorElements = elements.select("script[charset=UTF-8]");
ListIterator<Element> iter = colorElements.listIterator(colorElements.size());
while (iter.hasPrevious()) {
Element element = iter.previous();
if (element.data().startsWith("window.__INITIAL_STATE__=")) {
JsonParser parser = new JsonParser();
JsonReader reader = new JsonReader(new StringReader(element.data().split("window.__INITIAL_STATE__=")[1]));
reader.setLenient(true);
try {
JsonObject o = parser.parse(reader).getAsJsonObject();
String temp = searcher.deserialize(o, null, null);
if (temp != null) {
color = temp;
}
} catch (IllegalStateException e) {
}
}
}
return color;
}
private List<String> getSizes(Elements elements) {
List<String> sizes = new ArrayList<>(8);
Elements sizesContainers = elements.select("div[class*=js-size-dropdown-wrapper wrapper]").select("div[class*=list]").select("div[data-reactid]");
Elements sizeData = sizesContainers.select("span:not([class*=disabled])").select("span[class*=paddingLeft]");
if (sizeData.isEmpty()) {
sizeData = sizesContainers.select("div[class*=row]");
for (Element element : sizeData) {
sizes.add(getSizeDataFromTable(element));
}
} else {
Iterator<Element> iter = sizeData.iterator();
while (iter.hasNext()) {
Element nextElement = iter.next();
sizes.add(nextElement.text());
}
}
return sizes.isEmpty() ? Collections.emptyList() : sizes;
}
private String getSizeDataFromTable(Element element) {
return element.children().eachText().stream().collect(Collectors.joining(" "));
}
private String getShippingCost(Elements elements) {
Elements shipping = elements.select("div[class*=promises]").select("div[class*=headline]");
return shipping.eachText().stream().filter(x -> !x.matches("Kauf auf Rechnung")).collect(Collectors.joining(", "));
}
private String getSubline(Element parentElement) {
String text = null;
try {
text = parentElement.select("p[class*=subline]").first().text();
} catch (NullPointerException e) {
text = "Extras";
}
return text;
}
private List<String> getAttributes(Element element) {
Elements attrWrapper = element.select("ul[class*=orderedList] div li");
if (attrWrapper.isEmpty()) {
attrWrapper = element.select("ul[class*=orderedList] div ");
}
if (attrWrapper.isEmpty()) {
attrWrapper = element.select("ul[class*=orderedList] li ");
}
List<String> data = new ArrayList<>(10);
for (Element listElement : attrWrapper) {
data.add(listElement.text());
}
return data;
}
private List<String> getSymbolAttributes(Element element) {
return element.select("div[class*=tooltip careSymbols]").eachText();
}
private class StringLengthComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
return Integer.compare(o1.length(), o2.length());
}
}
}
<file_sep>/src/main/java/support/HttpDataFetcher.java
package support;
import connector.HttpRequestSender;
import models.Offer;
import models.SitePage;
import org.apache.log4j.Logger;
import parsers.DataParser;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
public class HttpDataFetcher implements Runnable {
private final static Logger LOGGER = Logger.getLogger(HttpDataFetcher.class);
private Set<SitePage> pagesSet;
private HttpRequestSender sender;
private DataParser parser = new DataParser();
private AtomicInteger executed;
private String name;
private String urlPrefix;
private boolean fetchAllLinks;
private Thread parent;
public HttpDataFetcher(String name, String urlPrefix, Set<SitePage> pagesSet, AtomicInteger executed, HttpRequestSender sender, boolean fetchAllLinks, Thread parent) {
this.urlPrefix = urlPrefix;
this.name = name;
this.executed = executed;
this.pagesSet = pagesSet;
this.sender = sender;
this.fetchAllLinks = fetchAllLinks;
this.parent = parent;
}
@Override
public void run() {
Thread.currentThread().setName(name);
LOGGER.info(Thread.currentThread().getName() + " has started.");
while (executed.get() < pagesSet.size()) {
Iterator<SitePage> iterator = pagesSet.iterator();
while (iterator.hasNext()) {
SitePage page = iterator.next();
ReentrantLock lock = page.getLock();
if (lock.tryLock()) {
if (!page.isFetched()) {
String result = sender.doRequest(urlPrefix + page.getUrl()).get();
boolean isAProduct = parser.hasAProduct(page.getUrl());
if (isAProduct) {
Offer offer = parser.getProductData(result);
if (offer!=null) {
page.setOffer(offer);
} else {
LOGGER.info("Not a valid product: "+page.getUrl());
}
}
if (fetchAllLinks) {
pagesSet.addAll(parser.getAllUrls(result));
} else {
if (page.getOffer() == null) {
pagesSet.addAll(parser.getKeywordSpecificUrls(result));
}
}
page.setFetched(true);
executed.incrementAndGet();
LOGGER.info(Thread.currentThread().getName() + " fetched " + (isAProduct ? "product:" : "page :") + page.getUrl());
} else {
lock.unlock();
}
}
}
}
if (executed.get() > pagesSet.size()) {
synchronized (parent) {
parent.interrupt();
}
}
LOGGER.info(Thread.currentThread().getName() + " has ended.");
}
}
<file_sep>/src/main/java/ParserInitializer.java
import algoritms.IProductMapGenerator;
import algoritms.KeywordProductMapGenerator;
import org.apache.log4j.Logger;
import algoritms.FullProductMapGenerator;
import support.TimeChecker;
import java.util.HashMap;
import java.util.Map;
public class ParserInitializer {
private final static Logger LOGGER = Logger.getLogger(ParserInitializer.class);
private final static int DEFAULT_CONNECTION_TIMEOUT = 2000;
private final static int DEFAULT_REQUEST_TIMEOUT = 2000;
private final static int DEFAULT_SOCKET_TIMEOUT = 2000;
private static final long MEGABYTE = 1024L * 1024L;
public static void main(String[] args) {
IProductMapGenerator generator;
String algo;
int connectionTimeout = getIntArgument(args, 1, DEFAULT_CONNECTION_TIMEOUT);
int requestTimeout = getIntArgument(args, 2, DEFAULT_REQUEST_TIMEOUT);
int socketTimeout = getIntArgument(args, 3, DEFAULT_SOCKET_TIMEOUT);
boolean usePrettyHeaders = getBooleanArgument(args, 4);
if (args.length == 0 || args[0].length() == 0 || args[0].equals("")) {
algo = "full site map";
generator = new FullProductMapGenerator(connectionTimeout, requestTimeout, socketTimeout);
} else {
String keyword = args[0];
algo = "keyword search: " + args[0];
;
generator = new KeywordProductMapGenerator(keyword, connectionTimeout, requestTimeout, socketTimeout);
}
if (usePrettyHeaders) {
Map<String, String> headers = new HashMap<>();
headers.put("User-Agent", "User-Agent: Mozilla/5.0 (X11; Linux i686; rv:2.0.1) Gecko/20100101 Firefox/4.0.1");
generator.setHeaders(headers);
}
TimeChecker checker = new TimeChecker();
LOGGER.info("Starting algoritm: " + algo);
printMemory();
generator.generateSiteMap("https://www.aboutyou.de");
LOGGER.info("Generation has been finished in "+checker.doCheck()+" ms.");
printMemory();
}
private static void printMemory(){
Runtime runtime = Runtime.getRuntime();
long memory = runtime.totalMemory() - runtime.freeMemory();
LOGGER.info("Used memory is megabytes: " + bytesToMegabytes(memory));
}
public static long bytesToMegabytes(long bytes) {
return bytes / MEGABYTE;
}
private static int getIntArgument(String[] arguments, int number, int defaultValue) {
int result;
try {
result = Integer.parseInt(arguments[number]);
} catch (NumberFormatException e) {
LOGGER.warn("Argument " + arguments[number] + " is not a valid integer value, using default: " + defaultValue);
return defaultValue;
} catch (ArrayIndexOutOfBoundsException e) {
LOGGER.warn("No integer argument with index: " + number);
return defaultValue;
}
return result>999?result:defaultValue;
}
private static boolean getBooleanArgument(String[] arguments, int number) {
boolean result;
try {
result = arguments[number] != null && Boolean.parseBoolean(arguments[number]);
} catch (NumberFormatException e) {
LOGGER.warn("Argument " + arguments[number] + " is not a valid boolean value, using default false value");
return false;
} catch (ArrayIndexOutOfBoundsException e) {
LOGGER.warn("No boolean argument with index: " + number);
return false;
}
return result;
}
}
<file_sep>/src/main/java/connector/HttpRequestSender.java
package connector;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;
import java.util.Optional;
public class HttpRequestSender {
private final static Logger LOGGER = Logger.getLogger(HttpRequestSender.class);
private HttpClient client = HttpClientBuilder.create().disableAutomaticRetries().build();
private RequestConfig config;
private Header[] headers;
public HttpRequestSender(Integer connectionTimeout, Integer requestTimeout, Integer socketTimeout) {
this.config = RequestConfig.custom()
.setConnectTimeout(connectionTimeout)
.setConnectionRequestTimeout(requestTimeout)
.setSocketTimeout(socketTimeout)
.build();
}
public void setHeaders(Map<String, String> headers) {
if (headers != null) {
this.headers = new Header[headers.size()];
int i = 0;
for (Map.Entry<String, String> header : headers.entrySet()) {
this.headers[i] = new BasicHeader(header.getKey(), header.getValue());
i++;
}
}
}
public Optional<String> doRequest(String url) {
HttpGet httpRequest = new HttpGet(url);
httpRequest.setHeaders(headers);
httpRequest.setConfig(config);
HttpResponse response = null;
try {
response = client.execute(httpRequest);
} catch (ClientProtocolException e) {
LOGGER.error("Please check internet connection:", e);
} catch (IOException e) {
LOGGER.error("Something went wrong:", e);
}
return deserializeResponse(response);
}
private Optional<String> deserializeResponse(HttpResponse response) {
StringBuilder result = null;
try {
int size = response.getEntity().getContentLength() > 0 ? Math.toIntExact(response.getEntity().getContentLength()) : 1000;
result = new StringBuilder(size);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
} catch (IOException e) {
LOGGER.error("Can't reade response object:", e);
}
EntityUtils.consumeQuietly(response.getEntity());
return Optional.ofNullable(result.toString());
}
}
<file_sep>/src/main/java/models/Offer.java
package models;
import java.util.List;
public class Offer {
private String brand;
private String name;
private String color;
private String price;
private List<String> sizes;
private String initialPrice;
private List<DescriptionData> description;
private String articleId;
private String shippingCosts;
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getPrice() {
return price;
}
public List<String> getSizes() {
return sizes;
}
public void setSizes(List<String> sizes) {
this.sizes = sizes;
}
public void setPrice(String price) {
this.price = price;
}
public String getInitialPrice() {
return initialPrice;
}
public void setInitialPrice(String initialPrice) {
this.initialPrice = initialPrice;
}
public List<DescriptionData> getDescription() {
return description;
}
public void setDescription(List<DescriptionData> description) {
this.description = description;
}
public void addDescriptionData(DescriptionData data) {
this.description.add(data);
}
public String getArticleId() {
return articleId;
}
public void setArticleId(String articleId) {
this.articleId = articleId;
}
public String getShippingCosts() {
return shippingCosts;
}
public void setShippingCosts(String shippingCosts) {
this.shippingCosts = shippingCosts;
}
@Override
public String toString() {
StringBuilder desr = new StringBuilder();
for (DescriptionData data : description) {
desr.append(data).append("\n");
}
return "Offer{" +
"brand='" + brand + '\'' +
", name='" + name + '\'' +
", color='" + color + '\'' +
", price='" + price + '\'' +
", initialPrice='" + initialPrice + '\'' +
", description='" + desr.toString() + '\'' +
", articleId='" + articleId + '\'' +
", sizes='" + sizes + '\'' +
", shippingCosts='" + shippingCosts + '\'' +
'}';
}
}
<file_sep>/src/test/java/HttpTest.java
import connector.HttpRequestSender;
import models.Offer;
import models.SitePage;
import org.apache.http.protocol.HTTP;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Node;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import parsers.DataParser;
import serializer.XmlSerializer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class HttpTest {
private static HttpRequestSender sender;
private static DataParser parser;
@Before
public void init() {
sender = new HttpRequestSender(1000, 1000, 1000);
parser = new DataParser();
}
@Test
public void sendRequest() {
String result = sender.doRequest("https://www.aboutyou.de/p/lacoste/t-shirt-mit-marken-emblem-3669296").get();
assertNotNull(result);
System.out.println(result);
}
@Test
public void getAllUrls() {
String result = sender.doRequest("https://www.aboutyou.de").get();
List<SitePage> urls = parser.getAllUrls(result);
assertNotNull(urls);
System.out.println("Urls list size: " + urls.size());
urls.forEach(System.out::println);
}
@Test
public void getSpecificUrls() {
int currentTimeProductsOfPage = 18;
String result = sender.doRequest("https://www.aboutyou.de/suche?term=Premium&category=138113").get();
List<SitePage> urls = parser.getKeywordSpecificUrls(result);
assertNotNull(urls);
System.out.println("Urls list size: " + urls.size());
assertEquals(currentTimeProductsOfPage, urls.size());
urls.forEach(System.out::println);
}
@Test
public void getOffer() {
String result = sender.doRequest("https://www.aboutyou.de/p/kangaroos/rundhalspullover-3519128").get();
Offer offer = parser.getProductData(result);
assertNotNull(offer);
System.out.println(offer);
}
@Test
public void writeOffers() {
String[] offersUrls = {"https://www.aboutyou.de/p/lacoste/t-shirt-mit-marken-emblem-3669296", "https://www.aboutyou.de/p/sheego-trend/jumpsuit-3290897", "https://www.aboutyou.de/p/jack-und-jones/wildleder-trucker-lederjacke-3622014"};
List<Offer> offers = new ArrayList<>(3);
for (String url : offersUrls) {
String result = sender.doRequest(url).get();
Offer offer = parser.getProductData(result);
offers.add(offer);
}
System.out.println("size:" + offers.size());
for (Offer offer : offers) {
System.out.println(offer);
}
XmlSerializer serializer = new XmlSerializer("test-offers.xml");
String fileName = serializer.write(offers);
assertNotNull(fileName);
System.out.println("Writed to " + fileName);
}
}
|
a07671a2865cd861cafcefc5cccb2906825d7132
|
[
"Markdown",
"Java"
] | 8 |
Markdown
|
Gvo3d/http_site_parser
|
c99512d5c2ffa98194c39c25320629e86ebc5d44
|
38510b9ae5c7f27d39115f90c2b080fb459e9867
|
refs/heads/master
|
<repo_name>tsungchh/GLTEST<file_sep>/MYMACRO.h
#ifndef MYMACRO_H
#define MYMACRO_H
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <string.h>
#define DEBUG_GL()\
{ \
GLenum err; \
while ((err = glGetError()) != GL_NO_ERROR) { \
printf("OpenGL error in %s:%d: %d\n", __FILE__, __LINE__, err); \
exit(0);\
} \
} \
#define PRINT_GLVERSION() \
{\
const GLubyte* openglVersion = glGetString(GL_VERSION); \
const GLubyte* shaderVersion = glGetString(GL_SHADING_LANGUAGE_VERSION); \
printf(" Opengl= %s, GLSL= %s\n", (char*)openglVersion, shaderVersion); \
}\
#define RANDOM random
#define ZERO_MEM(a) memset(a, 0, sizeof(a))
#define SAFE_DELETE(p) if(p) {delete p; p=NULL;}
#define ARRAY_SIZE_IN_ELEMENTS(a) (sizeof(a)/sizeof(a[0]))
#define INVALID_OGL_VALUE 0xffffffff
#define INVALID_UNIFORM_LOCATION oxffffffff
#define INVALID_MATERIAL 0xFFFFFFFF
#endif // MYMACRO_H
<file_sep>/texmatrix.h
#ifndef TEXMATRIX_H
#define TEXMATRIX_H
#include "patch.h"
class texMatrix
{
public:
texMatrix();
void draw();
private:
GLuint g_Texture0_ID;
Vertex_VT g_Quad[4];/*=
{
{{-1.5f, -1.5f, 0.0f}, {-1.0f, 2.0f}},
{{-0.1f, -1.5f, 0.0f}, { 2.0f, 2.0f}},
{{-1.5f, -0.1f, 0.0f}, {-1.0f,-1.0f}},
{{-0.1f, -0.1f, 0.0f}, { 2.0f,-1.0f}}
};*/
};
#endif // TEXMATRIX_H
<file_sep>/picktechnique.h
#ifndef PICKTECHNIQUE_H
#define PICKTECHNIQUE_H
#include "technique.h"
class pickTechnique : public technique
{
public:
pickTechnique();
~pickTechnique();
virtual bool init(QObject* parent);
void SetWVP(const QMatrix4x4 WVP);
void SetObjectIndex(uint ObjectIndex);
void DrawStartCB(uint DrawIndex);
private:
GLuint m_WVPLocation;
GLuint m_drawIndexLocation;
GLuint m_objectIndexLocation;
};
#endif // PICKTECHNIQUE_H
<file_sep>/widget.hpp
#ifndef WIDGET_H
#define WIDGET_H
//#include "patch.h"
#include "mesh.h"
#include "shadertest.h"
#include <QMatrix4x4>
#include "QGLShaderProgram"
#include "textest.h"
#include "rendertechnique.h"
class GLWidget;
class Subject;
class Observer;
#include <QGLWidget>
class Widget : public QGLWidget
{
Q_OBJECT
public:
Widget( const QGLFormat& format, QWidget* parent = 0 );
~Widget();
private slots:
void traslateTexCoor();
private:
QMatrix4x4 projection;
QMatrix4x4 view;
QMatrix4x4 model;
QMatrix4x4 texmatrix;
Mesh* myMesh;
//shadertest shader_test;
textest* myTexTest;
Subject* mySub;
/** Take care of matrix, lighting and shader settings. */
rendertechnique myTechnique;
QVector3D eye;
QVector3D center;
QVector3D g_up;
QPoint lastPos;
int xRot;
int yRot;
int zRot;
/** sensitifity of mouse */
double stepsize;
double scalefactor;
/** Events handeling functions */
void rotateBy(int xAngle, int yAngle, int zAngle);
void keyPressEvent(QKeyEvent*);
void mousePressEvent(QMouseEvent*);
void mouseMoveEvent(QMouseEvent*);
/** Setup model view and projection matrix */
void setupMatrix();
/** QTGLWidget callback functions */
void initializeGL();
void paintGL();
void resizeGL(int w, int h);
/** other draw functions */
void drawAxis();
// test
void drawTriangle();
};
#endif // WIDGET_H
<file_sep>/main.cpp
#include "widget.hpp"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGLFormat glFormat;
glFormat.setVersion( 4, 1 );
glFormat.setProfile( QGLFormat::CoreProfile ); // Requires >=Qt-4.8.0
glFormat.setSampleBuffers( true );
Widget w(glFormat);
w.resize(1000,1000);
w.show();
return a.exec();
}
<file_sep>/observer.cpp
#include "observer.h"
Observer::Observer(Subject* sub)
{
model = sub;
model->attach(this);
}
Observer::~Observer()
{
}
void Subject::attach(Observer* obs)
{
views.push_back(obs);
}
void Subject::notify()
{
for(size_t i=0; i<views.size(); ++i)
{
views[i]->update();
}
}
<file_sep>/observer.h
#ifndef OBSERVER_H
#define OBSERVER_H
#include <vector>
using namespace std;
class Subject;
class Observer
{
public:
Observer(Subject* sub);
~Observer();
virtual void update() = 0;
private:
Subject* model;
};
class Subject
{
public:
void attach(Observer *obs);
void notify();
private:
vector<Observer*> views;
};
#endif // OBSERVER_H
<file_sep>/pickingfbo.h
#ifndef PICKINGFBO_H
#define PICKINGFBO_H
#include"qgl.h"
class PickingFBO
{
public:
PickingFBO();
~PickingFBO();
/**
* Initiate frame buffer object which used to be renderd with Index info.
* And also initiate texture object which stored index info.
*/
bool init(unsigned int width, unsigned int height);
void enable();
void disable();
struct Pixelinfo {
float x;
float y;
float z;
};
Pixelinfo ReadPixel(unsigned int, unsigned int);
private:
// FBO
GLuint m_fbo;
// Two texture object, first used to store index. Second one used to store depth info.
GLuint m_pickingTexture;
GLuint m_depthTexture;
};
#endif // PICKINGFBO_H
<file_sep>/pickingfbo.cpp
#include "pickingfbo.h"
PickingFBO::PickingFBO(){
m_fbo = 0;
m_pickingTexture = 0;
m_depthTexture = 0;
}
PickingFBO::~PickingFBO() {
if (m_fbo != 0) {
glDeleteFramebuffers(1, &m_fbo);
}
if (m_pickingTexture != 0) {
glDeleteTextures(1, &m_pickingTexture);
}
if (m_depthTexture != 0) {
glDeleteTextures(1, &m_depthTexture);
}
}
bool PickingFBO::init(unsigned int width, unsigned int height){
//create frame buffer
glGenFramebuffers(1, &m_fbo);
glBindFramebuffer(GL_FRAMEBUFFER, m_fbo);
// Create texture object for the primitive infromation buffer
glGenFramebuffers(1, &m_pickingTexture);
glBindTexture(GL_TEXTURE_2D, m_pickingTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, width, height, 0, GL_RGB, GL_FLOAT, NULL);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE0, m_pickingTexture, 0);
// Create the texture object for the depth buffer
glGenTextures(1, &m_depthTexture);
glBindTexture(GL_TEXTURE_2D, m_depthTexture);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0, GL_DEPTH_COMPONENT, GL_FLOAT, NULL);
glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, m_depthTexture, 0);
glReadBuffer(GL_NONE);
glDrawBuffer(GL_COLOR_ATTACHMENT0);
// Verify that the FBO is correct
GLenum Status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (Status != GL_FRAMEBUFFER_COMPLETE) {
printf("FB error, status: 0x%x\n", Status);
return false;
}
// Restore the default framebuffer
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
return true;
}
void PickingFBO::enable(){
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, m_fbo);
}
void PickingFBO::disable(){
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
}
PickingFBO::Pixelinfo PickingFBO::ReadPixel(unsigned int x, unsigned int y) {
glBindFramebuffer(GL_READ_FRAMEBUFFER, m_fbo);
glReadBuffer(GL_COLOR_ATTACHMENT0);
Pixelinfo Pixel;
glReadPixels(x, y, 1, 1, GL_RGB, GL_FLOAT, &Pixel);
glReadBuffer(GL_NONE);
glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
return Pixel;
}
<file_sep>/patch.cpp
#include "patch.h"
#include "widget.hpp"
static inline void qSetColor(float colorVec[], QColor c)
{
colorVec[0] = c.redF();
colorVec[1] = c.greenF();
colorVec[2] = c.blueF();
colorVec[3] = c.alphaF();
}
void Geometry::loadArrays() const
{
glVertexPointer(3, GL_FLOAT, 0, vertices.constData());
glNormalPointer(GL_FLOAT, 0, normals.constData());
glColorPointer(4, GL_UNSIGNED_BYTE, 0, colors);
glTexCoordPointer(2, GL_FLOAT, sizeof(tex2d), &texCoor);
}
void Geometry::finalize()
{
// TODO: add vertex buffer uploading here
// Finish smoothing normals by ensuring accumulated normals are returned
// to length 1.0.
for (int i = 0; i < normals.count(); ++i)
normals[i].normalize();
}
void Geometry::appendSmooth(const QVector3D &a, const QVector3D &n, int from)
{
// Smooth normals are achieved by averaging the normals for faces meeting
// at a point. First find the point in geometry already generated
// (working backwards, since most often the points shared are between faces
// recently added).
int v = vertices.count() - 1;
for ( ; v >= from; --v)
if (qFuzzyCompare(vertices[v], a))
break;
if (v < from) {
// The vertex was not found so add it as a new one, and initialize
// its corresponding normal
v = vertices.count();
vertices.append(a);
normals.append(n);
} else {
// Vert found, accumulate normals into corresponding normal slot.
// Must call finalize once finished accumulating normals
normals[v] += n;
}
// In both cases (found or not) reference the vertex via its index
faces.append(v);
}
void Geometry::appendFaceted(const QVector3D &a, const QVector3D &n)
{
// Faceted normals are achieved by duplicating the vertex for every
// normal, so that faces meeting at a vertex get a sharp edge.
int v = vertices.count();
vertices.append(a);
normals.append(n);
faces.append(v);
}
Patch::Patch(Geometry *g)
: start(g->faces.count())
, count(0)
, initv(g->vertices.count())
, sm(Patch::Smooth)
, geom(g)
{
qSetColor(faceColor, QColor(Qt::darkGray));
}
void Patch::rotate(qreal deg, QVector3D axis)
{
mat.rotate(deg, axis);
}
void Patch::translate(const QVector3D &t)
{
mat.translate(t);
}
//! [2]
void Patch::draw() const
{
glPushMatrix();
glMultMatrixf(mat.constData());
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE, faceColor);
const GLushort *indices = geom->faces.constData();
glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_SHORT, indices + start);
glPopMatrix();
}
//! [2]
void Patch::addTri(const QVector3D &a, const QVector3D &b, const QVector3D &c, const QVector3D &n)
{
QVector3D norm = n.isNull() ? QVector3D::normal(a, b, c) : n;
if (sm == Smooth) {
geom->appendSmooth(a, norm, initv);
geom->appendSmooth(b, norm, initv);
geom->appendSmooth(c, norm, initv);
} else {
geom->appendFaceted(a, norm);
geom->appendFaceted(b, norm);
geom->appendFaceted(c, norm);
}
count += 3;
}
void Patch::addQuad(const QVector3D &a, const QVector3D &b, const QVector3D &c, const QVector3D &d)
{
QVector3D norm = QVector3D::normal(a, b, c);
if (sm == Smooth) {
addTri(a, b, c, norm);
addTri(a, c, d, norm);
} else {
// If faceted share the two common vertices
addTri(a, b, c, norm);
int k = geom->vertices.count();
geom->appendSmooth(a, norm, k);
geom->appendSmooth(c, norm, k);
geom->appendFaceted(d, norm);
count += 3;
}
}
void Patch::addtex2d(const tex2d &n) {
geom->texCoor.append(n);
}
void Patch::setColor(QColor c)
{
qSetColor(this->faceColor, c);
}
<file_sep>/picktechnique.cpp
#include "picktechnique.h"
pickTechnique::pickTechnique()
{
}
pickTechnique::~pickTechnique() {
}
bool pickTechnique::init(QObject* parent) {
myShader = new QOpenGLShaderProgram(parent);
myShader->addShaderFromSourceFile(QOpenGLShader::Vertex, "/Users/hsutsungchun/Desktop/QTGL/GL_2/vertex.vs");
myShader->addShaderFromSourceFile(QOpenGLShader::Fragment, "/Users/hsutsungchun/Desktop/QTGL/GL_2/fragment.fs");
myShader->link();
m_WVPLocation = myShader->uniformLocation("gWVP");
m_objectIndexLocation = myShader->uniformLocation("gObjectIndex");
m_drawIndexLocation = myShader->uniformLocation("gDrawIndex");
return true;
}
void pickTechnique::SetWVP(const QMatrix4x4 WVP){
glUniformMatrix4fv( m_WVPLocation, 1, GL_TRUE, WVP.constData() );
}
void pickTechnique::SetObjectIndex(uint ObjectIndex){
glUniform1ui(m_objectIndexLocation, ObjectIndex);
}
void pickTechnique::DrawStartCB(uint DrawIndex) {
glUniform1ui(m_drawIndexLocation, DrawIndex);
}
<file_sep>/technique.h
#ifndef TECHNIQUE_H
#define TECHNIQUE_H
#include "QOpenGLShaderProgram"
class technique
{
public:
technique();
virtual ~technique();
void Enable();
void Disable();
virtual bool init(QObject* parent)=0;
protected:
//virtual bool addShader(GLenum ShaderType, const char* Filename)=0;
QOpenGLShaderProgram* myShader;
};
#endif // TECHNIQUE_H
<file_sep>/shadertest.h
#ifndef SHADERTEST_H
#define SHADERTEST_H
#include "QOpenGLShaderProgram"
class shadertest
{
public:
shadertest();
void initialize(QObject*);
void render();
private:
QOpenGLShaderProgram * m_program;
GLuint m_posAttr;
GLuint m_colAttr;
GLuint m_matrixUniform;
};
#endif // SHADERTEST_H
<file_sep>/README.md
# GLTEST
Ju
<file_sep>/patch.h
#ifndef PATCH_H
#define PATCH_H
#include <QMatrix4x4>
#include <QVector3D>
#include <qmath.h>
#include <QtOpenGL>
struct Vertex_VT
{
float m_Position[3]; // 頂點位置
float m_Texcoord[2]; // 貼圖座標
float m_Normal[3]; // Normal Coordinates.
Vertex_VT() {
}
Vertex_VT(float pos[], float tex[], float nor[]) {
m_Position[0] = pos[0];
m_Position[1] = pos[1];
m_Position[2] = pos[2];
m_Texcoord[0] = tex[0];
m_Texcoord[1] = tex[1];
m_Normal[0] = nor[0];
m_Normal[1] = nor[1];
m_Normal[2] = nor[2];
}
void set(float pos[], float tex[], float nor[]) {
m_Position[0] = pos[0];
m_Position[1] = pos[1];
m_Position[2] = pos[2];
m_Texcoord[0] = tex[0];
m_Texcoord[1] = tex[1];
m_Normal[0] = nor[0];
m_Normal[1] = nor[1];
m_Normal[2] = nor[2];
}
};
struct Color {
unsigned char m_RGBA[4];
};
struct tex2d {
float coor[2];
};
//! [0]
struct Geometry
{
QVector<GLushort> faces;
QVector<QVector3D> vertices;
QVector<tex2d> texCoor;
QVector<QVector3D> normals;
//QVector<QVector4D> colors;
Color* colors;
void appendSmooth(const QVector3D &a, const QVector3D &n, int from);
void appendFaceted(const QVector3D &a, const QVector3D &n);
void finalize();
void loadArrays() const;
};
//! [0]
//! [1]
class Patch
{
public:
enum Smoothing { Faceted, Smooth };
Patch(Geometry *);
void setSmoothing(Smoothing s) { sm = s; }
void translate(const QVector3D &t);
void rotate(qreal deg, QVector3D axis);
void draw() const;
void addTri(const QVector3D &a, const QVector3D &b, const QVector3D &c, const QVector3D &n);
void addQuad(const QVector3D &a, const QVector3D &b, const QVector3D &c, const QVector3D &d);
void addtex2d(const tex2d &n);
void setColor(QColor c);
GLushort start;
GLushort count;
GLushort initv;
GLfloat faceColor[4];
QMatrix4x4 mat;
Smoothing sm;
Geometry *geom;
};
//! [1]
#endif // PATCH_H
<file_sep>/texture.cpp
/*
Copyright 2011 <NAME>
This program 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.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include "texture.h"
#include "MYMACRO.h"
Texture::Texture(GLenum TextureTarget, const std::string& FileName)
{
m_textureTarget = TextureTarget;
m_fileName = FileName;
// m_textureObj = 0;
}
bool Texture::Load()
{
if(!img.load(m_fileName.c_str())) {
printf("Texture path %s ERROR!\n", m_fileName.c_str());
return false;
}
QImage glimg = QGLWidget::convertToGLFormat(img);
DEBUG_GL();
glGenTextures(1, &m_textureObj);
DEBUG_GL();
glBindTexture(m_textureTarget, m_textureObj);
DEBUG_GL();
glTexImage2D(m_textureTarget, 0, GL_RGBA, glimg.size().width(), glimg.size().height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, glimg.bits());
DEBUG_GL();
// `設定顯示貼圖被縮小時使用線性內插 `
glTexParameterf(m_textureTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
// `設定顯示貼圖被放大時使用線性外插 `
glTexParameterf(m_textureTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
// GL_TEXTURE_WRAP_S `設定水平方向解讀模式`
glTexParameteri(m_textureTarget, GL_TEXTURE_WRAP_S, GL_REPEAT);
// GL_TEXTURE_WRAP_T `設定垂直方向解讀模式`
glTexParameteri(m_textureTarget, GL_TEXTURE_WRAP_T, GL_REPEAT);
glBindTexture(m_textureTarget, 0);
DEBUG_GL();
return true;
}
void Texture::Bind(GLenum TextureUnit)
{
DEBUG_GL();
glActiveTexture(TextureUnit);
DEBUG_GL();
glBindTexture(m_textureTarget, m_textureObj);
DEBUG_GL();
}
<file_sep>/multitex.h
#ifndef MULTITEX_H
#define MULTITEX_H
#include "patch.h"
class multiTex
{
public:
multiTex();
void draw();
private:
Vertex_VT g_Quad[4];/* =
{
{{-1.0f, -1.0f, 0.0f}, {0.0f, 1.0f}},
{{ 1.0f, -1.0f, 0.0f}, {1.0f, 1.0f}},
{{-1.0f, 1.0f, 0.0f}, {0.0f, 0.0f}},
{{ 1.0f, 1.0f, 0.0f}, {1.0f, 0.0f}}
};*/
GLuint g_Texture0_ID;
GLuint g_Texture1_ID;
};
#endif // MULTITEX_H
<file_sep>/solarsystem.h
#ifndef SOLARSYSTEM_H
#define SOLARSYSTEM_H
#include "patch.h"
const float PI = 3.14159;
const float PI_double = PI * 2.0f;
const float days_a_year = 365.0f;
const float days_a_month = 28.0f;
const float days_a_year_mercury = 88.0f;
const float days_a_year_venus = 224.7f;
const float sun_spin_x = 180.0f;
const float earth_to_sun_distance = 8.0f; // 地球離太陽的假設值
const float mercury_to_sun_distance = 3.0f; // 水星離太陽的假設值
const float venus_to_sun_distance = 5.0f; // 水星離太陽的假設值
const float moon_to_earth_distance = 2.0f; // 月球離地球的假設值
const float simulation_speed = 60.0f; // 1秒相當於60天
class solarsystem
{
public:
solarsystem();
void draw();
private:
Geometry* geom;
Patch* sun;
Patch* earth;
int g_iNumSphereVertices;
int g_iNumSphereTriangles;
int g_iNumSphereIndices;
bool CreateSphere(float radius, Patch* patch, Geometry* geom, float *color=NULL, int stacks = 20, int pieces = 20);
};
#endif // SOLARSYSTEM_H
<file_sep>/ToDo.txt
1. Observer pattern to render different object
api, init, render
<file_sep>/mesh.h
#ifndef MESH_H
#define MESH_H
#include <assimp/Importer.hpp>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
#include "pickingfbo.h"
#include "mathbase.h"
#include "observer.h"
using namespace std;
class Texture;
class Mesh : public Observer
{
struct Vertex_VT
{
float m_Position[3]; // 頂點位置
float m_Texcoord[2]; // 貼圖座標
float m_Normal[3]; // Normal Coordinates.
Vertex_VT() {}
Vertex_VT(float pos[], float tex[], float nor[]) {
m_Position[0] = pos[0];
m_Position[1] = pos[1];
m_Position[2] = pos[2];
m_Texcoord[0] = tex[0];
m_Texcoord[1] = tex[1];
m_Normal[0] = nor[0];
m_Normal[1] = nor[1];
m_Normal[2] = nor[2];
}
void set(float pos[], float tex[], float nor[]) {
m_Position[0] = pos[0];
m_Position[1] = pos[1];
m_Position[2] = pos[2];
m_Texcoord[0] = tex[0];
m_Texcoord[1] = tex[1];
m_Normal[0] = nor[0];
m_Normal[1] = nor[1];
m_Normal[2] = nor[2];
}
};
public:
Mesh(Subject* sub, const std::string& FileName);
~Mesh();
bool LoadMesh(const std::string& FileName);
void Render();
// render index
void RenderMouseIndex();
// render triangle
void RenderTriangle(PickingFBO::Pixelinfo);
void update()
{
Render();
}
private:
bool InitFromScene(const aiScene* pScene, const std::string& Filename);
bool InitMaterials(const aiScene* pScene, const std::string& Filename);
void InitMesh(const aiMesh* paiMesh,
vector<Vector3f>& Positions,
vector<Vector3f>& Normals,
vector<Vector2f>& TexCoords,
vector<unsigned int>& Indices);
#define INDEX_BUFFER 0
#define POS_VB 1
#define NORMAL_VB 2
#define TEXCOORD_VB 3
GLuint VAO;
GLuint m_Buffers[4];
struct MeshEntry {
MeshEntry();
~MeshEntry();
unsigned int NumIndices;
unsigned int BaseIndex;
unsigned int BaseVertex;
unsigned int MaterialIndex;
};
std::vector<Vertex_VT> vertices;
std::vector<unsigned int> indices;
std::vector<MeshEntry> m_Entries;
std::vector<Texture*> m_Textures;
};
#endif // MESH_H
<file_sep>/solarsystem.cpp
#include "solarsystem.h"
#include <QtMath>
solarsystem::solarsystem()
{
geom = new Geometry();
sun = new Patch(geom);
// create sun
float yellow[]={1.0f, 1.0f, 0.0f, 1.0f};
CreateSphere(2.0f, sun, geom, yellow);
earth = new Patch(geom);
// create earth
float red[]={1.0f, 0.0f, 0.0f, 1.0f};
CreateSphere(2.0f, earth, geom, red);
geom->loadArrays();
}
void solarsystem::draw() {
// matrix for sun
sun->draw();
glPushMatrix();
glPopMatrix();
earth->rotate(60,QVector3D(0.0f,1.0f,0.0f));
earth->translate(QVector3D(5.0f,0.0f,0.0f));
earth->draw();
}
bool solarsystem::CreateSphere(float radius, // 半徑
Patch* patch,
Geometry* geom,
float *color, // 球的顏色
int stacks, // 緯度的切面數目
int slices // 徑度的切面數目
)
{
//*ppVertices = NULL;
int num_vertices = (stacks+1)*(slices+1);
int num_triangles = stacks*slices*2;
g_iNumSphereVertices = num_vertices;
g_iNumSphereTriangles = num_triangles;
g_iNumSphereIndices = num_triangles * 3;
patch->count = g_iNumSphereIndices;
geom->colors = new Color[num_vertices];
float default_color[] = {1.0f, 1.0f, 1.0f, 1.0f};
if ( color==NULL )
color = default_color;
const float theta_start_degree = 0.0f;
const float theta_end_degree = 360.0f;
const float phi_start_degree = -90.0f;
const float phi_end_degree = 90.0f;
float ts = qDegreesToRadians(theta_start_degree);
float te = qDegreesToRadians(theta_end_degree);
float ps = qDegreesToRadians(phi_start_degree);
float pe = qDegreesToRadians(phi_end_degree);
float theta_total = te - ts;
float phi_total = pe - ps;
float theta_inc = theta_total/stacks;
float phi_inc = phi_total/slices;
int i,j;
int index = 0;
qreal theta = ts;
float sin_theta, cos_theta;
float sin_phi, cos_phi;
float r = color[0];
float g = color[1];
float b = color[2];
float a = color[3];
for ( i=0; i<=stacks; i++ )
{
qreal phi = ps;
sin_theta = qSin(theta);
cos_theta = qCos(theta);
for ( j=0; j<=slices; j++, index++ )
{
sin_phi = qSin(phi);
cos_phi = qCos(phi);
// vertex
QVector3D point;
point[0] = radius * cos_phi * cos_theta;
point[1] = radius * sin_phi;
point[2] = radius * cos_phi * sin_theta;
geom->vertices.append(point);
// Color
float shading = (float) j / (float) slices;
//float shading = 1.0f;
/*
QVector4D color;
color[0] = 255 * r * shading;
color[1] = 255 * g * shading;
color[2] = 255 * b * shading;
color[3] = 255 * a * shading;
geom->colors.append(color);
*/
geom->colors[index].m_RGBA[0] = 255 * r * shading;
geom->colors[index].m_RGBA[1] = 255 * g * shading;
geom->colors[index].m_RGBA[2] = 255 * b * shading;
geom->colors[index].m_RGBA[3] = 255 * a * shading;
// inc phi
phi += phi_inc;
}
// inc theta
theta += theta_inc;
}
int base = 0;
index = 0;
if ( geom )
{
// triangle list
for ( i=0; i<stacks; i++ )
{
for ( j=0; j<slices; j++ )
{
geom->faces.append(base);
geom->faces.append(base+1);
geom->faces.append(base+slices+1);
geom->faces.append(base+1);
geom->faces.append(base+slices+2);
geom->faces.append(base+slices+1);
base++;
}
base++;
}
}
return true;
}
<file_sep>/texmatrix.cpp
#include "texmatrix.h"
texMatrix::texMatrix()
{
float vertex[4][3]= {{-1.5f, -1.5f, 0.0f}, {-0.1f, -1.5f, 0.0f}, {-1.5f, -0.1f, 0.0f}, {-0.1f, -0.1f, 0.0f}};
float tex[4][2] = {{-1.0f, 2.0f}, {2.0f, 2.0f}, {-1.0f, -1.0f}, {2.0f, -1.0f}};
float normal[4][3] = {{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f}};
g_Quad[0].set(vertex[0], tex[0], normal[0]);
g_Quad[1].set(vertex[1], tex[1], normal[1]);
g_Quad[2].set(vertex[2], tex[2], normal[2]);
g_Quad[3].set(vertex[3], tex[3], normal[3]);
QImage brickwall = QGLWidget::convertToGLFormat(QImage(":images/brickwall.tga"));
QImage graffiti = QGLWidget::convertToGLFormat(QImage(":images/graffiti_happy.tga"));
glGenTextures( 1, &g_Texture0_ID);
glBindTexture(GL_TEXTURE_2D, g_Texture0_ID);
glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER, GL_LINEAR );
glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA,
brickwall.size().width(), brickwall.size().height(), 0,
GL_RGBA, GL_UNSIGNED_BYTE, brickwall.bits() );
}
void texMatrix::draw(){
// `清除畫面`
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
// `把正向跟反向的面都畫出來`
glDisable(GL_CULL_FACE);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, g_Texture0_ID);
// `設定要用陣列的方式傳入頂點位置跟顏色`
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(Vertex_VT), &g_Quad[0].m_Position);
glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex_VT), &g_Quad[0].m_Texcoord);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
glDisable(GL_TEXTURE_2D);
}
<file_sep>/textest.h
#ifndef LIGHTTEST_H
#define LIGHTTEST_H
#include "patch.h"
#include "mathBase.h"
#include "observer.h"
class Texture;
class Subject;
class textest : public Observer
{
public:
textest(Subject* sub);
~textest();
void draw();
void init();
QMatrix4x4 matrix;
void printCoord();
void update()
{
draw();
}
private:
Vertex_VT Vertices[4];
Vector3f Positions[4];
Vector3f Normals[4];
Vector2f TexCoords[4];
void CalcNormals(Vertex_VT* Vertices, const unsigned int* pIndices, unsigned int IndexCount, unsigned int VertexCount);
void CreateVertexBuffer(const unsigned int* pIndices, unsigned int IndexCount);
void CreateIndexBuffer( const unsigned int* pIndices, unsigned int SizeInBytes );
void clear();
GLuint m_VBO;
GLuint m_IBO;
GLuint m_VAO;
// GLuint m_Buffers[4];
Texture* myTex;
};
#endif // LIGHTTEST_H
<file_sep>/widget.cpp
#include "widget.hpp"
#include "solarsystem.h"
#include "textest.h"
#include "multitex.h"
#include "texmatrix.h"
#include "shadertest.h"
#include <QtWidgets>
#include "QGLShader"
#include <QColor>
#include "stdio.h"
#include "MYMACRO.h"
Widget::Widget( const QGLFormat& format, QWidget* parent )
: QGLWidget( format, parent )
{
stepsize = 0.2;
scalefactor = 1.0;
mySub = new Subject();
this->updateGL();
}
Widget::~Widget()
{
SAFE_DELETE(mySub);
SAFE_DELETE(myTexTest);
SAFE_DELETE(myMesh);
}
void Widget::traslateTexCoor() {
printf("tex matrix move\n");
texmatrix.translate(QVector3D(0.1f, 0.0f,0.0f));
this->updateGL();
}
void Widget::initializeGL()
{
PRINT_GLVERSION();
printf("Curr dir = %s\n", qApp->applicationDirPath().toStdString().c_str());
myTechnique.init(this);
/**
* Setup model to be rendered.
*/
myMesh = new Mesh(mySub, "/Users/hsutsungchun/Desktop/QTGL/GL_2/models/bunny.obj");
myTexTest = new textest(mySub);
DEBUG_GL();
glEnable(GL_DEPTH_TEST);
//glEnable(GL_CULL_FACE);
/**
* Setup Light
*/
myTechnique.Enable();
DirectionalLight m_directionalLight;
m_directionalLight.Color = QVector3D(1.0f, 1.0f, 1.0f);
m_directionalLight.AmbientIntensity = 0.5f;
m_directionalLight.DiffuseIntensity = 0.8f;
m_directionalLight.Direction = QVector3D(1.0f, -1.0, 0.0);
myTechnique.SetDirectionalLight(m_directionalLight);
/*
* Setup matrix;
*/
projection.setToIdentity();
projection.perspective(90.0f, 1.0f, 1.0f, 100.0f);
//glOrtho(-10,10,-50,50, 0,20);
eye = QVector3D(0.0f, 0.0f, -5.0f);
center = QVector3D(0.0f, 0.0f, 0.0f);
g_up = QVector3D(0.0f, 1.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
//texmatrix.setToIdentity();
}
void Widget::resizeGL(int w, int h) {
glViewport(0, 0, w, h);
// Calculate aspect ratio
qreal aspect = (qreal)w / ((qreal)h?h:1);
// Set near plane to 3.0, far plane to 7.0, field of view 45 degrees
const qreal zNear = 3.0, zFar = 7.0, fov = 45.0;
// Reset projection
projection.setToIdentity();
// Set perspective projection
projection.perspective(fov, aspect, zNear, zFar);
//projection.perspective(90.0f, 1.0f, f, 100.0f);
}
// red->x axis, green->y axis, blue->z axis
void Widget::drawAxis() {
glDisable(GL_LIGHT0);
glDisable(GL_LIGHTING);
glBegin(GL_LINES);
glColor3f(1.0f,0.0f,0.0f);
glVertex3f(0.0f,0.0f,0.0f);
glVertex3f(100.0f,0.0f,0.0f);
glColor3f(0.0f,1.0f,0.0f);
glVertex3f(0.0f,0.0f,0.0f);
glVertex3f(0.0f,100.0f,0.0f);
glColor3f(0.0f,0.0f,1.0f);
glVertex3f(0.0f,0.0f,0.0f);
glVertex3f(0.0f,0.0f,100.0f);
glEnd();
glEnable(GL_LIGHT0);
glEnable(GL_LIGHTING);
}
void Widget::setupMatrix()
{
view.setToIdentity();
model.setToIdentity();
view.lookAt(eye, center, g_up);
model.rotate(xRot / 16.0f, 1.0f, 0.0f, 0.0f);
model.rotate(yRot / 16.0f, 0.0f, 1.0f, 0.0f);
model.rotate(zRot / 16.0f, 0.0f, 0.0f, 1.0f);
model.scale(scalefactor, scalefactor, -scalefactor);
model.translate(-1.5, 0, 0);
QMatrix4x4 gwvp = projection*view*model;
myTechnique.SetWVP(gwvp);
myTechnique.SetWorldMatrix(model);
}
void Widget::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
myTechnique.Enable();
setupMatrix();
/** Render method applied below */
myTechnique.SetTextureUnit(0);
mySub->notify();
myTechnique.Disable();
}
//textest* texture = new textest();
//multiTex* texture = new multiTex();
//texMatrix* texture = new texMatrix();
//texture->draw();
//drawAxis();
// Todo
void Widget::drawTriangle() {
// picking shader program enable
// render the triangle
// render the index
// get mouse location
// render triangle
// render the normal scene
}
void Widget::keyPressEvent(QKeyEvent* keyevent) {
QVector3D g_lookat = center - eye;
g_lookat.normalize();
if(keyevent->key()==Qt::Key_A) {
QVector3D right = QVector3D::crossProduct(g_up, g_lookat);
eye += right*stepsize;
}else if (keyevent->key()==Qt::Key_W){
//eye += g_lookat*stepsize;
scalefactor *= stepsize*10;
}else if (keyevent->key()==Qt::Key_S){
//eye -= g_lookat*stepsize;
scalefactor /= stepsize*10;
}else if (keyevent->key()==Qt::Key_D){
QVector3D right = QVector3D::crossProduct(g_lookat, g_up);
eye += right*stepsize;
printf("eye = %f, %f, %f\n", eye.x(), eye.y(), eye.z());
printf("right = %f, %f, %f\n", right.x(), right.y(), right.z());
}else if (keyevent->key()==Qt::Key_Up){
rotateBy(50.0f,0.0f,0.0f);
}else if (keyevent->key()==Qt::Key_Down){
rotateBy(-50.0f,0.0f,0.0f);
}else if (keyevent->key()==Qt::Key_Left){
rotateBy(0.0f,50.0f,0.0f);
}else if (keyevent->key()==Qt::Key_Right){
rotateBy(0.0f,-50.0f,0.0f);
}
center = eye + g_lookat;
this->updateGL();
}
void Widget::rotateBy(int xAngle, int yAngle, int zAngle)
{
xRot += xAngle;
yRot += yAngle;
zRot += zAngle;
updateGL();
}
void Widget::mousePressEvent(QMouseEvent *event) {
lastPos = event->pos();
}
void Widget::mouseMoveEvent(QMouseEvent *event)
{
//int dx = event->x() - lastPos.x();
//int dy = event->y() - lastPos.y();
int dx = lastPos.x() - event->x();
int dy = lastPos.y() - event->y();
if (event->buttons() & Qt::LeftButton) {
rotateBy(8 * dy, 8 * dx, 0);
} else if (event->buttons() & Qt::RightButton) {
rotateBy(8 * dy, 0, 8 * dx);
}
lastPos = event->pos();
}
<file_sep>/rendertechnique.cpp
#include "rendertechnique.h"
#include "QtMath"
#include "MYMACRO.h"
//static int m_WVPLocation = 0;
rendertechnique::rendertechnique()
{
m_WorldMatrixLocation = 0;
m_WVPLocation = 0;
m_eyeWorldPosLocation = 0;
m_matSpecularIntensityLocation = 0;
m_matSpecularPowerLocation = 0;
m_samplerLocation = 0;
}
rendertechnique::~rendertechnique() {
}
bool rendertechnique::init(QObject* parent) {
myShader = new QOpenGLShaderProgram(parent);
if(!myShader->addShaderFromSourceFile(QOpenGLShader::Vertex, "/Users/hsutsungchun/Desktop/QTGL/GL_2/meshV.vert"))
return false;
if(!myShader->addShaderFromSourceFile(QOpenGLShader::Fragment, "/Users/hsutsungchun/Desktop/QTGL/GL_2/meshF.frag"))
return false;
myShader->link();
m_WVPLocation = myShader->uniformLocation("gWVP");
m_WorldMatrixLocation = myShader->uniformLocation("gWorld");
m_samplerLocation = myShader->uniformLocation("gSampler");
m_dirLightLocation.Color = myShader->uniformLocation("gDirectionalLight.Base.Color");
m_dirLightLocation.AmbientIntensity = myShader->uniformLocation("gDirectionalLight.Base.AmbientIntensity");
m_dirLightLocation.Direction = myShader->uniformLocation("gDirectionalLight.Direction");
m_dirLightLocation.DiffuseIntensity = myShader->uniformLocation("gDirectionalLight.Base.DiffuseIntensity");
m_matSpecularIntensityLocation = myShader->uniformLocation("gMatSpecularIntensity");
m_matSpecularPowerLocation = myShader->uniformLocation("gSpecularPower");
m_eyeWorldPosLocation = myShader->uniformLocation("gEyeWorldPos");
//m_numPointLightsLocation = myShader->uniformLocation("gNumPointLights");
//m_numSpotLightsLocation = myShader->uniformLocation("gNumSpotLights");
/*
if (m_dirLightLocation.AmbientIntensity == INVALID_UNIFORM_LOCATION ||
m_WVPLocation == INVALID_UNIFORM_LOCATION ||
m_WorldMatrixLocation == INVALID_UNIFORM_LOCATION ||
m_samplerLocation == INVALID_UNIFORM_LOCATION ||
m_eyeWorldPosLocation == INVALID_UNIFORM_LOCATION ||
m_dirLightLocation.Color == INVALID_UNIFORM_LOCATION ||
m_dirLightLocation.DiffuseIntensity == INVALID_UNIFORM_LOCATION ||
m_dirLightLocation.Direction == INVALID_UNIFORM_LOCATION ||
m_matSpecularIntensityLocation == INVALID_UNIFORM_LOCATION ||
m_matSpecularPowerLocation == INVALID_UNIFORM_LOCATION ||
m_numPointLightsLocation == INVALID_UNIFORM_LOCATION ||
m_numSpotLightsLocation == INVALID_UNIFORM_LOCATION) {
return false;
}
for (unsigned int i = 0 ; i < ARRAY_SIZE_IN_ELEMENTS(m_pointLightsLocation) ; i++) {
char Name[128];
memset(Name, 0, sizeof(Name));
snprintf(Name, sizeof(Name), "gPointLights[%d].Base.Color", i);
m_pointLightsLocation[i].Color = myShader->uniformLocation(Name);
snprintf(Name, sizeof(Name), "gPointLights[%d].Base.AmbientIntensity", i);
m_pointLightsLocation[i].AmbientIntensity = myShader->uniformLocation(Name);
snprintf(Name, sizeof(Name), "gPointLights[%d].Position", i);
m_pointLightsLocation[i].Position = myShader->uniformLocation(Name);
snprintf(Name, sizeof(Name), "gPointLights[%d].Base.DiffuseIntensity", i);
m_pointLightsLocation[i].DiffuseIntensity = myShader->uniformLocation(Name);
snprintf(Name, sizeof(Name), "gPointLights[%d].Atten.Constant", i);
m_pointLightsLocation[i].Atten.Constant = myShader->uniformLocation(Name);
snprintf(Name, sizeof(Name), "gPointLights[%d].Atten.Linear", i);
m_pointLightsLocation[i].Atten.Linear = myShader->uniformLocation(Name);
snprintf(Name, sizeof(Name), "gPointLights[%d].Atten.Exp", i);
m_pointLightsLocation[i].Atten.Exp = myShader->uniformLocation(Name);
if (m_pointLightsLocation[i].Color == INVALID_UNIFORM_LOCATION ||
m_pointLightsLocation[i].AmbientIntensity == INVALID_UNIFORM_LOCATION ||
m_pointLightsLocation[i].Position == INVALID_UNIFORM_LOCATION ||
m_pointLightsLocation[i].DiffuseIntensity == INVALID_UNIFORM_LOCATION ||
m_pointLightsLocation[i].Atten.Constant == INVALID_UNIFORM_LOCATION ||
m_pointLightsLocation[i].Atten.Linear == INVALID_UNIFORM_LOCATION ||
m_pointLightsLocation[i].Atten.Exp == INVALID_UNIFORM_LOCATION) {
return false;
}
}
for (unsigned int i = 0 ; i < ARRAY_SIZE_IN_ELEMENTS(m_spotLightsLocation) ; i++) {
char Name[128];
memset(Name, 0, sizeof(Name));
snprintf(Name, sizeof(Name), "gSpotLights[%d].Base.Base.Color", i);
m_spotLightsLocation[i].Color = myShader->uniformLocation(Name);
snprintf(Name, sizeof(Name), "gSpotLights[%d].Base.Base.AmbientIntensity", i);
m_spotLightsLocation[i].AmbientIntensity = myShader->uniformLocation(Name);
snprintf(Name, sizeof(Name), "gSpotLights[%d].Base.Position", i);
m_spotLightsLocation[i].Position = myShader->uniformLocation(Name);
snprintf(Name, sizeof(Name), "gSpotLights[%d].Direction", i);
m_spotLightsLocation[i].Direction = myShader->uniformLocation(Name);
snprintf(Name, sizeof(Name), "gSpotLights[%d].Cutoff", i);
m_spotLightsLocation[i].Cutoff = myShader->uniformLocation(Name);
snprintf(Name, sizeof(Name), "gSpotLights[%d].Base.Base.DiffuseIntensity", i);
m_spotLightsLocation[i].DiffuseIntensity = myShader->uniformLocation(Name);
snprintf(Name, sizeof(Name), "gSpotLights[%d].Base.Atten.Constant", i);
m_spotLightsLocation[i].Atten.Constant = myShader->uniformLocation(Name);
snprintf(Name, sizeof(Name), "gSpotLights[%d].Base.Atten.Linear", i);
m_spotLightsLocation[i].Atten.Linear = myShader->uniformLocation(Name);
snprintf(Name, sizeof(Name), "gSpotLights[%d].Base.Atten.Exp", i);
m_spotLightsLocation[i].Atten.Exp = myShader->uniformLocation(Name);
if (m_spotLightsLocation[i].Color == INVALID_UNIFORM_LOCATION ||
m_spotLightsLocation[i].AmbientIntensity == INVALID_UNIFORM_LOCATION ||
m_spotLightsLocation[i].Position == INVALID_UNIFORM_LOCATION ||
m_spotLightsLocation[i].Direction == INVALID_UNIFORM_LOCATION ||
m_spotLightsLocation[i].Cutoff == INVALID_UNIFORM_LOCATION ||
m_spotLightsLocation[i].DiffuseIntensity == INVALID_UNIFORM_LOCATION ||
m_spotLightsLocation[i].Atten.Constant == INVALID_UNIFORM_LOCATION ||
m_spotLightsLocation[i].Atten.Linear == INVALID_UNIFORM_LOCATION ||
m_spotLightsLocation[i].Atten.Exp == INVALID_UNIFORM_LOCATION) {
return false;
}
}
*/
return true;
}
void rendertechnique::SetWVP(const QMatrix4x4& WVP)
{
//glUniformMatrix4fv(m_WVPLocation, 1, GL_FALSE, (const GLfloat*)WVP.constData());
myShader->setUniformValue(m_WVPLocation, WVP);
}
void rendertechnique::SetWorldMatrix(const QMatrix4x4& WorldInverse)
{
myShader->setUniformValue(m_WorldMatrixLocation, WorldInverse);
//glUniformMatrix4fv(m_WorldMatrixLocation, 1, GL_TRUE, (const GLfloat*)WorldInverse.constData());
}
void rendertechnique::SetTextureUnit(unsigned int TextureUnit)
{
DEBUG_GL();
glUniform1i(m_samplerLocation, TextureUnit);
DEBUG_GL();
}
void rendertechnique::SetDirectionalLight(const DirectionalLight& Light)
{
DEBUG_GL();
glUniform3f(m_dirLightLocation.Color, Light.Color.x(), Light.Color.y(), Light.Color.z());
glUniform1f(m_dirLightLocation.AmbientIntensity, Light.AmbientIntensity);
QVector3D Direction = Light.Direction;
Direction.normalize();
glUniform3f(m_dirLightLocation.Direction, Direction.x(), Direction.y(), Direction.z());
glUniform1f(m_dirLightLocation.DiffuseIntensity, Light.DiffuseIntensity);
DEBUG_GL();
}
void rendertechnique::SetMatSpecularIntensity(float Intensity)
{
glUniform1f(m_matSpecularIntensityLocation, Intensity);
}
void rendertechnique::SetMatSpecularPower(float Power)
{
glUniform1f(m_matSpecularPowerLocation, Power);
}
void rendertechnique::SetEyeWorldPos(const QVector3D& EyeWorldPos)
{
myShader->setUniformValue(m_eyeWorldPosLocation, EyeWorldPos);
//glUniform3f(m_eyeWorldPosLocation, EyeWorldPos.x(), EyeWorldPos.y(), EyeWorldPos.z() );
}
/*
void rendertechnique::SetPointLights(unsigned int NumLights, const PointLight* pLights)
{
glUniform1i(m_numPointLightsLocation, NumLights);
for (unsigned int i = 0 ; i < NumLights ; i++) {
glUniform3f(m_pointLightsLocation[i].Color, pLights[i].Color.x(), pLights[i].Color.y(), pLights[i].Color.z() );
glUniform1f(m_pointLightsLocation[i].AmbientIntensity, pLights[i].AmbientIntensity);
glUniform1f(m_pointLightsLocation[i].DiffuseIntensity, pLights[i].DiffuseIntensity);
glUniform3f(m_pointLightsLocation[i].Position, pLights[i].Position.x(), pLights[i].Position.y(), pLights[i].Position.z() );
glUniform1f(m_pointLightsLocation[i].Atten.Constant, pLights[i].Attenuation.Constant);
glUniform1f(m_pointLightsLocation[i].Atten.Linear, pLights[i].Attenuation.Linear);
glUniform1f(m_pointLightsLocation[i].Atten.Exp, pLights[i].Attenuation.Exp);
}
}
void rendertechnique::SetSpotLights(unsigned int NumLights, const SpotLight* pLights)
{
glUniform1i(m_numSpotLightsLocation, NumLights);
for (unsigned int i = 0 ; i < NumLights ; i++) {
glUniform3f(m_spotLightsLocation[i].Color, pLights[i].Color.x(), pLights[i].Color.y(), pLights[i].Color.z());
glUniform1f(m_spotLightsLocation[i].AmbientIntensity, pLights[i].AmbientIntensity);
glUniform1f(m_spotLightsLocation[i].DiffuseIntensity, pLights[i].DiffuseIntensity);
glUniform3f(m_spotLightsLocation[i].Position, pLights[i].Position.x(), pLights[i].Position.y(), pLights[i].Position.z());
QVector3D Direction = pLights[i].Direction;
Direction.normalize();
glUniform3f(m_spotLightsLocation[i].Direction, Direction.x(), Direction.y(), Direction.z());
glUniform1f(m_spotLightsLocation[i].Cutoff, cosf(qDegreesToRadians(pLights[i].Cutoff)));
glUniform1f(m_spotLightsLocation[i].Atten.Constant, pLights[i].Attenuation.Constant);
glUniform1f(m_spotLightsLocation[i].Atten.Linear, pLights[i].Attenuation.Linear);
glUniform1f(m_spotLightsLocation[i].Atten.Exp, pLights[i].Attenuation.Exp);
}
}*/
<file_sep>/technique.cpp
#include "technique.h"
technique::technique()
{
}
technique::~technique()
{
myShader->release();
}
/*
bool technique::init(QObject *parent)
{
myShader = new QOpenGLShaderProgram(parent);
if(!myShader->addShaderFromSourceFile(QOpenGLShader::Vertex, "/Users/hsutsungchun/Desktop/QTGL/GL_2/vertex.vs"))
return false;
if(!myShader->addShaderFromSourceFile(QOpenGLShader::Fragment, "/Users/hsutsungchun/Desktop/QTGL/GL_2/fragment.fs"))
return false;
myShader->link();
return true;
}*/
void technique::Enable()
{
this->myShader->bind();
}
void technique::Disable()
{
this->myShader->release();
}
<file_sep>/textest.cpp
#include "textest.h"
#include "texture.h"
#include <QImage>
#include "MYMACRO.h"
#include "observer.h"
#define checkImageWidth 64
#define checkImageHeight 64
#define ARRAY_SIZE_IN_ELEMENTS(a) (sizeof(a)/sizeof(a[0]))
static GLuint g_TextureID;
static GLubyte checkImage[checkImageHeight][checkImageWidth][4];
void makeCheckImage(void)
{
int i, j, c;
for (i = 0; i < checkImageHeight; i++) {
for (j = 0; j < checkImageWidth; j++) {
c = (((i&0x8)==0)^((j&0x8))==0)*255;
checkImage[i][j][0] = (GLubyte) c;
checkImage[i][j][1] = (GLubyte) c;
checkImage[i][j][2] = (GLubyte) c;
checkImage[i][j][3] = (GLubyte) 255;
} }
}
textest::textest(Subject* sub) : Observer(sub) {
m_VBO = INVALID_OGL_VALUE;
m_VAO = INVALID_OGL_VALUE;
m_IBO = INVALID_OGL_VALUE;
// ZERO_MEM(m_Buffers);
init();
}
textest::~textest()
{
clear();
}
void textest::clear()
{
if(m_VBO!=INVALID_OGL_VALUE)
{
glDeleteBuffers(1, &m_VBO);
}
if(m_VAO!=INVALID_OGL_VALUE)
{
glDeleteBuffers(1, &m_VAO);
}
if(m_IBO!=INVALID_OGL_VALUE)
{
glDeleteBuffers(1, &m_IBO);
}
// if(m_Buffers[0]!=0) {
// glDeleteBuffers(ARRAY_SIZE_IN_ELEMENTS(m_Buffers), m_Buffers);
// }
}
void textest::init()
{
unsigned int Indices[] = { 0, 3, 1,
1, 3, 2,
2, 3, 0,
1, 2, 0 };
DEBUG_GL();
glGenVertexArrays(1, &m_VAO);
DEBUG_GL();
glBindVertexArray(m_VAO);
DEBUG_GL();
CreateIndexBuffer( Indices, sizeof(Indices) );
CreateVertexBuffer( Indices, ARRAY_SIZE_IN_ELEMENTS(Indices) );
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex_VT), 0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex_VT), (const GLvoid*)12);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex_VT), (const GLvoid*)20);
myTex = new Texture(GL_TEXTURE_2D, "/Users/hsutsungchun/Desktop/QTGL/GL_2/images/brickwall.tga");
DEBUG_GL();
if(!myTex->Load()) {
DEBUG_GL();
printf("Loading Texture Error!\n");
return;
}
glBindVertexArray(0);
}
void textest::CalcNormals(Vertex_VT* Vertices, const unsigned int* pIndices, unsigned int IndexCount, unsigned int VertexCount)
{
for(int i=0 ;i< IndexCount; ++i)
{
unsigned int Index0 = pIndices[i];
unsigned int Index1 = pIndices[i+1];
unsigned int Index2 = pIndices[i+2];
float* tmp;
tmp = Vertices[Index0].m_Position;
QVector3D v1 (tmp[0], tmp[1], tmp[2]);
tmp = Vertices[Index1].m_Position;
QVector3D v2 (tmp[0], tmp[1], tmp[2]);
tmp = Vertices[Index2].m_Position;
QVector3D v3 (tmp[0], tmp[1], tmp[2]);
QVector3D va = v2 - v1;
QVector3D vb = v3 - v1;
QVector3D normal = QVector3D::crossProduct(va, vb);
Vertices[Index0].m_Normal[0] += normal.x();
Vertices[Index0].m_Normal[1] += normal.y();
Vertices[Index0].m_Normal[2] += normal.z();
Vertices[Index1].m_Normal[0] += normal.x();
Vertices[Index1].m_Normal[1] += normal.y();
Vertices[Index1].m_Normal[2] += normal.z();
Vertices[Index2].m_Normal[0] += normal.x();
Vertices[Index2].m_Normal[1] += normal.y();
Vertices[Index2].m_Normal[2] += normal.z();
}
for (int i=0; i<VertexCount; ++i)
{
QVector3D tmp( Vertices[i].m_Normal[0], Vertices[i].m_Normal[1], Vertices[i].m_Normal[2] );
tmp.normalize();
Vertices[i].m_Normal[0] = tmp.x();
Vertices[i].m_Normal[1] = tmp.y();
Vertices[i].m_Normal[2] = tmp.z();
}
}
void textest::CreateIndexBuffer( const unsigned int* pIndices, unsigned int SizeInBytes )
{
glGenBuffers(1, &m_IBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_IBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, SizeInBytes, pIndices, GL_STATIC_DRAW);
}
void textest::CreateVertexBuffer(const unsigned int* pIndices, unsigned int IndexCount)
{
float v1[] = {-1.0f, -1.0f, 0.5773f };
float t1[] = {0.0f, 0.0f};
float n1[] = {0.0f, 0.0f};
float v2[] = { 0.0f, -1.0f, -1.15475f}; float t2[] = {0.5f, 0.0f}; float n2[]={0.0f, 0.0f};
float v3[] = { 1.0f, -1.0f, 0.5773f }; float t3[] = {1.0f, 0.0f}; float n3[]={0.0f, 0.0f};
float v4[] = { 0.0f, 1.0f, 0.0f }; float t4[] = {0.5f, 1.0f}; float n4[]={0.0f, 0.0f};
Vertices[0].set(v1, t1, n1);
Vertices[1].set(v2, t2, n2);
Vertices[2].set(v3, t3, n3);
Vertices[3].set(v4, t4, n4);
int VertexCount = ARRAY_SIZE_IN_ELEMENTS(Vertices);
//CalcNormals(Vertices, pIndices, IndexCount, VertexCount);
glGenBuffers(1, &m_VBO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex_VT)*VertexCount, Vertices, GL_STATIC_DRAW);
}
void textest::printCoord() {
QVector3D verts[4];
float* tmp;
tmp = Vertices[0].m_Position;
verts[0] = QVector3D(tmp[0], tmp[1], tmp[2]);
tmp = Vertices[1].m_Position;
verts[1] = QVector3D(tmp[0], tmp[1], tmp[2]);
tmp = Vertices[2].m_Position;
verts[2] = QVector3D(tmp[0], tmp[1], tmp[2]);
tmp = Vertices[3].m_Position;
verts[3] = QVector3D(tmp[0], tmp[1], tmp[2]);
printf("Before===\n");
for(int i=0 ;i<4 ; ++i)
{
printf(" vertex %d %f %f %f\n", i+1, verts[i].x(), verts[i].y(), verts[i].z());
verts[i] = matrix * verts[i];
}
printf("After===\n");
for(int i=0 ;i<4 ; ++i)
{
printf(" vertex %d %f %f %f\n", i+1, verts[i].x(), verts[i].y(), verts[i].z());
}
}
void textest::draw() {
myTex->Bind(GL_TEXTURE0);
glBindVertexArray(m_VAO);
glDrawElements(GL_TRIANGLES, 12, GL_UNSIGNED_INT, (void*)0);
glBindVertexArray(0);
}
<file_sep>/shadertest.cpp
#include "shadertest.h"
#include "QGLShader"
static const char *vertexShaderSource =
"attribute highp vec4 posAttr;\n"
"attribute lowp vec4 colAttr;\n"
"varying lowp vec4 col;\n"
"uniform highp mat4 matrix;\n"
"void main() {\n"
" col = colAttr;\n"
" gl_Position = matrix * posAttr;\n"
"}\n";
GLuint VBO;
GLuint VAO;
GLuint IB = 0;
static void CreateVertexBuffer()
{
GLfloat vertices[] = {
0.0f, 0.707f, 0.5,
-0.5f, -0.5f, 0.5,
0.5f, -0.5f, 0.5
};
GLuint indices[] = {
0, 1, 2
};
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, 9*sizeof(GLfloat), vertices, GL_STATIC_DRAW);
glGenBuffers(1, &IB);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IB);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*3, indices, GL_STATIC_DRAW);
}
shadertest::shadertest()
{
m_program = 0;
}
void shadertest::initialize(QObject* parent) {
m_program = new QOpenGLShaderProgram(parent);
m_program->addShaderFromSourceFile(QOpenGLShader::Vertex, "/Users/hsutsungchun/Desktop/QTGL/GL_2/vertex.vs");
m_program->addShaderFromSourceFile(QOpenGLShader::Fragment, "/Users/hsutsungchun/Desktop/QTGL/GL_2/fragment.fs");
if (!m_program->link()) {
return;
}
m_posAttr = m_program->attributeLocation("Position");
//m_colAttr = m_program->attributeLocation("colAttr");
//m_matrixUniform = m_program->uniformLocation("matrix");
CreateVertexBuffer();
}
void shadertest::render() {
glClear(GL_COLOR_BUFFER_BIT);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IB);
GLenum err;
while ((err = glGetError()) != GL_NO_ERROR) {
printf("OpenGL error:%d\n ", err);
}
if(!m_program->bind()) {
return;
}
QMatrix4x4 matrix;
matrix.perspective(60.0f, 4.0f/3.0f, 0.1f, 100.0f);
matrix.translate(0, 0, -2);
//matrix.rotate(100.0f * m_frame / screen()->refreshRate(), 0, 1, 0);
//m_program->setUniformValue(m_matrixUniform, matrix);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
glEnableVertexAttribArray(0);
glBindVertexArray(VAO);
//glDrawArrays(GL_TRIANGLES, 0, 3);
glDrawElements(GL_TRIANGLES, 3, GL_UNSIGNED_INT, 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glDisableVertexAttribArray(0);
m_program->release();
}
|
69512f4476bc3c12600c47820e827403e0839c01
|
[
"Markdown",
"Text",
"C++"
] | 28 |
C++
|
tsungchh/GLTEST
|
d1c17bbe1a448eb184cfb6a228ab601d36319d54
|
2cf67a29dc1e052fe281fa93b1c72edd3d86f4bf
|
refs/heads/master
|
<repo_name>Innoberger/Matrices<file_sep>/src/de/innoberger/les/Main.java
package de.innoberger.les;
import de.innoberger.matrix.Matrix;
import de.innoberger.matrix.SquareMatrix;
//import de.innoberger.les.matrix.LinearEquationSystem3x2;
//import de.innoberger.les.matrix.LinearEquationSystem4x3;
public class Main {
public static void main(String[] args) {
// double[][] matrix4x3 = { { 1, 1, 1, 6 }, { 1, -1, 2, 2 }, { 2, 1, -1, 3 } };
// double[][] matrix3x2 = { { 7, -2, 3 }, { 3, 1, 5 } };
//
// LinearEquationSystem4x3 les_1 = new LinearEquationSystem4x3(matrix4x3);
// LinearEquationSystem3x2 les_2 = new LinearEquationSystem3x2(matrix3x2);
//
// les_1.print();
// les_1.printSolve();
//
// les_2.print();
// les_2.printSolve();
try {
SquareMatrix a = new SquareMatrix(3);
double[][] aElements = { { 1, 4, 0 }, { 0, 3, 4 }, { -1, 1, 0 } };
a.setElements(aElements);
a.print();
System.out.println("det(A) = " + a.getDeterminat());
System.out.println("");
SquareMatrix inv = a.getInversion();
inv.print();
System.out.println("det(A^-1) = " + inv.getDeterminat());
System.out.println("");
Matrix prod = a.multiplyWithMatrix(inv);
prod.print();
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>/src/de/innoberger/les/matrix/LinearEquationSystem3x2.java
package de.innoberger.les.matrix;
public class LinearEquationSystem3x2 {
private double[][] les;
/**
* Create a new LES (format: Ax = b)
*
* @param newLES
* 1st dimension is the rows; 2nd dimension elements x_1, x_2 and b
* of a row
*/
public LinearEquationSystem3x2(double[][] newLES) {
if (newLES.length != 2) {
System.err.println("This matrix must have two rows.");
return;
}
for (int i = 0; i < 2; i++) {
if (newLES[i].length != 3) {
System.err.println("A row must contain three values (x_1, x_2, b)");
break;
}
}
this.les = newLES;
}
public void print() {
System.out.println("");
for (int i = 0; i < 2; i++) {
System.out.println(this.les[i][0] + "*x_1 + " + this.les[i][1] + "*x_2 = " + this.les[i][2]);
}
System.out.println("");
}
public double[] solve() {
double detA = this.les[0][0] * this.les[1][1] - this.les[1][0] * this.les[0][1];
double detA_1 = this.les[0][2] * this.les[1][1] - this.les[1][2] * this.les[0][1];
double detA_2 = this.les[0][0] * this.les[1][2] - this.les[1][0] * this.les[0][2];
return new double[] { detA_1 / detA, detA_2 / detA };
}
public void printSolve() {
double[] solve = this.solve();
System.out.println("Solved: x_1=" + solve[0] + " x_2=" + solve[1]);
}
}
<file_sep>/src/de/innoberger/les/matrix/LinearEquationSystem4x3.java
package de.innoberger.les.matrix;
public class LinearEquationSystem4x3 {
private double[][] les;
/**
* Create a new LES (format: Ax = b)
*
* @param newLES
* 1st dimension is the rows; 2nd dimension elements x_1, x_2, x_3
* and b of a row
*/
public LinearEquationSystem4x3(double[][] newLES) {
if (newLES.length != 3) {
System.err.println("This matrix must have three rows.");
return;
}
for (int i = 0; i < 3; i++) {
if (newLES[i].length != 4) {
System.err.println("A row must contain four values (x_1, x_2, x_3, b)");
break;
}
}
this.les = newLES;
}
public void print() {
System.out.println("");
for (int i = 0; i < 3; i++) {
System.out.println(this.les[i][0] + "*x_1 + " + this.les[i][1] + "*x_2 + " + this.les[i][2] + "*x_3 = "
+ this.les[i][3]);
}
System.out.println("");
}
public double[] solve() {
double detA = this.les[0][0] * this.les[1][1] * this.les[2][2]
+ this.les[0][1] * this.les[1][2] * this.les[2][0] + this.les[0][2] * this.les[1][0] * this.les[2][1]
- this.les[2][0] * this.les[1][1] * this.les[0][2] - this.les[2][1] * this.les[1][2] * this.les[0][0]
- this.les[2][2] * this.les[1][0] * this.les[0][1];
double detA_1 = this.les[0][3] * this.les[1][1] * this.les[2][2]
+ this.les[0][1] * this.les[1][2] * this.les[2][3] + this.les[0][2] * this.les[1][3] * this.les[2][1]
- this.les[2][3] * this.les[1][1] * this.les[0][2] - this.les[2][1] * this.les[1][2] * this.les[0][3]
- this.les[2][2] * this.les[1][3] * this.les[0][1];
double detA_2 = this.les[0][0] * this.les[1][3] * this.les[2][2]
+ this.les[0][3] * this.les[1][2] * this.les[2][0] + this.les[0][2] * this.les[1][0] * this.les[2][3]
- this.les[2][0] * this.les[1][3] * this.les[0][2] - this.les[2][3] * this.les[1][2] * this.les[0][0]
- this.les[2][2] * this.les[1][0] * this.les[0][3];
double detA_3 = this.les[0][0] * this.les[1][1] * this.les[2][3]
+ this.les[0][1] * this.les[1][3] * this.les[2][0] + this.les[0][3] * this.les[1][0] * this.les[2][1]
- this.les[2][0] * this.les[1][1] * this.les[0][3] - this.les[2][1] * this.les[1][3] * this.les[0][0]
- this.les[2][3] * this.les[1][0] * this.les[0][1];
return new double[] { detA_1 / detA, detA_2 / detA, detA_3 / detA };
}
public void printSolve() {
double[] solve = this.solve();
System.out.println("Solved: x_1=" + solve[0] + " x_2=" + solve[1] + " x_3=" + solve[2]);
}
}
<file_sep>/src/de/innoberger/matrix/Matrix.java
package de.innoberger.matrix;
import java.text.MessageFormat;
public class Matrix {
/**
* 1st dimension: rows, 2nd dimension: columns
*/
protected double matrix[][];
/**
* Creates a new Matrix object.
*
* @param width
* Columns of the matrix
* @param height
* Rows of the matrix
*/
public Matrix(int width, int height) throws Exception {
if (width < 1 || height < 1) {
try {
throw new Exception("Matrix must be at least 1x1");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
this.matrix = new double[height][width];
this.fillUpWithZeroes();
}
/**
* Sets the elements.
*
* @param elements
* Two-dimensional array of matrix elements. Length of first
* dimension must match the given matrix height, length of second
* dimension must match the given matrix width.
*/
public void setElements(double elements[][]) throws Exception {
if (elements.length != this.getHeight()) {
try {
throw new Exception("Amount of rows (" + elements.length + ") must match given matrix height ("
+ this.getHeight() + ")");
} catch (Exception e) {
e.printStackTrace();
}
return;
}
for (int row = 0; row < elements.length; row++) {
if (elements[row].length != this.getWidth()) {
try {
throw new Exception("Amount of columns (" + elements[row].length
+ ") does not match given matrix height (" + this.getWidth() + ") in row " + (row + 1));
} catch (Exception e) {
e.printStackTrace();
}
return;
}
}
this.matrix = elements;
}
public void setElement(int row, int col, double value) throws Exception {
if (row < 1 || row > this.getHeight()) {
throw new Exception("Row number (" + row + ") must be between 1 and the height of the matrix ("
+ this.getHeight() + ")");
} else if (col < 1 || col > this.getWidth()) {
throw new Exception("Column number (" + col + ") must be between 1 and the size of the matrix ("
+ this.getWidth() + ")");
} else {
this.matrix[row - 1][col - 1] = value;
}
}
public void multiply(double factor) {
for (int row = 0; row < this.getHeight(); row++) {
for (int col = 0; col < this.getWidth(); col++) {
this.matrix[row][col] *= factor;
}
}
}
/**
* Replaces every empty element with zero.
*/
private void fillUpWithZeroes() {
for (int row = 0; row < this.getHeight(); row++) {
for (int col = 0; col < this.getWidth(); col++) {
if (this.matrix[row][col] != 0.0) {
this.matrix[row][col] = 0.0;
}
}
}
}
/**
* Prints out the matrix to console in a readable format.
*/
public void print() {
for (int row = 0; row < this.getHeight(); row++) {
StringBuilder sb = new StringBuilder();
sb.append("| ");
for (int col = 0; col < this.getWidth(); col++) {
sb.append(this.matrix[row][col] + " ");
}
sb.append("|");
System.out.println(sb.toString());
}
}
/**
* Extracts a specific row as array.
*
* @param rowNumber
* Number of row (STARTING WITH 1!!!)
* @return
*/
public double[] getRowAsArray(int rowNumber) {
return this.matrix[rowNumber - 1];
}
/**
* Extracts a specific column as array.
*
* @param colNumber
* Number of column (STARTING WITH 1!!!)
* @return
*/
public double[] getColumnAsArray(int colNumber) {
double[] result = new double[this.getHeight()];
for (int row = 1; row <= this.getHeight(); row++) {
for (int col = 1; col <= this.getWidth(); col++) {
if (col == colNumber)
result[row - 1] = this.matrix[row - 1][col - 1];
}
}
return result;
}
/**
* Multiplies this matrix with a second matrix.
*
* @param second
* second matrix
*
* @return result after multiplication
*/
public Matrix multiplyWithMatrix(Matrix second) throws Exception {
Matrix resultMatrix;
double[][] result;
int xColumns, xRows, yColumns, yRows;
xRows = this.getHeight();
xColumns = this.getWidth();
yRows = second.getHeight();
yColumns = second.getWidth();
result = new double[xRows][yColumns];
resultMatrix = new Matrix(xRows, yColumns);
if (xColumns != yRows) {
throw new Exception(MessageFormat.format("Matrices don't match: {0} != {1}.", xColumns, yRows));
}
for (int i = 0; i < xRows; i++) {
for (int j = 0; j < yColumns; j++) {
for (int k = 0; k < xColumns; k++) {
result[i][j] += (this.matrix[i][k] * second.matrix[k][j]);
}
}
}
resultMatrix.setElements(result);
return resultMatrix;
}
////////////////////////////////////////////////
public int getHeight() {
return this.matrix.length;
}
public int getWidth() {
return this.matrix[0].length;
}
/**
*
* @return true if height is equal to width
*/
public boolean isSquareMatrix() {
return this.getHeight() == this.getWidth();
}
}
|
6d0aa686ee9edb5e6e2939b3ebb559ff479c4bfa
|
[
"Java"
] | 4 |
Java
|
Innoberger/Matrices
|
62f07bb7595de693e18a03193bc4ac6f8a2b98c1
|
10d9565b4b8b8303e8575fb9dac5d0d0f356fb33
|
refs/heads/main
|
<repo_name>JonCels/NPC-mancer<file_sep>/src/test.py
import mysql.connector
db = mysql.connector.connect(
host="localhost",
user="root",
passwd="<PASSWORD>",
auth_plugin='mysql_native_password',
database='npc_mancer_db'
)
mycursor = db.cursor()
mycursor.execute("select * from races")
races = []
for race in mycursor:
races.append(race);<file_sep>/src/pdfProcessing.py
import pdfrw as p
characterSheetTemplatePDF = "template.pdf"
characterSheetOutputPDF = "output.pdf"
templatePDF = p.PdfReader(characterSheetTemplatePDF)
ANNOT_KEY = '/Annots'
ANNOT_FIELD_KEY = '/T'
ANNOT_VAL_KEY = '/V'
ANNOT_RECT_KEY = '/Rect'
SUBTYPE_KEY = '/Subtype'
WIDGET_SUBTYPE_KEY = '/Widget'
# for page in templatePDF.pages:
# annotations = page[ANNOT_KEY]
# for annotation in annotations:
# if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY:
# if annotation[ANNOT_FIELD_KEY]:
# key = annotation[ANNOT_FIELD_KEY][1:-1]
# print(key)
#Takes the pdf given as inputPDF, adds the data specified in characterData, and creates a new pdf with the data given and the name given as outputPDF
def fillPDF(inputPDF, outputPDF, characterData):
templatePDF = p.PdfReader(inputPDF)
for page in templatePDF.pages:
annotations = page[ANNOT_KEY]
for annotation in annotations:
if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY:
if annotation[ANNOT_FIELD_KEY]:
key = annotation[ANNOT_FIELD_KEY][1:-1]
if key in characterData.keys():
if type(characterData[key]) == bool:
if characterData[key] == True:
annotation.update(p.PdfDict(
AS=p.PdfName('Yes')))
else:
annotation.update(
p.PdfDict(V='{}'.format(characterData[key]))
)
annotation.update(p.PdfDict(AP=''))
p.PdfWriter().write(outputPDF, templatePDF)
characterData = {
'ClassLevel': 'Ranger, ' + str(5),
'Background': 'urchin',
'Race': 'High Elf',
'STR': 13
}
fillPDF(characterSheetTemplatePDF, characterSheetOutputPDF, characterData)<file_sep>/src/races.py
from enum import Enum
Races = Enum('Races', 'DWARF, ELF, HALFLING, HUMAN, DRAGONBORN, GNOME, HALF-ELF, HALF-ORC, TIEFLING')
Skills = Enum('Skills', 'STRENGTH, DEXTERITY, CONSTITUTION, INTELLIGENCE, WISDOM, CHARISMA')
class Race():
def __init__(self, name, bonus1, bonus2):
self.name = name
self.bonus1 = bonus1
self.bonus2 = bonus2
print(bonus1[0].name)
print(bonus1[1])
print(bonus2[0].name)
print(bonus2[1])
DragonBorn = Race(Races.DRAGONBORN, [Skills.STRENGTH, 2], [Skills.CHARISMA, 1])
<file_sep>/README.md
# NPC-mancer
An easy way to auto-generate DnD 5e playable characters for quick use. This is intended for quick generation of NPC's.
<file_sep>/src/character.py
import random
from enum import Enum
import mysql.connector
import math
playableRaces = []
selectableSubraces = []
abilitiesList = []
classesList = []
selectableClassSpecs = []
skillsList = []
backgroundsList = []
armoursList = []
weaponsList = []
numProf = 18
numStat = 6
selectedRace = {}
selectedSubrace = ""
selectedClass = {}
selectedClassSpec = {}
selectedBackground = {}
class Character():
def __init__(self, race, dndClass, background, level):
self.race = race[0]['race']
self.subrace = race[1]
self.dndClass = dndClass[0]['class']
self.dndClassSpec = dndClass[1]['class']
self.subclass = self.selectSubclass(dndClass)
#subclass
self.background = background['background']
self.level = level
self.prioDict = {}
self.stats = self.placeStats()
self.racialTraits()
self.modifiers = self.calcModifiers()
self.skills = self.placeSkills()
self.savingThrows = self.placeSavingThrows()
self.proficiencyBonus = self.calcProficiencyBonus()
self.selectArmour("Unarmoured")
self.initiative = self.modifiers['Dexterity']
self.walkSpeed = race[0]['walk_speed']
self.passivePerception = self.calcPassivePerception()
self.hitDice = dndClass[0]['hit_dice']
self.hp = self.calcHP()
self.numHitDice = self.level
self.backgroundTraits(background)
self.classTraits(dndClass)
self.weapons = []
def selectSubclass(self, dndClass):
pass
#Generates an array of ability scores and places them according to common ability priorities based on the character class
def placeStats(self):
statArray = generateStatArray()
#priorityArray = generatePriorityArray(self.class)
#todo: generatePriorityDict function
self.prioDict = {'Strength' : 5, 'Dexterity': 0, 'Constitution': 2, 'Intelligence': 3, 'Wisdom': 1, 'Charisma': 4}
prioDict = self.prioDict.copy()
stats = {}
for _ in range(numStat):
#Get next highest priority ability
currAbility = min(prioDict, key=prioDict.get)
prioDict.pop(currAbility)
#Get next highest scores
currScore = max(statArray)
statArray.remove(currScore)
#Assign score to ability
stats[currAbility] = currScore
return stats
def calcModifiers(self):
modifiers = {}
for stat in self.stats:
modifiers[stat] = ((self.stats[stat] // 2) - 5)
return modifiers
def placeSkills(self):
skills = {}
for skill in skillsList:
skills[skill['skill']] = [0, self.modifiers[getAbility(skill['abilityID'])]]
return skills
def placeSavingThrows(self):
savingThrows = {}
for savingThrow in abilitiesList:
savingThrows[savingThrow['ability']] = [0, self.modifiers[savingThrow['ability']]]
return savingThrows
def calcProficiencyBonus(self):
return math.ceil(1 + (1/4) * self.level)
def calcPassivePerception(self):
self.passivePerception = 10 + self.skills['Perception'][1]
def calcHP(self):
#hp = hit dice value + constitution
hp = self.hitDice + self.modifiers['Constitution']
return hp
def addHP(self, hp):
self.hp += hp
def levelUp(self):
#Add any ASI's taken
lvlHp = random.randint(1, self.hitDice) + self.modifiers['Constitution']
self.addHP(lvlHp)
#todo
def generatePriorityArray():
priority = []
for i in range(numStat):
priority.append(i)
return priority
def racialTraits(self):
if (self.race == "Aarakocra"):
self.stats['Dexterity'] += 2
self.stats['Wisdom'] += 1
#Flight
#Talons
#Languages
elif (self.race == "Aasimar"):
self.stats['Charisma'] += 2
#Darkvision
#Celestial Resistance
#Healing Hands
#Light Bearer
#Languages
if (self.subrace == "Protector Aasimar"):
self.stats['Wisdom'] += 1
#Radiant soul
elif (self.subrace == "Scourge Aasimar"):
self.stats['Constitution'] += 1
#Radiant consumption
elif (self.subrace == "Fallen Aasimar"):
self.stats['Strength'] += 1
#Necrotic shroud
elif (self.race == "Bugbear"):
self.stats['Strength'] += 2
self.stats['Dexterity'] += 1
#Darkvision
#Long limbed
#Powerful build
#Sneaky
#Surprise attack
#Languages
elif (self.race == "Dragonborn"):
self.stats['Strength'] += 2
self.stats['Charisma'] += 1
#Draconic ancestry
#Breath weapon
#Damage resistance
#Languages
elif (self.race == "Dwarf"):
self.stats['Constitution'] += 2
#Darkvision
#Dwarven resilience
#Dwarven combat training
#Tool proficicency
#Stonecunning
#Languages
if (self.subrace == "Hill Dwarf"):
self.stats['Wisdom'] += 1
#Dwarven toughness
elif (self.subrace == "Mountain Dwarf"):
self.stats['Strength'] += 2
#Dwarven armor training
elif (self.race == "Elf"):
self.stats['Dexterity'] += 2
#Darkvision
#Keen senses
#Fey ancestry
#Trance
#Languages
if (self.subrace == "High Elf"):
self.stats['Intelligence'] += 1
#Elf weapon training
#Cantrip
#Extra language
elif (self.subrace == "Wood Elf"):
self.stats['Wisdom'] += 1
#Elf weapon training
#Fleet of foot
#Mask of the wild
elif (self.race == "Firbolg"):
self.stats['Wisdom'] += 2
self.stats['Strength'] += 1
#Firbolg magic
#Hidden step
#Powerful build
#Speech of beast and leaf
#Languages
elif (self.race == "Genasi"):
self.stats['Constitution'] += 2
#Languages
if (self.subrace == "Air Genasi"):
self.stats['Dexterity'] += 1
#Unending breath
#Mingle with the wind
elif (self.subrace == "Earth Genasi"):
self.stats['Strength'] += 1
#Earth walk
#Merge with stone
elif (self.subrace == "Fire Genasi"):
self.stats['Intelligence'] += 1
#Darkvision
#Fire resistance
#Reach to the blaze
elif (self.subrace == "Water Genasi"):
self.stats['Wisdom'] += 1
#Acid Resistance
#Amphibious
#Swim
#Call to the wave
elif (self.race == "Gnome"):
self.stats['Intelligence'] += 2
#Darkvision
#Gnome cunning
#Languages
if (self.subrace == "Forest Gnome"):
self.stats['Dexterity'] += 1
#Natural Illusionist
#Speak with small beasts
elif (self.subrace == "Rock Gnome"):
self.stats['Constitution'] += 1
#Artificers lore
#Tinker
elif (self.subrace == "Deep Gnome"):
self.stats['Dexterity']
#Superior darkvision
#Stone camouflage
elif (self.race == "Goblin"):
self.stats['Dexterity'] += 2
self.stats['Constitution'] += 1
#Darkvision
#Fury of the small
#Nimble escape
#Languages
elif (self.race == "Goliath"):
self.stats['Strength'] += 2
self.stats['Constitution'] += 1
#Natural athlete
#Stone's endurance
#Powerful build
#Mountain born
elif (self.race == "Half-Elf"):
self.stats['Charisma'] += 2
#Choose based on abilityPriority
prioDict = self.prioDict.copy()
prioDict.pop("Charisma")
sortedPrioDict = dict(sorted(prioDict.items(), key=lambda item: item[1]))
focus1 = list(sortedPrioDict.items())[:1][0][0]
focus2 = list(sortedPrioDict.items())[1:2][0][0]
self.stats[focus1] += 1
self.stats[focus2] += 1
elif (self.race == "Half-Orc"):
self.stats['Strength'] += 2
self.stats['Constitution'] += 1
#Darkvision
#Menacing
#Relentless endurance
#Savage attacks
#Languages
elif (self.race == "Halfling"):
self.stats['Dexterity'] += 2
if (self.subrace == "Lightfoot Halfling"):
self.stats['Charisma'] += 1
#Naturally stealthy
elif (self.subrace == "Stout Halfling"):
self.stats['Constitution'] += 1
#Stout resilience
elif (self.race == "Hobgoblin"):
self.stats['Constitution'] += 2
self.stats['Intelligence'] += 1
#Darkvision
#Martial Training
#Saving face
#Languages
def classTraits(self, dndClass):
#Saving throw proficiencies
savingThrow1 = getAbility(dndClass[0]['saving_throw_1'])
savingThrow2 = getAbility(dndClass[0]['saving_throw_2'])
self.addSavingThrowProficiency(savingThrow1)
self.addSavingThrowProficiency(savingThrow2)
def backgroundTraits(self, background):
#Skill proficiencies
skill1 = getSkill(background['skillProficiency1ID'])
skill2 = getSkill(background['skillProficiency2ID'])
self.addSkillProficiency(skill1)
self.addSkillProficiency(skill2)
#Adds proficiency in a skill. Pass an optional parameter of 2 for expertise rather than regular proficiency.
def addSkillProficiency(self, skill, level=1):
self.skills[skill][0] = level
self.skills[skill][1] += self.proficiencyBonus * level
if (skill == "Perception"):
self.calcPassivePerception()
def addSavingThrowProficiency(self, savingThrow):
self.savingThrows[savingThrow][0] = 1
self.savingThrows[savingThrow][1] += self.proficiencyBonus
def addLanguage(self, language):
pass
def addEquipmentProficiency(self, equipment, proficiency):
pass
def selectArmour(self, armour):
selectedArmour = getArmour(armour)
ac = selectedArmour['AC_base']
mod1 = selectedArmour['AC_mod1']
mod2 = selectedArmour['AC_mod2']
ac += self.modifiers[getAbility(mod1)] if mod1 is not None else 0
ac += self.modifiers[getAbility(mod2)] if mod2 is not None else 0
self.ac = ac
self.armour = selectedArmour
return selectedArmour
def selectWeapon(self, weapon):
selectedWeapon = getWeapon(weapon)
self.weapons.append(selectedWeapon)
def levelUp(self):
pass
def print(self):
print(self.race)
print(self.subrace)
print(self.dndClassSpec + ",", self.level)
print(self.background)
print(self.initiative)
print(self.walkSpeed)
print(self.ac)
print(self.proficiencyBonus)
print(self.stats)
print(self.modifiers)
print(self.skills)
print(self.savingThrows)
print(self.armour)
print(self.passivePerception)
print(self.hitDice)
print(self.hp)
def rollStat():
stats = []
for _ in range(4):
stats.append(random.randint(1, 6))
stats.remove(min(stats))
return sum(stats)
def generateStatArray():
stats = []
for _ in range(numStat):
stats.append(rollStat())
return stats
def fetchRaces():
db = sqlConnect()
mycursor = db.cursor(dictionary=True)
mycursor.execute("SELECT * FROM RACES")
for race in mycursor:
playableRaces.append(race)
#Should be called after selectRace()
def fetchSubraces():
db = sqlConnect()
selectedRaceID = selectedRace['rid']
mycursor = db.cursor(dictionary=True)
query = "SELECT subrace FROM subraces WHERE rid =" + str(selectedRaceID)
mycursor.execute(query)
for subrace in mycursor:
selectableSubraces.append(subrace)
def fetchAbilities():
db = sqlConnect()
mycursor = db.cursor(dictionary=True)
query = "SELECT * FROM abilities"
mycursor.execute(query)
for ability in mycursor:
abilitiesList.append(ability)
def fetchSkills():
db = sqlConnect()
mycursor = db.cursor(dictionary=True)
query = "SELECT * FROM skills"
mycursor.execute(query)
for skill in mycursor:
skillsList.append(skill)
def fetchClasses():
db = sqlConnect()
mycursor = db.cursor(dictionary=True)
query = "SELECT * FROM classes"
mycursor.execute(query)
for dndClass in mycursor:
classesList.append(dndClass)
#Should be called after selectClass()
def fetchClassSpecs():
db = sqlConnect()
selectedClassID = selectedClass['cid']
mycursor = db.cursor(dictionary=True)
query = "SELECT class, primaryAbilityID, secondaryAbilityID FROM classspecs WHERE cid =" + str(selectedClassID)
mycursor.execute(query)
for classSpec in mycursor:
selectableClassSpecs.append(classSpec)
def fetchBackgrounds():
db = sqlConnect()
mycursor = db.cursor(dictionary=True)
query = "SELECT background, skillProficiency1ID, skillProficiency2ID FROM backgrounds"
mycursor.execute(query)
for background in mycursor:
backgroundsList.append(background)
def fetchArmours():
db = sqlConnect()
mycursor = db.cursor(dictionary=True)
query = "SELECT name, AC_base, AC_mod1, AC_mod2, classification FROM armour"
mycursor.execute(query)
for armour in mycursor:
armoursList.append(armour)
def fetchWeapons():
db = sqlConnect()
mycursor = db.cursor(dictionary=True)
query = "SELECT name, rolls, damage, damage_type, weapon_type, weapon_range, properties FROM weapons"
mycursor.execute(query)
for weapon in mycursor:
weaponsList.append(weapon)
def sqlConnect():
db = mysql.connector.connect(
host="localhost",
user="root",
passwd="<PASSWORD>",
auth_plugin='mysql_native_password',
database='npc_mancer_db'
)
return db
#Should be called after fetch method for data
def selectRace(race):
global selectedRace
selectedRace = getRace(race)
#Should be called after fetch method for data
def selectSubrace(subrace):
global selectedSubrace
selectedSubrace = getSubrace(subrace)
#Should be called after fetch method for data
def selectClass(dndClass):
global selectedClass
selectedClass = getClass(dndClass)
#Should be called after fetch method for data
def selectClassSpec(dndClassSpec):
global selectedClassSpec
selectedClassSpec = getClassSpec(dndClassSpec)
def selectBackground(background):
global selectedBackground
selectedBackground = getBackground(background)
def getRace(name):
return list(filter(lambda race : race['race'] == name, playableRaces))[0]
def getSubrace(name):
return list(filter(lambda subrace : subrace['subrace'] == name, selectableSubraces))[0]['subrace']
def getAbility(id):
return list(filter(lambda ability : ability['aid'] == id, abilitiesList))[0]['ability']
def getSkill(id):
return list(filter(lambda skill : skill['sid'] == id, skillsList))[0]['skill']
def getClass(name):
return list(filter(lambda dndClass : dndClass['class'] == name, classesList))[0]
def getClassSpec(name):
return list(filter(lambda dndClassSpec : dndClassSpec['class'] == name, selectableClassSpecs))[0]
def getBackground(name):
return list(filter(lambda background : background['background'] == name, backgroundsList))[0]
def getArmour(name):
return list(filter(lambda armour : armour['name'] == name, armoursList))[0]
def getWeapon(name):
return list(filter(lambda weapon : weapon['name'] == name, weaponsList))[0]
fetchAbilities()
fetchSkills()
fetchRaces()
fetchClasses()
fetchBackgrounds()
fetchArmours()
fetchWeapons()
selectRace("Half-Elf")
fetchSubraces()
#selectSubrace("Wood Elf")
selectClass("Ranger")
fetchClassSpecs()
selectClassSpec("Ranger (Dex)")
selectBackground("Urchin")
steve = Character([selectedRace, selectedSubrace], [selectedClass, selectedClassSpec], selectedBackground, 9)
steve.addSkillProficiency("Perception")
steve.print()
|
42d543653374b7b689fb66566f5214cad9e28e5b
|
[
"Markdown",
"Python"
] | 5 |
Python
|
JonCels/NPC-mancer
|
f6140cc11beea0757efcc2c7b7c00a04a02501bc
|
95f88a192c2268fbbf6c664f057489a76997d1e5
|
refs/heads/develop
|
<file_sep>var fs = require('fs');
module.exports = function(grunt) {
var pkg = grunt.file.readJSON('package.json');
var banner = [ "<%= pkg.name %> v<%= pkg.version %>", "The MIT License (MIT)", "Copyright (c) 2014 <%= pkg.author %>" ].join("\n * ").trim();
grunt.initConfig({
pkg: pkg,
concat: {
options: {
banner: "/*! " + banner + " */\n\n"
},
copy: {
files: {
'dist/ripple.js': ["src/ripple.js"],
'dist/ripple.css': ["src/ripple.css"]
}
}
},
cssmin: {
options: {
banner: "/*! " + banner + " */",
preserveComments: 'some'
},
main: {
files: {
'dist/ripple.min.css': ['src/ripple.css']
}
}
},
jshint: {
all: ['src/ripple.js']
},
uglify: {
options: {
banner: "/*! " + banner + " */\n",
footer: "$.ripple.version = \"<%= pkg.version %>\";",
preserveComments: 'some'
},
main: {
files: {
'dist/ripple.min.js': ['src/ripple.js']
}
}
},
watch: {
scripts: {
files: 'src/*.js',
tasks: ['jshint', 'uglify']
},
styles: {
files: 'src/*.css',
tasks: ['cssmin']
},
manifests: {
files: ['package.json'],
tasks: ['sync_versions']
}
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['jshint', 'concat', 'uglify', 'cssmin']);
grunt.registerTask('develop', ['jshint', 'concat', 'uglify', 'cssmin', 'watch']);
};
|
c413b6fb3847562dfe3287ec1ca0f777f0a6cf49
|
[
"JavaScript"
] | 1 |
JavaScript
|
atomiks/Ripple.js
|
8aabef6de31132bf277baf3db0f234941b75ac0b
|
1527f2442a04f622a9d58a1b1435e6a798b568c5
|
refs/heads/master
|
<repo_name>ryush00/Fancy-Portals<file_sep>/Fancy-Portals/src/com/sniperzciinema/fancyportals/Util/FileManager.java
package com.sniperzciinema.fancyportals.Util;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Level;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
public class FileManager {
Plugin plugin;
private YamlConfiguration portals;
private File portalsFile;
public FileManager(Plugin plugin)
{
this.plugin = plugin;
}
// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
public FileConfiguration getConfig() {
return this.plugin.getConfig();
}
public FileConfiguration getPortals() {
if (this.portals == null)
{
reloadPortals();
savePortals();
}
return this.portals;
}
public void reloadConfig() {
this.plugin.reloadConfig();
}
public void reloadPortals() {
if (this.portalsFile == null)
this.portalsFile = new File(this.plugin.getDataFolder(), "Portals.yml");
this.portals = YamlConfiguration.loadConfiguration(this.portalsFile);
InputStream defConfigStream = this.plugin.getResource("Portals.yml");
if (defConfigStream != null)
{
YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigStream);
if (!this.portalsFile.exists() || (this.portalsFile.length() == 0))
this.portals.setDefaults(defConfig);
}
}
public void saveConfig() {
this.plugin.saveConfig();
}
public void savePortals() {
if ((this.portals == null) || (this.portalsFile == null))
return;
try
{
getPortals().save(this.portalsFile);
}
catch (IOException ex)
{
Bukkit.getLogger().log(Level.SEVERE, "Could not save config " + this.portalsFile, ex);
}
}
}
<file_sep>/Fancy-Portals/src/com/sniperzciinema/fancyportals/FancyPortals.java
package com.sniperzciinema.fancyportals;
import java.io.IOException;
import java.util.ArrayList;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import com.sniperzciinema.fancyportals.Portals.Portal;
import com.sniperzciinema.fancyportals.Portals.PortalHandler;
import com.sniperzciinema.fancyportals.Portals.PortalHandler.PortalType;
import com.sniperzciinema.fancyportals.Util.Coords;
import com.sniperzciinema.fancyportals.Util.FileManager;
import com.sniperzciinema.fancyportals.Util.Metrics;
import com.sniperzciinema.fancyportals.Util.Updater;
import com.sniperzciinema.fancyportals.Util.FancyMessage.FancyMessage;
public class FancyPortals extends JavaPlugin {
private PortalHandler portalHandler;
private FileManager fileManager;
@Override
public void onDisable() {
}
@Override
public void onEnable() {
this.fileManager = new FileManager(this);
this.portalHandler = new PortalHandler(this, this.fileManager);
startMetrics();
getConfig().options().copyDefaults(true);
saveConfig();
if (getConfig().getBoolean("Check For Updates"))
checkForUpdates(78080);
// Register the event listener
getServer().getPluginManager().registerEvents(new Listeners(this, this.portalHandler), this);
Bukkit.getMessenger().registerOutgoingPluginChannel(this, "BungeeCord");
}
void checkForUpdates(int id) {
Updater updater = new Updater(this, id, getFile(), Updater.UpdateType.NO_DOWNLOAD, true);
boolean update = updater.getResult() == Updater.UpdateResult.UPDATE_AVAILABLE;
String updateName = updater.getLatestName();
String updateLink = updater.getLatestFileLink();
if (update)
for (Player player : Bukkit.getOnlinePlayers())
if (player.isOp())
new FancyMessage(
ChatColor.YELLOW + "Update for FancyPortals Availble: (" + ChatColor.DARK_AQUA + ChatColor.BOLD + updateName + ChatColor.YELLOW + ")").link(updateLink).tooltip("Click here to open the link").send(player);
}
void startMetrics() {
try
{
Metrics metrics = new Metrics(this);
metrics.start();
System.out.println("Metrics was started!");
}
catch (IOException e)
{
System.out.println("Metrics was unable to start...");
}
}
public FileManager getFileManager() {
return this.fileManager;
}
public PortalHandler getPortalHandler() {
return this.portalHandler;
}
@SuppressWarnings("deprecation")
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if (cmd.getName().equalsIgnoreCase("FancyPortals"))
{
Player p = (Player) sender;
if (!p.hasPermission("FancyPortals.Create"))
{
sender.sendMessage("" + ChatColor.RED + ChatColor.BOLD + "Invalid Permissions!");
return true;
}
// /////////////////////////////////////////////////////// CREATE /////////////////////////////////////////////////////////////////
if ((args.length >= 3) && (args[0].equalsIgnoreCase("Create") || args[0].equalsIgnoreCase("C")))
{
String portal = args[1];
if (this.portalHandler.getPortal(portal) != null)
{
sender.sendMessage("" + ChatColor.RED + ChatColor.BOLD + "FancyPortal Already Exists!");
return true;
}
if (p.getTargetBlock(null, 50).getType().isSolid())
{
sender.sendMessage("" + ChatColor.RED + ChatColor.BOLD + "Invalid FancyPortal Block. Please use a non Solid block!");
return true;
}
// Create target string
StringBuilder arg = new StringBuilder(args[2]);
for (int argC = 3; argC < args.length; argC++)
arg.append(" ").append(args[argC]);
PortalType portalType;
String target = arg.toString();
// ============================================================ LOCATION <world,x,y,z[,yaw,pitch]> =================================
if (target.contains(","))
{
portalType = PortalType.LOCATION;
if (StringUtils.countMatches(target, ",") != 3 && StringUtils.countMatches(target, ",") != 5)
{
sender.sendMessage("" + ChatColor.RED + ChatColor.BOLD + "Unable to create a Target Portal with those coordinates!");
sender.sendMessage("§7Remember the layout: §e§o/FP Create PortalToSky world,x,y,z[,yaw,pitch]");
return true;
}
}
// ============================================================ COMMANDS ===========================================================
else if (target.contains("/"))
{
// ========================= Server Command =====================
if (target.toLowerCase().startsWith("s"))
{
portalType = PortalType.SERVER_COMMAND;
target = target.replaceFirst(target.startsWith("S/") ? "S/" : "s/", "");
}
// ========================= Player Command =====================
else
{
portalType = PortalType.PLAYER_COMMAND;
target = target.replaceFirst("/", "");
}
}
// ============================================================ BUNGEE =============================================================
else
portalType = PortalType.BUNGEE;
// ============================================================= CREATE ===============================================
ArrayList<String> blockArray = this.portalHandler.getAdjacentBlocks(p.getTargetBlock(null, 50).getLocation());
this.portalHandler.createPortal(portal, portalType, blockArray, target);
sender.sendMessage(ChatColor.RED + "FancyPortal Created: " + ChatColor.GREEN + "Successfully created a " + portalType.toString() + " portal " + args[1]);
}
// /////////////////////////////////////////////////////// REMOVE /////////////////////////////////////////////////////////////////
else if ((args.length == 2) && (args[0].equalsIgnoreCase("Remove") || args[0].equalsIgnoreCase("R")))
{
if (this.portalHandler.getPortal(args[1]) != null)
{
this.portalHandler.removePortal(this.portalHandler.getPortal(args[1]));
sender.sendMessage(ChatColor.RED + "FancyPortal Removed: " + ChatColor.GREEN + "Successfully removed portal " + args[1]);
}
else
sender.sendMessage(ChatColor.RED + "Invalid FancyPortal: " + ChatColor.GREEN + "This portal apperently doesn't exist!");
}
// /////////////////////////////////////////////////////// INFO /////////////////////////////////////////////////////////////////
else if ((args.length == 2) && (args[0].equalsIgnoreCase("Info") || args[0].equalsIgnoreCase("I")))
{
String portalName = args[1];
if (this.portalHandler.getPortal(portalName) == null)
{
sender.sendMessage("" + ChatColor.RED + ChatColor.BOLD + "FancyPortal Doesn't Exists!");
return true;
}
else
{
Portal portal = this.portalHandler.getPortal(portalName);
sender.sendMessage("");
sender.sendMessage("" + ChatColor.YELLOW + ChatColor.BOLD + "----------[ " + portal.getName() + " ]----------");
sender.sendMessage("");
sender.sendMessage(ChatColor.AQUA + "" + ChatColor.BOLD + "Location: " + ChatColor.WHITE + new Coords(
portal.getCoords().get(0)).asStringIgnoreYawAndPitch());
sender.sendMessage(ChatColor.GRAY + "" + ChatColor.BOLD + "Portal Block: " + ChatColor.WHITE + new Coords(
portal.getCoords().get(0)).asLocationIgnoreYawAndPitch().getBlock().getType());
sender.sendMessage(ChatColor.LIGHT_PURPLE + "" + ChatColor.BOLD + "Portal Type: " + ChatColor.WHITE + portal.getType().toString());
if (portal.getType() == PortalType.BUNGEE)
sender.sendMessage(ChatColor.YELLOW + "" + ChatColor.BOLD + "Bungee Target: " + ChatColor.WHITE + portal.getBungeeTarget());
else if (portal.getType() == PortalType.LOCATION)
sender.sendMessage(ChatColor.GREEN + "" + ChatColor.BOLD + "Location Target: " + ChatColor.WHITE + portal.getLocationTarget());
else if (portal.getType() == PortalType.PLAYER_COMMAND)
sender.sendMessage(ChatColor.BLUE + "" + ChatColor.BOLD + "Player Command: " + ChatColor.WHITE + portal.getCommand());
else if (portal.getType() == PortalType.SERVER_COMMAND)
sender.sendMessage(ChatColor.RED + "" + ChatColor.BOLD + "Server Command: " + ChatColor.WHITE + portal.getCommand());
sender.sendMessage("");
new FancyMessage(" §7§l[§4§nRemove Portal§7§l]").tooltip("§aClick to suggest §cremoving§a this portal.").suggest("/FP Remove " + portal.getName()).send(p);
sender.sendMessage("");
}
}
// /////////////////////////////////////////////////////// LIST /////////////////////////////////////////////////////////////////
else if ((args.length == 1) && (args[0].equalsIgnoreCase("List") || args[0].equalsIgnoreCase("L")))
{
int i = 1;
sender.sendMessage("");
sender.sendMessage("" + ChatColor.YELLOW + ChatColor.BOLD + "---------------[ FancyPortals ]---------------");
for (Portal portal : this.portalHandler.getPortals())
{
new FancyMessage(i + ". ").then("" + ChatColor.YELLOW + ChatColor.BOLD + portal.getName()).command("/FancyPortals Info " + portal.getName()).tooltip(ChatColor.GRAY + "" + ChatColor.ITALIC + "Click to see Portals Info").send(p);
i++;
}
}
// /////////////////////////////////////////////////////// HELP /////////////////////////////////////////////////////////////////
else
{
sender.sendMessage("");
sender.sendMessage("" + ChatColor.WHITE + ChatColor.BOLD + "-------------[ FancyPortals Help ]-------------");
new FancyMessage("§c§l/FancyPortals §eCreate §a<PortalName> §d<Target>").itemTooltip(FancyMessage.getFancyMessageItem("Create", "To Create a FancyPortal:", "§e§l/FP Create <Portal Name> <target>", " ", "§fNow for target you'd want to type:", "§fworld,x,y,z §a<- Teleport to Specific Location", "§fworld,x,y,z,yaw,pitch §a<- Teleport to Specific Location", "§fServerName §a<- Teleport to a Bungee Server", "§f/Command §a<- Make the player use a command", "§fs/Command §a<- Make the server use the command", " ", "§7Ex: §o/FP Create PortalToSpawn /Spawn", "§7Ex: §o/FP Create PortalToHub Hub", "§7Ex: §o/FP Create PortalToSky world,10,100,10,-1.5,90", "§7Ex: §o/FP Create PortalToSay s/Say Hello <player>")).suggest("/FP Create <PortalName> [S]<Bungee/world,x,y,z,yaw,pitch/Command>").send(p);
new FancyMessage("§c§l/FancyPortals §eRemove §a<PortalName>").itemTooltip(FancyMessage.getFancyMessageItem("Remove", "To Remove a Fancy Portal:", "§e§l/FP Remove <Portal Name>")).suggest("/FP Remove <PortalName>").send(p);
new FancyMessage("§c§l/FancyPortals §eInfo §a<PortalName>").itemTooltip(FancyMessage.getFancyMessageItem("Info", "Show the info for that FancyPortals", "§e§l/FP Info <Portal Name>")).suggest("/FP Info <Portal Name>").send(p);
new FancyMessage("§c§l/FancyPortals §eList").itemTooltip(FancyMessage.getFancyMessageItem("List", "To show a list of all FancyPortals", "§e§l/FP List", " ", "§7[§eTip§7]§f Try clicking a portal in the list!")).suggest("/FP List").send(p);
sender.sendMessage("");
}
}
return true;
}
}
|
b11526ccef2f2c9719d11b3d1e1a8364f20e6f79
|
[
"Java"
] | 2 |
Java
|
ryush00/Fancy-Portals
|
dedc64359a492b2866134758b6e5d524178864ce
|
fc198e9fe959910240db80437d3067d57aec6a78
|
refs/heads/master
|
<file_sep>package com.example.android.moviesapp.DbData;
import android.net.Uri;
import android.provider.BaseColumns;
/**
* Created by evi on 17. 3. 2018.
*/
public class FavoritesContract {
public static final String AUTHORITY = "com.example.android.moviesapp";
public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + AUTHORITY);
public static final String PATH_FAVORITES = "favorites";
public static final class FavoritesEntry implements BaseColumns {
public static final Uri CONTENT_URI = BASE_CONTENT_URI.buildUpon().appendPath(PATH_FAVORITES).build();
public static final String TABLE_NAME = "favorites";
public static final String COLUMN_MOVIE_ID = "movieId";
public static final String COLUMNN_TITLE = "title";
public static final String COLUMN_POSTER_URL = "posterUrl";
}
}
<file_sep># MoviesApp
App displays **20 movies** from https://www.themoviedb.org **API**. User can **sort** movies by Popularity or by Rating. Each movie has a **detail screen** with synopsis, rating, trailers and reviews. Movie can be added to **Favorite Movies** and can be displayed later using the Favorites option in Settings. This project was done as a part of **Udacity Android Developer Nanodegree**.
**App Preview:**

**Main features:**
- App uses **Retrofit library** - to pull and parse data about movies from www.themoviedb.org.
- App uses **Picasso library** to display movies' posters on main navigation screen.
- App **opens movie trailer** using implicit intent.
- The **list of favorite movies** is stored in local **SQLite database** using **Content Provider**.
- App uses **Tab layout** for displaying movies's detail.
(To be able to use app properly, insert TMDB API key in app:build.gradle within the defaultConfig)

<file_sep>package com.example.android.moviesapp.data;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by evi on 12. 3. 2018.
*/
public class Reviews {
@SerializedName("author")
private String mAuthor;
@SerializedName("content")
private String mContent;
public Reviews(String author, String content) {
mAuthor = author;
mContent = content;
}
public String getAuthor() {
return mAuthor;
}
public String getContent() {
return mContent;
}
public static class ReviewsResult {
@SerializedName("results")
private List<Reviews> reviews;
public List<Reviews> getReviewsList() {
return reviews;
}
}
}
<file_sep>package com.example.android.moviesapp;
import android.content.Context;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class DetailActivity extends AppCompatActivity {
private static final String LOG_TAG = "DetailActivity";
FragmentPagerAdapter adapterViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
ViewPager vpPager = findViewById(R.id.pager_header);
adapterViewPager = new DetailMoviePagerAdapter(this, getSupportFragmentManager());
vpPager.setAdapter(adapterViewPager);
TabLayout tabLayout = findViewById(R.id.tabs);
tabLayout.setupWithViewPager(vpPager);
}
// Viewpager
public static class DetailMoviePagerAdapter extends FragmentPagerAdapter {
private static int NUMBER_ITEMS = 3;
private Context mContext;
public DetailMoviePagerAdapter(Context context, FragmentManager fragmentManager) {
super(fragmentManager);
mContext = context;
}
@Override
public Fragment getItem(int position) {
if (position == 0) {
return new DetailsFragment();
} else if (position == 1) {
return new TrailersFragment();
} else {
return new ReviewsFragment();
}
}
@Override
public int getCount() {
return NUMBER_ITEMS;
}
@Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return mContext.getString(R.string.details);
} else if (position == 1) {
return mContext.getString(R.string.trailers);
} else {
return mContext.getString(R.string.reviews);
}
}
}
}
|
cf582be1ce1bd3e44d8ff5372bdb58456627e71d
|
[
"Markdown",
"Java"
] | 4 |
Java
|
evii/MoviesApp
|
8c12285e28fedc38ee47abdc4b507e8cda173c22
|
4136629a6ece2a99b6a8f1459dc7412df2999c2d
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.