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>#include <stdlib.h>
#include <stdio.h>
#include "uuid4.h"
int main(void) {
char buf[UUID4_LEN];
uuid4_generate(buf);
printf("%s\n", buf);
return EXIT_SUCCESS;
}
<file_sep>#include <stdio.h>
#include <string.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
#include "uuid4.h"
int _uuid(lua_State* L)
{
char buf[UUID4_LEN];
uuid4_generate(buf);
lua_pushlstring(L, buf, UUID4_LEN);
return 1;
}
static luaL_Reg libs[] = {
{"gen_uuid", _uuid},
{NULL, NULL}
};
int luaopen_uuid(lua_State* L)
{
luaL_newlib(L, libs);
return 1;
}
|
edd3a9ea8429db96a64a340fe41a89622cad3724
|
[
"C"
] | 2
|
C
|
qyh/uuid4
|
bb4fcc8663a237cb884202bc8c500aacf45099af
|
cb82582582f1d4ca5d6ad57ae13ee20d8ae6e27d
|
refs/heads/main
|
<file_sep># -*- coding: utf-8 -*-
"""
Created on Wed Jan 20 09:23:33 2021
@author: Khoa
"""
import numpy as np
import pandas as pd
df = pd.read_csv(r"C:\Users\Khoa\Desktop\New coding\Project HR Analytics Job change of Data Scientists\aug_train.csv")
#Cleaning up DataFrame values
df['relevent_experience'] = df['relevent_experience'].str.replace('Has relevent experience','Y')
df['relevent_experience'] = df['relevent_experience'].str.replace('No relevent experience','N')
df['enrolled_university'] = df['enrolled_university'].str.replace('Full time course','FT')
df['enrolled_university'] = df['enrolled_university'].str.replace('no_enrollment','N')
df['enrolled_university'] = df['enrolled_university'].str.replace('Part time course','PT')
#Imputing missing data with most frequent values for string and mean for numeric
from sklearn.base import TransformerMixin
class DataFrameImputer(TransformerMixin):
def __init__(self):
"""Impute missing values.
Columns of dtype object are imputed with the most frequent value
in column.
Columns of other types are imputed with mean of column.
"""
def fit(self, X, y=None):
self.fill = pd.Series([X[c].value_counts().index[0]
if X[c].dtype == np.dtype('O') else X[c].mean() for c in X],
index=X.columns)
return self
def transform(self, X, y=None):
return X.fillna(self.fill)
df = DataFrameImputer().fit_transform(df)
#Data transformation by Labelencoder
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
df['city'] = le.fit_transform(df['city'])
df['gender'] = le.fit_transform(df['gender'])
df['relevent_experience'] = le.fit_transform(df['relevent_experience'])
df['enrolled_university'] = le.fit_transform(df['enrolled_university'])
df['education_level'] = le.fit_transform(df['education_level'])
df['major_discipline'] = le.fit_transform(df['major_discipline'])
df['experience'] = le.fit_transform(df['experience'])
df['company_size'] = le.fit_transform(df['company_size'])
df['company_type'] = le.fit_transform(df['company_type'])
df['last_new_job'] = le.fit_transform(df['last_new_job'])
#or use OneHotEncoder although in this case, there seems to be some issues to be fixed tomorrow
from sklearn.preprocessing import OneHotEncoder
onehotencoder = OneHotEncoder()
df = np.array(columnTransformer.fit_transform(df), dtype = np.str)
#start deploying keras model
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from sklearn.model_selection import train_test_split
#using Keras Model
inputs = keras.Input(shape=(13,))
dense = layers.Dense(64,activation='relu')
x = dense(inputs)
x = layers.Dense(64, activation='relu')(x)
outputs = layers.Dense(10)(x)
model = keras.Model(inputs=inputs,outputs=outputs,name='hr_data_science_train_model')
model.summary()
#defining x,y values and its associated train,test values
x = df.iloc[:,0:13]
y = df.iloc[:,13:14]
x = np.matrix(x)
y = np.matrix(y)
x_train, x_test, y_train, y_test = train_test_split(x,y, test_size=0.4,random_state=42)
#compiling model
model.compile(
loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True),
optimizer=keras.optimizers.RMSprop(),
metrics=["accuracy"],)
#Fitting data into model
history = model.fit(x_train,y_train,batch_size=64,epochs=2,validation_split=0.2)
#accuracy measurement
test_scores = model.evaluate(x_test,y_test,verbose=2)
|
4d48e1f32aeeb6a03d0a580b1cb86f359f5bfac7
|
[
"Python"
] | 1
|
Python
|
huykhoapham16/Portfolio
|
52a484c20dcf6aa02f1e1b161bd1980ed549baa9
|
85d48aaf14c845be805c6adc07481c05f056edd9
|
refs/heads/master
|
<file_sep>var Numbers: [Int] = [ ]
print ("Enter, how many numbers you want to read?", terminator: "")
var Count = Int(readLine()!)!
print("To find the greatest number among the \(Count) numbers, enter the first number:" , terminator: "" )
var FirstNumber = Int(readLine()!)!
Numbers.append(FirstNumber);
var Counter = 1
while( Counter < Count ){
print ( "Enter the next number:", terminator: "")
let NextNumber = Int(readLine()!)!
Numbers.append(NextNumber);
Counter = Counter + 1
}
print( "The greatest number among" ,terminator:"")
Counter = 0
for Counter in Numbers{
print( " \(Counter)", terminator: "" )
}
var MaximumNUmber = FirstNumber
Counter = 1
while ( Counter < Count ){
if( Numbers [Counter] > MaximumNUmber ){
MaximumNUmber = Numbers [Counter ]
}
Counter=Counter + 1
}
print(" is \(MaximumNUmber).")
<file_sep>Numbers = []
Count = int (input ("How many numbers you want to read?") )
FirstNumber = int ( input ( 'To read " + str (Count) + "enter the first number:' ) )
Numbers.append ( FirstNumber )
for Counter in range ( 1, Count, 1 ):
NextNumber = int ( input ( 'Enter the next number:' ) )
Numbers.append ( NextNumber )
MaximumNumber = FirstNumber
print ( 'The greatest number among ', end = "" )
for Counter1 in Numbers:
print ( " " + str ( Counter1 ), end = "" )
print ( " is " + str ( max ( Numbers ) ) , end = "" )
print ( '.' )
<file_sep>print ( "Up to which number you want to print natural numbers", terminator : "" )
var Count = Int (readLine()!)!
var Counter = 1
print ( "The first \(Count) natural numbers are", terminator: "")
while ( Counter <= Count ){
print(" \(Counter)", terminator: "")
Counter = Counter + 1
}
print (".")
<file_sep>using System;
class MainClass {
public static void Main (string[] args) {
int Count, Counter;
Console.Write ("How many natural numbers you want to print?");
Count = int.Parse(Console.ReadLine());
Counter = 1;
Console.Write ("The first "+ Count + " natural numbers are");
while (Counter <= Count) {
Console.Write(" "+ Counter);
Counter = Counter + 1;
}
Console.Write(".");
}
}
<file_sep>import java.util.Scanner;
class Main {
public static void main(String[] args) {
int Count;
System.out.print("How many natural numbers you want to print?");
Scanner read = new Scanner( System.in );
Count = read.nextInt();
System.out.print("The first " + Count + " natural numbers are");
for ( int Counter = 1; Counter <= Count; Counter ++ ) {
System.out.print( " " + Counter);
}
System.out.print(".");
}
}<file_sep>print ( "Up to which number you want to print the series?", terminator: "")
var TermValue = Int(readLine()!)!
var TermCounter = 1;
print ( "The series up to \( TermValue ) is", terminator: "")
while ( TermCounter <= TermValue ){
var Counter = 1
var Product = 1
while ( Counter <= TermCounter ){
Product = Product * TermCounter
Counter = Counter + 1
}
if(Product > TermValue){
break
}
else {
print (" \( Product )", terminator: "" )
}
TermCounter=TermCounter+1
}
print ( "." ) <file_sep>#include<stdio.h>
int main(){
int Number1, Number2, Sum;
printf("To add two numbers, enter the first number:");
scanf("%d", &Number1);
printf("Enter the second number:");
scanf("%d", &Number2);
Sum = Number1 + Number2;
printf("The sum of %d and %d is %d.", Number1, Number2, Sum);
return 0;
}
<file_sep>#include <stdio.h>
int main(void) {
int Count, Counter;
printf("How many natural numbers you want to print?");
scanf("%d", &Count);
printf("The first %d natural numbers are", Count);
for ( Counter = 1; Counter <= Count; Counter ++ ) {
printf(" %d", Counter);
}
printf(".");
return 0;
}<file_sep>#include <stdio.h>
int main(void) {
int Numbers[10], Count, Counter, MaximumNumber;
printf("Enter how many numbers you want to read:");
scanf("%d", &Count);
printf("Enter the first number:");
scanf("%d", &Numbers[0]);
for ( Counter = 1; Counter < Count; Counter ++ ) {
printf("Enter the next number:");
scanf("%d", &Numbers[Counter]);
}
MaximumNumber = Numbers[0];
for ( Counter = 1; Counter < Count; Counter ++ ) {
if ( Numbers[Counter] > MaximumNumber ) {
MaximumNumber = Numbers[Counter];
}
}
printf ( "%d is the greatest number among all the numbers.", MaximumNumber);
return 0;
}<file_sep>Number = int ( input ( 'Up to which number you want to print natural numbers:' ) )
print ('The first '+ str(Number) + ' natural numbers are')
for Counter in range ( 0, Number, 1 ):
print (' ' + str ( Counter + 1 ) ,)
print ( '.' )
<file_sep>#include <stdio.h>
int main(void) {
int TermValue, TermCounter, Counter, Product;
printf ("Up to which number you want to print the series?");
scanf( "%d", &TermValue);
TermCounter = 1;
printf("The series up to %d is", TermValue);
while ( TermCounter < TermValue ) {
Counter = 1;
Product = 1;
while ( Counter <= TermCounter ) {
Product = Product * TermCounter;
Counter = Counter + 1;
}
if (Product > TermValue) {
break;
}
else {
printf(" %d",Product);
}
TermCounter = TermCounter + 1;
}
printf(".");
return 0;
}<file_sep>TermValue = int ( input ( "Up to which number you want to print the series 1 4 27 ......... upto n:") )
TermCounter = 1;
print ( 'The series up to ' + str ( TermValue ) + ' is', end ="")
while ( TermCounter < TermValue ):
Counter = 1;
Product = 1;
while ( Counter <= TermCounter ):
Product = Product * TermCounter
Counter = Counter + 1;
if(Product > TermValue):
break
else:
print (" " + str ( Product ), end ="" )
TermCounter=TermCounter+1
print ( '.' )
|
362b5fb76910d25988b759e8529421898651c561
|
[
"Swift",
"C#",
"Python",
"Java",
"C"
] | 12
|
Swift
|
Priya3690/Programs
|
3502af242b71d2edf4b540017d1cb1e3352e7d5b
|
72af9d70e8a4c0ea6ca37fc947df644b19eadea3
|
refs/heads/master
|
<repo_name>jacilynh/sinatra-fwitter-group-project-v-000<file_sep>/app/controllers/users_controller.rb
class UsersController < ApplicationController
get '/users/:slug' do
@user = User.find_by_slug(params[:slug])
erb :'users/show'
end
# display the user signup
get '/signup' do
if !logged_in?
erb :'users/create_user', locals: {message: 'Please sign up first'}
else
redirect to '/tweets'
end
end
# process the form submission of user signup
post '/signup' do
if params[:email] == "" || params[:username] == "" || params[:password] == ""
redirect to '/signup'
else
@user = User.create(:email => params[:email], :username => params[:username], :password => params[:password])
session[:user_id] = @user.id
redirect to '/tweets'
end
end
# display the form to log in
get '/login' do
if !logged_in?
erb :'users/login'
else
redirect to '/tweets'
end
end
# log add the `user_id` to the sessions hash
post '/login' do
user = User.find_by(username: params[:username])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect to '/tweets'
else
redirect to '/signup'
end
end
# logout the user
get '/logout' do
if logged_in?
session.clear
redirect to '/login'
else
redirect to '/'
end
end
end
|
2051cfc26fc404fa9020c50edbc27251920b95e3
|
[
"Ruby"
] | 1
|
Ruby
|
jacilynh/sinatra-fwitter-group-project-v-000
|
1d5d88d5115f2fb359f288702798e81c5ce176a1
|
db145ffcd0709ce2e43b040fbfd7a354b6892b3b
|
refs/heads/master
|
<file_sep>import React from 'react';
import WrappedFilter from '../containers/WrappedFilter';
class FilterList extends React.Component {
render() {
return <p>
Show:{" "}
<WrappedFilter filter="SHOW_ALL" label="All" />{", "}
<WrappedFilter filter="SHOW_PENDING" label="Pending" />{", "}
<WrappedFilter filter="SHOW_COMPLETED" label="Completed" />
</p>
}
}
export default FilterList;
<file_sep>import React, { PropTypes } from 'react';
class Filter extends React.Component {
static propTypes = {
active: PropTypes.bool.isRequired,
label: PropTypes.string.isRequired,
onClick: PropTypes.func.isRequired
}
render() {
const { active, label, onClick } = this.props;
if (active)
return <span>{label}</span>;
else
return <a href="#" onClick={e => {
e.preventDefault();
onClick();
} }
>
{label}
</a>;
}
}
export default Filter;
<file_sep>import React from 'react';
import NewTodo from '../containers/NewTodo';
import WrappedTodoList from '../containers/WrappedTodoList';
import FilterList from './FilterList';
class App extends React.Component {
render() {
return <div>
<NewTodo />
<WrappedTodoList />
<FilterList />
</div>
}
}
export default App;
|
6c7ec0a16c3c8091048fabc697add4419b956593
|
[
"JavaScript"
] | 3
|
JavaScript
|
Gary92/6_redux_todo_new
|
ea45a53008cf2e19032c575801a32680e3026175
|
a192506b4b5e537ac59e59fb6e4b3c57dc48523c
|
refs/heads/master
|
<repo_name>moniqueshenouda/Systems-Programming<file_sep>/SIC-XE/code/include/Entry.h
#ifndef ENTRY_H
#define ENTRY_H
#include <string>
#include<cstring>
using namespace std;
class Entry
{
public:
int loc ;
string label , op_code , operand ,comment,error,ObjectCode;
Entry();
Entry(int x , string a , string b , string c , string d,string e, string o);
virtual ~Entry();
protected:
private:
};
#endif // ENTRY_H
<file_sep>/SIC-XE/code/include/Utilities.h
#ifndef UTILITIES_H
#define UTILITIES_H
#include <fstream>
#include <string>
#include<iostream>
#include<stdio.h>
#include<vector>
#include<cstring>
#include <cctype>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include<math.h>
#include"Entry.h"
#define INF 1000000000
#define MOD 1000000007
#define MAX 100000
using namespace std;
class Utilities
{
public:
map <string,int>symbolTable;
vector <string> opc;
vector <string> n1;
vector <string> n2;
vector <string> regmem;
vector <string> objc;
map<string,bool>absolute;
bool firstEntering=true;
vector<Entry>table;
vector <string> label;
int CURRENTADRESS=-1;
map<string, string>mnemonicNumber;
int base=0;
bool error1;
bool error2;
int sizeall=0;
Utilities();
bool checkSpace(string a);
void checkEndLine(string line);
void fillingMap();
void parse(string line );
void parse_sic(string line );
void labtable(string line);
void threeWord ( vector<string> line,int typeByte,vector<string>comment);
void twoWord ( vector<string> line,int typeByte,vector<string>comment);
void oneWord ( vector<string> line,vector<string> comment,int byt);
bool duplicateLable(string a);
int validateOpcode(string a,int check);
int check_operand(string opcode,string oper);
string Tolower(string str);
void buildObjectFile();
void generateObjectFile();
string modifyLocation(int loc , int len);
int Tointeger(string str);
int todecimal(string a);
bool checkWord(string a);
int checkByte(string a);
int byte(string a);
int stoi(string s);
string Comment(vector<string>a);
int checkOrg(string a);
int checkEqu(string a,string label);
void tokenize(std::string const &str, const char delim,
std::vector<std::string> &out);
bool is_number(const std::string& s);
string binary_to_hexa(string a);
string format1(string line);
string format2(string opCode, string operand );
string format3_4(int index,string instr,string operand,int current_address);
vector <string>splitLine(string line);
void initRegisters();
int eval_address(string a,int index);
void objectCode();
virtual ~Utilities();
protected:
private:
};
#endif // UTILITIES_H
<file_sep>/SIC-XE/code/src/Utilities.cpp
#include "Utilities.h"
#include<string>
#include<iostream>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
int labelch=0;
int labeleq=0;
string startlbl="";
vector<pair<string, int > >objectFile;
vector<int >objectFileFormat4;
string programName;
int startAdress;
string baseadd="";
Utilities::Utilities()
{
//ctor
}
string Utilities::Comment(vector<string>a)
{
string temp="";
for(int i=0; i<a.size(); i++)
temp+=a[i]+" ";
return temp;
}
int Utilities::checkByte(string a)
{
if(a.size()<4)
return -1;
if(a[0]=='x'&&a[1]=='\''&&a[a.size()-1]=='\'')
{
if((a.size()-3)%2==1)
return -1;
for(int i=2; i<a.size()-1; i++)
{
if((a[i]>='0'&&a[i]<='9')||(a[i]>='a'&&a[i]<='f'))
{
}
else
return -2;
}
return ((a.size()-3)/2);
}
else if(a[0]=='c'&&a[1]=='\''&&a[a.size()-1]=='\'')
{
return (a.size()-3);
}
else
return -1;
}
bool Utilities::checkWord(string a)
{
if(a.size()==1)
{
if((a[0]<'0'||a[0]>'9'))
return false;
return true;
}
if(a.size()==2&&a[1]=='-')
return false;
if(a[0]!='@'&&a[0]!='#'&&a[0]!='-'&&(a[0]<'0'||a[0]>'9'))
return false;
for(int i=1; i<a.size(); i++)
{
if(a[i]<'0'||a[i]>'9')
{
if(i==1)
{
if(a[1]=='-'&&(a[0]=='#'||a[0]=='@'))
{
}
else
return false;
}
else
return false;
}
}
return true;
}
int Utilities::todecimal(string a)
{
int ans=0;
int t=a.size()-1;
for(int i=0; i<a.size(); i++)
{
if(a[i]=='A'||a[i]=='a')
{
ans+=10*pow(16,t);
}
else if(a[i]=='B'||a[i]=='b')
{
ans+=11*pow(16,t);
}
else if(a[i]=='C'||a[i]=='c')
{
ans+=12*pow(16,t);
}
else if(a[i]=='D'||a[i]=='d')
{
ans+=13*pow(16,t);
}
else if(a[i]=='E'||a[i]=='e')
{
ans+=10*pow(14,t);
}
else if(a[i]=='F'||a[i]=='f')
{
ans+=10*pow(15,t);
}
else if(a[i]>='0'&&a[i]<='9')
{
ans+=(a[i]-'0')*pow(16,t);
}
else
return -1;
t--;
}
return ans;
}
int Utilities::Tointeger(string str)
{
int res = 0 ;
for(int i = 0 ; i < str.size() ; i++)
{
if(str[i]<'0'||str[i]>'9')
return -1;
res = res*10 + (int)(str[i]-'0');
}
return res;
}
string Utilities::Tolower(string str)
{
for(int i=0 ; i <str.size() ; i++)
str[i]=tolower(str[i]);
return str;
}
int Utilities:: check_operand(string opcode,string oper)
{
int error;
if(opcode.compare("tixr")==0)
{
if(oper.compare("a")==0||oper.compare("s")==0||oper.compare("t")==0||oper.compare("x")==0
||oper.compare("b")==0||oper.compare("l")==0)
{
error=0;
return error;
}
else
{
if(oper.size()==1)
error=1;
else
error=2;
return error;
}
}
else if(opcode.compare("addr")==0||opcode.compare("subr")==0||opcode.compare("compr")==0||opcode.compare("rmo")==0)
{
if(oper.size()==3)
{
if((oper[0]=='a'||oper[0]=='s'||oper[0]=='t'||oper[0]=='x'||oper[0]=='b'||oper[0]=='l')&&
oper[1]==','&&(oper[2]=='a'||oper[2]=='s'||oper[2]=='t'||oper[2]=='x'||oper[0]=='b'
||oper[0]=='l'))
{
error=0;
return error;
}
else
{
error=1;
return error;
}
}
else
{
error=2;
return error;
}
}
else
{
if(oper[0]=='#'||oper[0]=='@')
{
if(oper.size()>=2&&oper[oper.size()-1]=='x'&&oper[oper.size()-2]==',')
{
error=2;
return error;
}
else
{
if(oper[0]=='#')
{
int countop=0;
oper.erase(std::remove(oper.begin(), oper.end(),'#'), oper.end());
for(int i=0; i<oper.size(); i++)
{
if(oper[i]>='0'&&oper[i]<='9')
countop++;
}
if(countop==oper.size())
{
error=0;
return error;
}
}
else if(oper[0]=='@')
oper.erase(std::remove(oper.begin(), oper.end(),'@'), oper.end());
for(int i=0; i<label.size(); i++)
{
if(oper.compare(label[i])==0)
{
error=0;
break;
}
else
{
error=3;
}
}
return error;
}
}
else
{
if((opcode.compare("resw")!=0)&&(opcode.compare("resb")!=0)&&(opcode.compare("base")!=0)&&(opcode.compare("byte")!=0)&&(opcode.compare("word")!=0)&&(opcode.compare("equ")!=0)&&opcode.compare("org")!=0)
{
int comma;
for(int i=0; i<oper.size(); i++)
{
if(oper[i]==',')
{
comma=1;
break;
}
else
comma=0;
}
if(comma==1)
{
if(oper[oper.size()-1]=='x'&&oper[oper.size()-2]==',')
{
oper.erase(std::remove(oper.begin(), oper.end(),'x'), oper.end());
oper.erase(std::remove(oper.begin(), oper.end(),','), oper.end());
}
else
{
error=2;
return error;
}
}
int countop2=0;
for(int i=0; i<oper.size(); i++)
{
if(oper[i]>='0'&&oper[i]<='9')
countop2++;
}
if(countop2==oper.size()&&oper[0]!='#')
{
error=2;
return error;
}
else if((oper.find("+")!=-1)||(oper.find("/")!=-1)||(oper.find("*")!=-1)||(oper.find("-")!=-1))
{
int cot=0;
int c=0;
string opr;
for( int n=0; n<oper.size(); n++)
{
if(oper[n]=='+'||oper[n]=='-'||oper[n]=='*'||oper[n]=='/')
{
opr+=oper[n];
oper[n]='.';
c++;
}
}
vector<string> s;
tokenize(oper, '.', s);
int j,m,i;
for(j=0; j<s.size(); j++)
{
for(i=0; i<label.size(); i++)
{
if(s[j].compare(label[i])==0||is_number(s[j]))
{
error=0;
break;
}
else
{
error=3;
}
}
}
return error;
}
else
{
for(int i=0; i<label.size(); i++)
{
if(oper.compare(label[i])==0)
{
error=0;
break;
}
else
{
error=3;
}
}
return error;
}
}
}
}
}
int Utilities::validateOpcode(string a, int check)
{
int found=0,i;
int error0=1;
int error1=2;
int error2=3;
int place=-1;
for( i=0; i<opc.size(); i++)
{
if(a.compare(opc[i])==0)
{
found=1;
place=i;
break;
}
}
if(found==1&&a!="org"&&a!="equ"&&a!="base")
{
if(check==1&&n2[i].compare("4")==0||check==0)
return error0;
else
return error2;
}
else if(a=="org"||a=="equ"||a=="base")
return 6;
else
{
return error1;
}
}
int Utilities::byte(string a)
{
int p;
if (a[0]=='+')
{
a.erase(std::remove(a.begin(), a.end(),'+'), a.end());
for(int i=0; i<opc.size(); i++)
{
if(a.compare(opc[i])==0)
{
p=i;
break;
}
}
return stoi(n2[p]);
}
else
{
for(int i=0; i<opc.size(); i++)
{
if(a.compare(opc[i])==0)
{
p=i;
break;
}
}
return stoi(n1[p]);
}
}
bool Utilities::duplicateLable(string a)
{
if( symbolTable.find(a ) == symbolTable.end() )
return false;
return true;
}
void Utilities::oneWord ( vector<string> line,vector<string> comment,int byt)
{
string temp=Comment(comment);
table.push_back(Entry(CURRENTADRESS,"",line[0],"",temp,"",""));
CURRENTADRESS+=byt;
}
void Utilities::twoWord ( vector<string> line,int typeByte,vector<string>comment)
{
string temp=Comment(comment);
table.push_back(Entry(CURRENTADRESS,"",line[0],line[1],temp,"",""));
if(typeByte!=6)
CURRENTADRESS+=typeByte;
else if(typeByte==6)
{
if(line[0].compare("org")==0)
{
int org=checkOrg(line[1]);
if(org==-1)
{
table[table.size()-1].error="****Error: Invalid Operand";
}
CURRENTADRESS=org;
}
else if(line[0].compare("base")==0)
{
int found =0;
for(int i=0; i<label.size(); i++)
{
if(line[1].compare(label[i])==0)
{
baseadd=line[1];
found=1;
break;
}
}
if(found==0)
table[table.size()-1].error="****Error: Symbol not found";
}
}
}
void Utilities::threeWord ( vector<string> line,int typeByte,vector<string>comment)
{
string temp=Comment(comment);
symbolTable[line[0]]=CURRENTADRESS;
table.push_back(Entry(CURRENTADRESS,line[0],line[1],line[2],temp,"",""));
if(typeByte!=5)
CURRENTADRESS+=typeByte;
else
{
if(line[1]=="equ")
{
int adress=checkEqu(line[2],line[0]);
if(adress==-1)
{
table[table.size()-1].error="****Error: Invalid Operand";
}
else
{
symbolTable[line[0]]=adress;
}
}
else if(line[1]=="byte")
{
int check=checkByte(line[2]);
if(check!=-1&&check!=-2)
CURRENTADRESS+=check;
else if(check==-2)
table[table.size()-1].error="****Error: not a hexadecimal string";
else
table[table.size()-1].error="****Error: Invalid Operand";
}
else if(line[1]=="word")
{
if(checkWord(line[2]))
CURRENTADRESS+=3;
else
table[table.size()-1].error="****Error: Invalid Operand";
}
else if(line[1]=="resb")
{
int numOfByt=Tointeger(line[2]);
if(numOfByt==-1)
{
table[table.size()-1].error="****Error: Invalid Operand";
}
else
CURRENTADRESS+=numOfByt;
}
else
{
int numOfByt=Tointeger(line[2]);
if(numOfByt==-1)
table[table.size()-1].error="****Error: Invalid Operand";
else
CURRENTADRESS+=numOfByt*3;
}
}
}
int Utilities:: checkEqu(string a,string label)
{
if(a.size()==1&&a[0]=='*')
return CURRENTADRESS;
int k=0;
if(a[0]=='#'||a[0]=='@')
k++;
string one="";
string two="";
int sign=-1;
bool flag1=true;
bool flag2=true;
for(int i=k; i<a.size(); i++)
{
if(a[i]=='-'||a[i]=='+')
{
if(a[i]=='+')
sign=1;
else
sign=2;
}
else if(a[i]<'0'||a[i]>'9')
{
if(sign==-1)
{
one+=a[i];
flag1=false;
}
else
{
flag2=false;
two+=a[i];
}
}
else
{
if(sign==-1)
one+=a[i];
else
two+=a[i];
}
}
if(one=="")
return -1;
if(sign!=-1&&two=="")
return -1;
if(flag1&&!flag2)
return -1;
//two integers
if(flag1&&flag2)
{
if(sign==-1)
{
absolute[label]=true;
return Tointeger(one);
}
else
return -1;
}
// two words
else
{
if(sign==-1)
{
if(symbolTable.find(one)!=symbolTable.end())
{
if(absolute.find(one)!=absolute.end())
absolute[label]=true;
return symbolTable[one];
}
else
return -1;
}
else
{
int addrs;
if(symbolTable.find(one)!=symbolTable.end())
addrs=symbolTable[one];
else
return -1;
if(flag2==true)
{
if(absolute.find(one)!=absolute.end())
absolute[label]=true;
if(sign==1)
{
return addrs+Tointeger(two);
}
else
{
return addrs-Tointeger(two);
}
}
else
{
if(absolute.find(one)!=absolute.end()&&absolute.find(two)!=absolute.end())
absolute[label]=true;
int addrs2;
if(symbolTable.find(two)!=symbolTable.end())
addrs2=symbolTable[two];
else
return -1;
if(sign==1)
{
if(absolute.find(one)==absolute.end()&&absolute.find(two)==absolute.end())
return -1;
return addrs+addrs2;
}
else
{
return addrs-addrs2;
}
}
}
}
}
int Utilities::checkOrg(string a)
{
cout<<a;
if(a.size()==1&&a[0]=='*')
{
return CURRENTADRESS;
}
int k=0;
string one="";
string two="";
int sign=-1;
int c=0;
bool flag1=true;
bool flag2=true;
for(int i=0; i<a.size(); i++)
{
if(a[i]>='0'&&a[i]<='9')
{
one+=a[i];
c++;
}
}
if(c==a.size())
return Tointeger(one);
else
{
for(int i=0; i<label.size(); i++)
{
if(a.compare(label[i])==0)
return symbolTable[a];
}
}
}
void Utilities::labtable(string line)
{
string temp="";
if(line!=""&&line[0]=='.')
{
}
else
{
for(int i=0; i<line.length()&&i<8; i++)
{
if(line[i]!=' ')
{
temp+=line[i];
}
}
if(temp!="")
{
if(line[0]!=' ')
{
label.push_back(Tolower(temp));
}
}
}
}
void Utilities::parse_sic(string line )
{
if(line.size()>66)
{
table.push_back( Entry( CURRENTADRESS,"","","","","****Error: Invalid spaces in this line","") ) ;
}
vector<string>res;
vector<string>comments;
string temp="";
bool com=false;
bool check_spaces=false;
bool check_spaces_l=false;
bool check_spaces_opc=false;
bool check_spaces_op=false;
bool comment_field=false;
if(line!=""&&line[0]=='.')
{
}
else
{
for(int i=0; i<line.length()&&i<8; i++)
{
if(line[i]!=' ')
{
temp+=line[i];
}
}
if(temp!="")
{
if(line[0]==' ')
{
check_spaces_l=true;
}
temp="";
}
//................................
for(int i=9; i<line.length()&&i<15; i++)
{
if(line[i]!=' ')
{
temp+=line[i];
}
}
if(temp!="")
{
if(line[8]==' '||line[8]=='+')
{
}
else
{
check_spaces=true;
}
if(line[9]==' ')
{
check_spaces_opc=true;
}
temp="";
}
//................................
for(int i=17; i<line.length()&&i<35; i++)
{
if(line[i]!=' ')
{
temp+=line[i];
}
}
if(temp!="")
{
if(line[15]!=' '||line[16]!=' ')
{
check_spaces=true;
}
if(line[17]==' ')
{
check_spaces_op=true;
}
temp="";
}
//................................
for(int i=35; i<line.length(); i++)
{
if(line[i]!=' ')
{
temp+=line[i];
}
}
if(temp!="")
{
comment_field=true;
temp="";
}
if(check_spaces)
{
table.push_back(Entry(CURRENTADRESS,"","","","","****Error: invalid spaces in this line",""));
}
if(check_spaces_l)
{
table.push_back(Entry(CURRENTADRESS,"","","","","****Error: misplaced label",""));
}
if(check_spaces_op)
{
table.push_back(Entry(CURRENTADRESS,"","","","","****Error: misplaced operand",""));
}
if(check_spaces_opc)
{
table.push_back(Entry(CURRENTADRESS,"","","","","****Error: misplaced opcode",""));
}
}
temp="";
for(int i = 0 ; i < line.size(); i++)
{
if(line[i]!=' ')
temp+=line[i];
else if(temp!="")
{
if(temp[0]=='.'||i>=35)
com=true;
if(!com)
{
temp=Tolower(temp);
res.push_back(temp);
}
else
comments.push_back(temp);
temp="";
}
}
if(temp!="")
{
if(temp[0]=='.'||comment_field)
com=true;
if(!com)
{
temp=Tolower(temp);
res.push_back(temp);
}
else
comments.push_back(temp);
}
if(res.size()>0&&firstEntering)
{
string start="";
if(line.size()>13)
{
for(int i=9; i<14; i++)
{
start+=line[i];
}
start=Tolower(start);
}
if(res.size()==2)
CURRENTADRESS=todecimal(res[1]);
else if(res.size()==3)
{
CURRENTADRESS=todecimal(res[2]);
startlbl=res[0];
}
firstEntering=false;
if(res.size()==2&&res[0].compare("start")==0&&CURRENTADRESS!=-1&&start.compare("start")==0)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"",""));
}
else if(res.size()==3&&res[1].compare("start")==0&&CURRENTADRESS!=-1&&start.compare("start")==0)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,res[0],res[1],res[2],temp,"",""));
}
else
{
temp=Comment(comments);
string lin=Comment(res);
table.push_back(Entry(CURRENTADRESS,lin,"","",temp,"****Error: invalid start of the program",""));
}
}
else if(res.size()==3)
{
int k,check=0;
string p="";
p=res[1];
if(res[1][0]=='+')
{
check=1;
p.erase(std::remove(p.begin(), p.end(),'+'), p.end());
}
k=validateOpcode(p,check);
if(k==2)
{
temp=Comment(comments);
if((res[1][0]>='a'&&res[1][0]<='z')||(res[1][0]>='A'&&res[1][0]<='Z'))
table.push_back(Entry(CURRENTADRESS,res[0],res[1],res[2],temp,"****Error: Unrecognized OpCode",""));
else
table.push_back(Entry(CURRENTADRESS,res[0],res[1],res[2],temp,"****Error: wrong operation prefix",""));
}
else if(k==3)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,res[0],res[1],res[2],temp,"****Error: canít be format 4 instruction",""));
}
else
{
if(!duplicateLable(res[0]))
{
int r=check_operand(res[1],res[2]);
if(r==1)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,res[0],res[1],res[2],temp,"****Error: Invalid Register address",""));
}
else if(r==2)
{
temp=Comment(comments);
cout<<"here";
table.push_back(Entry(CURRENTADRESS,res[0],res[1],res[2],temp,"****Error: Invalid Operand",""));
}
else if(r==3)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,res[0],res[1],res[2],temp,"****Error: Symbol of operand not found",""));
}
else if(k==6)
{
if(res[1]=="org"||res[1]=="base")
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,res[0],res[1],res[2],temp,"****Error: This instruction can't have a label",""));
}
else
threeWord(res,5,comments);
}
else
{
threeWord(res,byte(res[1]),comments);
}
}
else
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,res[0],res[1],res[2],temp,"****Error: Duplicate Symbol",""));
}
}
}
else if(res.size()==2)
{
int k,m,check=0;
string p="",q="";
p=res[0];
q=res[1];
m=validateOpcode(res[1],check);
if(res[1][0]=='+')
{
check=1;
q.erase(std::remove(q.begin(), q.end(),'+'), q.end());
m=validateOpcode(q,check);
}
else
{
m=validateOpcode(res[1],check);
}
if(m==1||m==6)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,res[0],res[1],"",temp,"****Error: missing operand",""));
}
else
{
if(res[0][0]=='+')
{
check=1;
p.erase(std::remove(p.begin(), p.end(),'+'), p.end());
}
k=validateOpcode(p,check);
if(k==2)
{
temp=Comment(comments);
if((res[0][0]>='a'&&res[0][0]<='z')||(res[0][0]>='A'&&res[0][0]<='Z'))
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"****Error: Unrecognized OpCode",""));
else
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"****Error: wrong operation prefix",""));
}
else if(k==3)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"****Error: canít be format 4 instruction",""));
}
else
{
int r=check_operand(res[0],res[1]);
if(r==1)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"****Error: Invalid Register address",""));
}
else if(r==2)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"****Error: Invalid Operand",""));
}
else if(r==3)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"****Error: Symbol of operand not found",""));
}
else if(k==6)
{
if(p=="equ")
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"****Error: This instruction must have a label",""));
}
else
twoWord(res,6,comments);
}
else
{
twoWord(res,byte(res[0]),comments);
}
}
}
}
else if(res.size()==1)
{
int k,check=0;
string p="";
p=res[0];
if(res[0][0]=='+')
{
check=1;
p.erase(std::remove(p.begin(), p.end(),'+'), p.end());
}
k=validateOpcode(p,check);
if(k==2)
{
temp=Comment(comments);
if((res[0][0]>='a'&&res[0][0]<='z')||(res[0][0]>='A'&&res[0][0]<='Z'))
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"****Error: Unrecognized OpCode",""));
else
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"****Error: wrong operation prefix",""));
}
else if(k==3)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,"",res[0],"",temp,"****Error: canít be format 4 instruction",""));
}
else if(k==6)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,"",res[0],"",temp,"****Error: missing operand",""));
}
else
{
oneWord(res,comments,byte(res[0]));
}
}
else if(res.size()>3)
{
table.push_back( Entry( CURRENTADRESS, "",line,"","","****Error: Invalid Entry","") ) ;
}
else if(comments.size()>0)
{
temp=Comment(comments);
if(!firstEntering)
table.push_back( Entry( CURRENTADRESS,"","","",temp,"","") ) ;
else
table.push_back( Entry( -1,"","","",temp,"","") ) ;
}
}
void Utilities::parse(string line )
{
labelch=1;
vector<string>res;
vector<string>comments;
string temp="";
bool com=false;
for(int i = 0 ; i < line.size(); i++)
{
if(line[i]!=' ')
temp+=line[i];
else if(temp!="")
{
if(temp[0]=='.')
com=true;
if(!com)
{
temp=Tolower(temp);
res.push_back(temp);
}
else
comments.push_back(temp);
temp="";
}
}
if(temp!="")
{
if(temp[0]=='.')
com=true;
if(!com)
{
temp=Tolower(temp);
res.push_back(temp);
}
else
comments.push_back(temp);
}
if(res.size()>0&&firstEntering)
{
if(res.size()==2)
CURRENTADRESS=todecimal(res[1]);
else if(res.size()==3)
{
CURRENTADRESS=todecimal(res[2]);
startlbl=res[0];
}
firstEntering=false;
if(res.size()==2&&res[0].compare("start")==0&&CURRENTADRESS!=-1)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"",""));
}
else if(res.size()==3&&res[1].compare("start")==0&&CURRENTADRESS!=-1)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,res[0],res[1],res[2],temp,"",""));
}
else
{
temp=Comment(comments);
string lin=Comment(res);
table.push_back(Entry(CURRENTADRESS,lin,"","",temp,"****Error: invalid start of the program",""));
}
}
else if(res.size()==3)
{
int k,check=0;
string p="";
p=res[1];
if(res[1][0]=='+')
{
check=1;
p.erase(std::remove(p.begin(), p.end(),'+'), p.end());
}
k=validateOpcode(p,check);
if(k==2)
{
temp=Comment(comments);
if((res[1][0]>='a'&&res[1][0]<='z')||(res[1][0]>='A'&&res[1][0]<='Z'))
table.push_back(Entry(CURRENTADRESS,res[0],res[1],res[2],temp,"****Error: Unrecognized OpCode",""));
else
table.push_back(Entry(CURRENTADRESS,res[0],res[1],res[2],temp,"****Error: wrong operation prefix",""));
}
else if(k==3)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,res[0],res[1],res[2],temp,"****Error: canít be format 4 instruction",""));
}
else
{
if(!duplicateLable(res[0]))
{
int r=check_operand(res[1],res[2]);
if(r==1)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,res[0],res[1],res[2],temp,"****Error: Invalid Register address",""));
}
else if(r==2)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,res[0],res[1],res[2],temp,"****Error: Invalid Operand",""));
}
else if(r==3)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,res[0],res[1],res[2],temp,"****Error: Symbol of operand not found",""));
}
else if(k==6)
{
if(res[1]=="org"||res[1]=="base")
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,res[0],res[1],res[2],temp,"****Error: This instruction can't have a label",""));
}
else
threeWord(res,5,comments);
}
else
{
threeWord(res,byte(res[1]),comments);
}
}
else
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,res[0],res[1],res[2],temp,"****Error: Duplicate Symbol",""));
}
}
}
else if(res.size()==2)
{
int k,m,check=0;
string p="",q="";
p=res[0];
q=res[1];
m=validateOpcode(res[1],check);
if(res[1][0]=='+')
{
check=1;
q.erase(std::remove(q.begin(), q.end(),'+'), q.end());
m=validateOpcode(q,check);
}
else
{
m=validateOpcode(res[1],check);
}
if(m==1)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,res[0],res[1],"",temp,"****Error: missing operand",""));
}
else
{
if(res[0][0]=='+')
{
check=1;
p.erase(std::remove(p.begin(), p.end(),'+'), p.end());
}
k=validateOpcode(p,check);
if(k==2)
{
temp=Comment(comments);
if((res[0][0]>='a'&&res[0][0]<='z')||(res[0][0]>='A'&&res[0][0]<='Z'))
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"****Error: Unrecognized OpCode",""));
else
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"****Error: wrong operation prefix",""));
}
else if(k==3)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"****Error: canít be format 4 instruction",""));
}
else
{
int r=check_operand(res[0],res[1]);
if(r==1)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"****Error: Invalid Register address",""));
}
else if(r==2)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"****Error: Invalid Operand",""));
}
else if(k==6)
{
if(p=="equ")
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"****Error: This instruction must have a label",""));
}
else
twoWord(res,6,comments);
}
else
{
twoWord(res,byte(res[0]),comments);
}
}
}
}
else if(res.size()==1)
{
int k,check=0;
string p="";
p=res[0];
if(res[0][0]=='+')
{
check=1;
p.erase(std::remove(p.begin(), p.end(),'+'), p.end());
}
k=validateOpcode(p,check);
if(k==2)
{
temp=Comment(comments);
if((res[0][0]>='a'&&res[0][0]<='z')||(res[0][0]>='A'&&res[0][0]<='Z'))
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"****Error: Unrecognized OpCode",""));
else
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"****Error: wrong operation prefix",""));
}
else if(k==3)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,"",res[0],"",temp,"****Error: canít be format 4 instruction",""));
}
else if(k==6)
{
temp=Comment(comments);
table.push_back(Entry(CURRENTADRESS,"",res[0],"",temp,"****Error: missing operand",""));
}
else
{
oneWord(res,comments,byte(res[0]));
}
}
else if(res.size()>3)
{
table.push_back( Entry( CURRENTADRESS, "",line,"","","****Error: Invalid Entry","" ) ) ;
}
else if(comments.size()>0)
{
temp=Comment(comments);
if(!firstEntering)
table.push_back( Entry( CURRENTADRESS,"","","",temp,"","") ) ;
else
table.push_back( Entry( -1,"","","",temp,"","" ) ) ;
}
}
void Utilities::fillingMap()
{
ifstream infile( "format.txt" );
vector <string> record;
while (infile)
{
string s;
if (!getline( infile, s ))
break;
istringstream ss( s );
while (ss)
{
string s;
if (!getline( ss, s, ',' ))
break;
record.push_back( s );
}
}
infile.close();
for(int i=0; i<record.size(); i++)
{
if(i%5==0)
opc.push_back(record[i]);
else if(i%5==1)
n1.push_back(record[i]);
else if(i%5==2)
n2.push_back(record[i]);
else if(i%5==3)
regmem.push_back(record[i]);
else if(i%5==4)
objc.push_back(record[i]);
}
}
void Utilities::checkEndLine(string line)
{
vector<string>res;
vector<string>comments;
string temp="";
bool com=false;
for(int i = 0 ; i < line.size(); i++)
{
if(line[i]!=' ')
temp+=line[i];
else if(temp!="")
{
if(temp[0]=='.')
com=true;
if(!com)
{
temp=Tolower(temp);
res.push_back(temp);
}
else
comments.push_back(temp);
temp="";
}
}
if(temp!="")
{
if(temp[0]=='.')
com=true;
if(!com)
{
temp=Tolower(temp);
res.push_back(temp);
}
else
comments.push_back(temp);
}
temp=Comment(comments);
if(res.size()==1&&res[0]=="end"||res.size()==2&&res[0]=="end"&&res[1].compare(startlbl)==0)
{
if(res.size()==1)
table.push_back(Entry(CURRENTADRESS,"",res[0],"",temp,"",""));
else
table.push_back(Entry(CURRENTADRESS,"",res[0],res[1],temp,"",""));
}
else
{
if(res[0]!="end"&&res[1]!="end")
{
string lin=Comment(res);
table.push_back(Entry(CURRENTADRESS,lin,"","",temp,"****Error: invalid end of program",""));
}
else if(res[0]!="end")
{
string lin=Comment(res);
table.push_back(Entry(CURRENTADRESS,lin,"","",temp,"****Error: This instruction can't have a label",""));
}
else if(startlbl=="")
{
string lin=Comment(res);
table.push_back(Entry(CURRENTADRESS,lin,"","",temp,"****Error: Start instruction doesn't have a label so this instruction can't have an operand ",""));
}
else
{
string lin=Comment(res);
table.push_back(Entry(CURRENTADRESS,lin,"","",temp,"****Error: The operand must be the label of the start instruction",""));
}
}
}
bool Utilities::checkSpace(string a)
{
for(int i=0; i<a.size(); i++)
if(a[i]!=' ')
return true;
return false;
}
int Utilities::stoi(string s)
{
int i;
i =(s[0] -'0');
return i;
}
string Utilities::binary_to_hexa(string a)
{
int dec=0;
for(int i=0; i<a.size(); i++)
{
dec+=(a[i]-'0')*pow(2,a.size()-i-1);
}
char buffer [33];
itoa(dec,buffer,16);
return buffer;
}
void Utilities::initRegisters()
{
mnemonicNumber["a"]="0";
mnemonicNumber["x"]="1";
mnemonicNumber["l"]="2";
mnemonicNumber["b"]="3";
mnemonicNumber["s"]="4";
mnemonicNumber["t"]="5";
mnemonicNumber["f"]="6";
mnemonicNumber["pc"]="8";
mnemonicNumber["sw"]="9";
}
vector <string>Utilities::splitLine(string line)
{
vector<string>res;
string temp="";
for( int i = 0; i < line.size() ; i++)
{
if(line[i]==',')
{
res.push_back(temp);
temp="";
}
else
temp+=line[i];
}
res.push_back(temp);
return res;
}
int Utilities::eval_address(string a,int index)
{
if(a!=""&&(a.find("+")==-1)&&(a.find("/")==-1)&&(a.find("*")==-1)&&(a.find("-")==-1))
{
if(a.size()==1&&a[0]=='*')
return CURRENTADRESS;
int k=0;
if(a[0]=='#'||a[0]=='@')
k++;
string one="";
string two="";
int sign=-1;
bool flag1=true;
bool flag2=true;
for(int i=k; i<a.size(); i++)
{
if(a[i]=='-'||a[i]=='+')
{
if(a[i]=='+')
sign=1;
else
sign=2;
}
else if(a[i]<'0'||a[i]>'9')
{
if(sign==-1)
{
one+=a[i];
flag1=false;
}
else
{
flag2=false;
two+=a[i];
}
}
else
{
if(sign==-1)
one+=a[i];
else
two+=a[i];
}
}
if((a[0]=='#'||a[0]=='@')&&flag1&&two=="")
{
if(sign==-1)
{
return -2;
}
else
{
table[index].error="****Error: invalid expression";
return -1;
}
}
if(one=="")
{
table[index].error="****Error: invalid expression";
return -1;
}
if(sign!=-1&&two=="")
{
table[index].error="****Error: invalid expression";
return -1;
}
if(flag1&&!flag2)
{
table[index].error="****Error: invalid expression";
return -1;
}
//two integers
if(flag1&&flag2)
{
table[index].error="****Error: invalid expression";
return -1;
}
// two words
else
{
if(sign==-1)
{
if(symbolTable.find(one)!=symbolTable.end())
{
return symbolTable[one];
}
else
{
table[index].error="****Error: undefined symbol";
return -1;
}
}
else
{
if(flag1&&!flag2)
{
table[index].error="****Error: invalid expression";
return -1;
}
else if(!flag1&&flag2)
{
if(symbolTable.find(one)!=symbolTable.end())
{
if(sign==1)
{
return symbolTable[one]+Tointeger(two);
}
else
{
return symbolTable[one]-Tointeger(two);
}
}
else
{
table[index].error="****Error: undefined symbol";
return -1;
}
}
else if(!flag1&&!flag2)
{
if(sign==1&&((symbolTable.find(one)!=symbolTable.end()&&absolute.find(two)!=absolute.end())||
(symbolTable.find(two)!=symbolTable.end()&&absolute.find(one)!=absolute.end())))
{
return symbolTable[one]+symbolTable[two];
}
else if(sign==2&&((symbolTable.find(one)!=symbolTable.end()&&absolute.find(two)!=absolute.end())||
(symbolTable.find(two)!=symbolTable.end()&&absolute.find(one)!=absolute.end())))
{
return -1;
}
else if(sign==2&&((symbolTable.find(one)!=symbolTable.end()&&symbolTable.find(two)!=symbolTable.end())||
(symbolTable.find(two)!=symbolTable.end()&&symbolTable.find(one)!=symbolTable.end())))
{
int add=symbolTable[one]-symbolTable[two];
if(add<0)
{
table[index].error="****Error: negative address";
return -1;
}
else
{
return add;
}
}
else
{
table[index].error="****Error: invalid expression";
return -1;
}
}
}
}
}
else if(a!=""&&((a.find("+")!=-1)||(a.find("/")!=-1)||(a.find("*")!=-1)||(a.find("-")!=-1)))
{
int cot=0;
int c=0;
string opr;
vector<string> str;
vector<int> str2;
if((a.find("+")!=-1)||(a.find("/")!=-1)||(a.find("*")!=-1)||(a.find("-")!=-1))
{
for( int n=0; n<a.size(); n++)
{
if(a[n]=='+'||a[n]=='-'||a[n]=='*'||a[n]=='/')
{
opr+=a[n];
a[n]='.';
c++;
}
}
tokenize(a, '.', str);
int res=0;
for(int j=0; j<opr.size(); j++)
{
if(j==0)
{
if(opr[j]=='+')
{
int cp=0;
for(int k=0; k<str[j+1].size(); k++)
{
if(str[j+1][k]>='0'&&str[j+1][k]<='9')
cp++;
}
if(cp==str[j+1].size())
res=symbolTable[str[j]]+atoi(str[j+1].c_str());
else
res=symbolTable[str[j]]+symbolTable[str[j+1]];
}
else if(opr[j]=='-')
{
int cp=0;
for(int k=0; k<str[j+1].size(); k++)
{
if(str[j+1][k]>='0'&&str[j+1][k]<='9')
cp++;
}
if(cp==str[j+1].size())
res=symbolTable[str[j]]-atoi(str[j+1].c_str());
else
res=symbolTable[str[j]]-symbolTable[str[j+1]];
}
else if(opr[j]=='/')
{
int cp=0;
for(int k=0; k<str[j+1].size(); k++)
{
if(str[j+1][k]>='0'&&str[j+1][k]<='9')
cp++;
}
if(cp==str[j+1].size())
res=symbolTable[str[j]]/atoi(str[j+1].c_str());
else
res=symbolTable[str[j]]/symbolTable[str[j+1]];
}
else if(opr[j]=='*')
{
int cp=0;
for(int k=0; k<str[j+1].size(); k++)
{
if(str[j+1][k]>='0'&&str[j+1][k]<='9')
cp++;
}
if(cp==str[j+1].size())
res=symbolTable[str[j]]*atoi(str[j+1].c_str());
else
res=symbolTable[str[j]]*symbolTable[str[j+1]];
}
}
else
{
if(opr[j]=='+')
{
int cp=0;
for(int k=0; k<str[j+1].size(); k++)
{
if(str[j+1][k]>='0'&&str[j+1][k]<='9')
cp++;
}
if(cp==str[j+1].size())
res=res+atoi(str[j+1].c_str());
else
res=res+symbolTable[str[j+1]];
}
else if(opr[j]=='-')
{
int cp=0;
for(int k=0; k<str[j+1].size(); k++)
{
if(str[j+1][k]>='0'&&str[j+1][k]<='9')
cp++;
}
if(cp==str[j+1].size())
res=res-atoi(str[j+1].c_str());
else
res=res-symbolTable[str[j+1]];
}
else if(opr[j]=='/')
{
int cp=0;
for(int k=0; k<str[j+1].size(); k++)
{
if(str[j+1][k]>='0'&&str[j+1][k]<='9')
cp++;
}
if(cp==str[j+1].size())
res=res/atoi(str[j+1].c_str());
else
res=res/symbolTable[str[j+1]];
}
else if(opr[j]=='*')
{
int cp=0;
for(int k=0; k<str[j+1].size(); k++)
{
if(str[j+1][k]>='0'&&str[j+1][k]<='9')
cp++;
}
if(cp==str[j+1].size())
res=res*atoi(str[j+1].c_str());
else
res=res*symbolTable[str[j+1]];
}
}
}
return res;
}
}
return -1;
}
string Utilities::format1(string line)
{
int found = 0;
int place = -1;
for( int i=0; i<objc.size(); i++)
{
if(line.compare(objc[i])==0)
{
found=1;
place=i;
break;
}
}
return binary_to_hexa( objc[place] );
}
string Utilities::format2(string opCode, string operand )
{
// op_code r1,r2
initRegisters();
string res="";
vector<string>registers = splitLine(operand);
int found = 0;
int place = -1;
for( int i=0; i<objc.size(); i++)
{
if(opCode.compare(opc[i])==0)
{
found=1;
place=i;
break;
}
}
res += binary_to_hexa(objc[place]);
res+=mnemonicNumber[registers[0]];
if(registers.size()>1)
res+=mnemonicNumber[registers[1]];
else
res+="0";
return res;
}
string Utilities::format3_4(int index,string instr,string operand,int current_address)
{
string res="";
string nixbpe="000000";
string temp="";
if(instr[0]=='+')
{
for(int i=1; i<instr.size(); i++)
temp+=instr[i];
instr=temp;
nixbpe[5]='1';
}
if(operand[0]=='#')
{
nixbpe[1]='1';
}
else if(operand[0]=='@')
{
nixbpe[0]='1';
}
else
{
nixbpe[0]='1';
nixbpe[1]='1';
//check ni==00
}
int found1 = 0;
int place1 = -1;
for( int i=0; i<opc.size(); i++)
{
if(instr.compare(opc[i])==0)
{
found1=1;
place1=i;
break;
}
}
string opValue= objc[place1];
temp=opValue;
if(temp.size()==1)
{
string temp2="";
temp2='0';
temp2+=temp[0];
temp=temp2;
}
for(int i=0; i<temp.size(); i++)
res+=temp[i];
if(operand[operand.size()-1]=='x'&&operand[operand.size()-2]==',')
{
nixbpe[2]='1';
temp="";
for(int i=0; i<operand.size()-2; i++)
{
temp+=operand[i];
}
operand=temp;
}
string dis="";
if(nixbpe[5]=='0')
{
int TA=eval_address(operand,index);
if(TA!=-1)
{
int dis=TA-(current_address+3);
if(TA!=-2)
{
if(dis>=-2048&&dis<=2047)
{
nixbpe[4]='1';
}
else if(dis>=0&&dis<=4095)
{
//dis will change here=TA-B
//lsa man3rfsh lw mandash 3la LDB 7n3ml 2eh
dis=TA-base;
nixbpe[3]='1';
}
}
else
{
temp="";
for(int i=1; i<operand.size(); i++)
temp+=operand[i];
dis=Tointeger(temp);
}
char buffer [33];
for(int i=0; i<nixbpe.size(); i++)
{
res+=nixbpe[i];
}
res=binary_to_hexa(res);
temp=itoa (dis,buffer,16);
if(temp.size()>3)
{
string temp2="";
temp2=temp[temp.size()-3];
temp2+=temp[temp.size()-2];
temp2+=temp[temp.size()-1];
temp=temp2;
}
else
{
string temp2="";
for(int i=0; i<(3-temp.size()); i++)
{
temp2+='0';
}
for(int i=0; i<temp.size(); i++)
{
temp2+=temp[i];
}
temp=temp2;
}
for(int i=0; i<temp.size(); i++)
{
res+=temp[i];
}
return res;
}
else
{
//error
if(operand=="")
{
temp="0000";
for(int i=0; i<temp.size(); i++)
{
res+=temp[i];
}
return res;
}
else
{
// table[index].error="invalid expression or symbol";
error2=false;
}
}
}
else
{
for(int i=0; i<nixbpe.size(); i++)
{
res+=nixbpe[i];
}
res=binary_to_hexa(res);
char buffer [33];
//lsa mat3mltsh
int TA=eval_address(operand,index);
if(TA!=-1)
{
if(TA!=-2)
{
temp= itoa (TA,buffer,16);
}
else
{
temp="";
for(int i=1; i<operand.size(); i++)
temp+=operand[i];
TA = atoi(temp.c_str());
}
temp= itoa (TA,buffer,16);
if(temp.size()>5)
{
string temp2="";
temp2=temp[temp.size()-5];
temp2+=temp[temp.size()-4];
temp2+=temp[temp.size()-3];
temp2+=temp[temp.size()-2];
temp2+=temp[temp.size()-1];
temp=temp2;
}
else
{
string temp2="";
for(int i=0; i<(5-temp.size()); i++)
{
temp2+='0';
}
for(int i=0; i<temp.size(); i++)
{
temp2+=temp[i];
}
temp=temp2;
}
for(int i=0; i<temp.size(); i++)
res+=temp[i];
return res;
}
else
{
//error
if(operand=="")
{
temp="000000";
for(int i=0; i<temp.size(); i++)
{
res+=temp[i];
}
return res;
}
else
{
// table[index].error="invalid expression or symbol";
error2=false;
}
}
}
return res;
}
void Utilities::objectCode()
{
for(int i=0; i<table.size(); i++)
{
string q=table[i].op_code;
if(table[i].op_code[0]=='+')
{
q.erase(std::remove(q.begin(),q.end(),'+'),q.end());
}
if(q=="start"||q=="end"||q==""||q=="org"||q=="base")
continue;
if(q=="resw"){
sizeall=sizeall+atoi(table[i].operand.c_str())*3;
cout<<sizeall;
}
if(q=="resb"){
sizeall=sizeall+atoi(table[i].operand.c_str());
}
if(table[i].op_code=="byte")
{
if(table[i].operand[0]=='x')
{
for(int j=2; j<table[i].operand.size()-1; j++)
table[i].ObjectCode+=table[i].operand[j];
}
else
{
for(int j=2; j<table[i].operand.size()-1; j++)
{
int ascii=table[i].operand[j];
char buffer [33];
itoa (ascii,buffer,16);
table[i].ObjectCode+=buffer;
}
}
}
else if(table[i].op_code=="word")
{
int dec=0;
for(int k=0 ; k<table[i].operand.size(); k++)
{
dec=dec*10+(table[i].operand[k]-48);
}
char buffer [33];
itoa (dec,buffer,16);
string b2;
b2=buffer;
while(b2.size()<6)
b2="0"+b2;
table[i].ObjectCode=b2;
}
else
{
int found = 0;
int place = -1;
int j;
for( j=0; j<opc.size(); j++)
{
if(q.compare(opc[j])==0)
{
found=1;
place=j;
break;
}
}
//bydrb hna
int byt=stoi(n1[place]);
string res="";
if(byt==1)
{
res=format1(q);
while(res.size()<2)
res="0"+res;
}
else if(byt==2)
{
res=format2(q,table[i].operand);
while(res.size()<4)
res="0"+res;
}
else if(byt==3||byt==4)
{
res=format3_4(i,table[i].op_code,table[i].operand,table[i].loc);
if(byt==3)
{
while(res.size()<6)
res="0"+res;
}
else
{
while(res.size()<8)
res="0"+res;
}
}
table[i].ObjectCode=res;
string s=table[i].operand;
if(table[i].op_code=="ldb")
{
s.erase(std::remove(s.begin(),s.end(),'#'),s.end());
if(s.compare(baseadd)==0)
{
base=eval_address(table[i].operand,i);
if(base==-1)
{
error2=false;
table[i].error="invalid expression or symbol";
}
}
else
table[i].error="invalid symbol or base directive not found";
}
}
}
}
void Utilities::buildObjectFile()
{
programName="";
for(int i = 0 ; i < table.size() ; i++)
{
if(table[i].op_code=="start")
{
if(table[i].label!="")
{
programName=table[i].label;
}
startAdress=table[i].loc;
}
if(table[i].ObjectCode !="")
{
if(table[i].op_code[0]=='+'&&table[i].operand[0]!='#')
objectFileFormat4.push_back(table[i].loc);
objectFile.push_back(make_pair(table[i].ObjectCode,table[i].loc));
}
}
}
string Utilities::modifyLocation(int loc, int len)
{
string lenght="";
char buffer [33];
itoa (loc,buffer,16);
lenght=buffer;
while(lenght.size()<len)
lenght="0"+lenght;
return lenght;
}
void Utilities::generateObjectFile()
{
FILE * file = fopen( "objectfile.txt", "w" );
string res ="";
string header="H";
int len;
if(programName!="")
{
header+=programName;
}
while(header.size()<7)
header=header+"0";
string lenght=modifyLocation(CURRENTADRESS-startAdress,6);
string start=modifyLocation(startAdress,6);
fprintf(file,"%s%s%s\n",header.c_str(),start.c_str(),lenght.c_str());
int sizeobj=0;
int sizetot=0;
int numberOfFormat4=0,numberOfotherForamt=0;
for(int i =0; i <objectFile.size(); i+=9)
{
numberOfFormat4=numberOfotherForamt=0;
res="T";
res+=modifyLocation(objectFile[i].second,6);
string temp="";
for(int j = i ; j < i+9 && j<objectFile.size() ; j++){
temp+=objectFile[j].first;
sizeobj+=objectFile[j].first.size();
}
sizetot=sizeall+sizeobj/2;
res+=modifyLocation(sizetot,2)+temp;
fprintf(file,"%s\n",res.c_str());
}
for(int i = 0 ; i < objectFileFormat4.size(); i++)
fprintf(file,"M%s05\n",modifyLocation(objectFileFormat4[i]+1,6).c_str());
fprintf(file,"E%s\n",start.c_str());
}
void Utilities:: tokenize(std::string const &str, const char delim,
std::vector<std::string> &out)
{
size_t start;
size_t end = 0;
while ((start = str.find_first_not_of(delim, end)) != std::string::npos)
{
end = str.find(delim, start);
out.push_back(str.substr(start, end - start));
}
}
bool Utilities::is_number(const std::string& s)
{
std::string::const_iterator it = s.begin();
while (it != s.end() && std::isdigit(*it))
++it;
return !s.empty() && it == s.end();
}
Utilities::~Utilities()
{
//dtor
}
<file_sep>/SIC-XE/code/main.cpp
#include <fstream>
#include <string>
#include<iostream>
#include<stdio.h>
#include<vector>
#include<cstring>
#include<algorithm>
#include<set>
#include<map>
#include<queue>
#include<stack>
#include "Utilities.h"
#include<math.h>
#define INF 1000000000
#define MOD 1000000007
#define MAX 100000
using namespace std;
Utilities u;
int main()
{
u.fillingMap();
string inputFile;
int choice;
do
{
cout<<"For fixed assembly choose 0 for free assembly choose 1:"<<endl;
cin>>choice;
}
while(choice!=0&&choice!=1);
cout<<"Please enter the input file"<<endl;
cin>>inputFile;
freopen("output.txt","w",stdout);
ifstream code;
code.open(inputFile.c_str());
string prev="" ;
string next="";
while(getline(code,next))
{
if(u.checkSpace(next))
{
if(prev!="")
u.labtable(next);
prev=next;
}
}
code.close();
code.open(inputFile.c_str());
string prev2="" ;
string next2="";
while(getline(code,next2))
{
if(u.checkSpace(next2))
{
if(prev2!="")
if(choice==0)
u.parse_sic(prev2);
else
u.parse(prev2);
prev2=next2;
}
}
u.checkEndLine(prev2);
u.objectCode();
code.close();
// if(u.error1)
//{
// u.objectCode();
printf("%5s%20s%20s%20s%30s%30s%30s ","LineNo","Address","Label","Op-code","Operand","Comment","ObjectCode");
//printf("%s","ObjectCode");
printf("\n");
for(int i=0; i<u.table.size(); i++)
{
string location="";
char buffer [33];
if(u.table[i].loc!=-1)
{
itoa (u.table[i].loc,buffer,16);
location=buffer;
}
printf("%5d%20s%20s%20s%30s%30s ",i,location.c_str(),u.table[i].label.c_str(),u.table[i].op_code.c_str(),u.table[i].operand.c_str(),u.table[i].comment.c_str());
if(u.table[i].ObjectCode!=""&&u.table[i].error=="")
printf("%20s",u.table[i].ObjectCode.c_str());
printf("\n");
if(u.table[i].error!="")
printf(" %s\n",u.table[i].error.c_str());
}
// }
if(!u.error1)
{
//error of pass1
printf(" *********************pass1 errors********************\n\n");
for(int i=0; i<u.table.size(); i++)
{
if(u.table[i].error!="")
printf("line number : %d ,error: %s\n",i,u.table[i].error.c_str());
}
}
else
{
//error of pass2
printf(" *********************pass2 errors********************\n\n");
for(int i=0; i<u.table.size(); i++)
{
if(u.table[i].error!="")
printf("line number : %d ,error: %s\n",i,u.table[i].error.c_str());
}
}
if(u.error2)
{
//buildObjectFile();
//generateObjectFile();
}
cout<<"\n\n\n\n\n"<<endl;
cout<<" *********************Symbol Table********************"<<endl<<endl;
printf("%20s | %20s\n","Symbol","Address");
printf(" ****************************|*******************************\n");
typedef map<string, int>::const_iterator MapIterator;
for (MapIterator iter = u.symbolTable.begin(); iter !=u.symbolTable.end(); iter++)
{
char buffer [33];
itoa (iter->second,buffer,16);
printf("%20s | %20s\n",iter->first.c_str(),buffer);
}
u.buildObjectFile();
u.generateObjectFile();
return 0;
}
<file_sep>/SIC-XE/code/src/Entry.cpp
#include "Entry.h"
Entry::Entry()
{
//ctor
loc=0;
label=op_code=operand=comment=error=ObjectCode="";
}
Entry::Entry(int x , string a , string b , string c , string d,string e, string o)
{
loc = x;
label=a, op_code=b, operand=c ,comment=d,error=e, ObjectCode =o;
}
Entry::~Entry()
{
//dtor
}
|
a1814a70ad8eb57ffc9b99a0ba2daca9edc90fdb
|
[
"C++"
] | 5
|
C++
|
moniqueshenouda/Systems-Programming
|
f461dc27586b99b86c936b73cd654467a5032169
|
97d47965f59b63a7f8348bc105e1aaa35ccff227
|
refs/heads/master
|
<repo_name>Xuchen1591/Motion-Diary<file_sep>/motion_diary_v2/ChoosePhoto.xaml.cs
using motion_diary_v2.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// “基本页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234237 上有介绍
namespace motion_diary_v2
{
/// <summary>
/// 基本页,提供大多数应用程序通用的特性。
/// </summary>
public sealed partial class ChoosePhoto : Page
{
private NavigationHelper navigationHelper;
private ObservableDictionary defaultViewModel = new ObservableDictionary();
/// <summary>
/// 可将其更改为强类型视图模型。
/// </summary>
public ObservableDictionary DefaultViewModel
{
get { return this.defaultViewModel; }
}
/// <summary>
/// NavigationHelper 在每页上用于协助导航和
/// 进程生命期管理
/// </summary>
public NavigationHelper NavigationHelper
{
get { return this.navigationHelper; }
}
public ChoosePhoto()
{
this.InitializeComponent();
this.navigationHelper = new NavigationHelper(this);
this.navigationHelper.LoadState += navigationHelper_LoadState;
this.navigationHelper.SaveState += navigationHelper_SaveState;
}
/// <summary>
///使用在导航过程中传递的内容填充页。 在从以前的会话
/// 重新创建页时,也会提供任何已保存状态。
/// </summary>
/// <param name="sender">
/// 事件的来源; 通常为 <see cref="NavigationHelper"/>
/// </param>
/// <param name="e">事件数据,其中既提供在最初请求此页时传递给
/// <see cref="Frame.Navigate(Type, Object)"/> 的导航参数,又提供
/// 此页在以前会话期间保留的状态的
/// 的字典。 首次访问页面时,该状态将为 null。</param>
private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
}
/// <summary>
/// 保留与此页关联的状态,以防挂起应用程序或
/// 从导航缓存中放弃此页。 值必须符合
/// <see cref="SuspensionManager.SessionState"/> 的序列化要求。
/// </summary>
///<param name="sender">事件的来源;通常为 <see cref="NavigationHelper"/></param>
///<param name="e">提供要使用可序列化状态填充的空字典
///的事件数据。</param>
private void navigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
}
#region NavigationHelper 注册
/// 此部分中提供的方法只是用于使
/// NavigationHelper 可响应页面的导航方法。
///
/// 应将页面特有的逻辑放入用于
/// <see cref="GridCS.Common.NavigationHelper.LoadState"/>
/// 和 <see cref="GridCS.Common.NavigationHelper.SaveState"/> 的事件处理程序中。
/// 除了在会话期间保留的页面状态之外
/// LoadState 方法中还提供导航参数。
protected override void OnNavigatedTo(NavigationEventArgs e)
{
navigationHelper.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
navigationHelper.OnNavigatedFrom(e);
}
#endregion
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
Windows.Storage.Pickers.FileOpenPicker openPicker =
new Windows.Storage.Pickers.FileOpenPicker();
openPicker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
openPicker.FileTypeFilter.Clear();
openPicker.FileTypeFilter.Add(".bmp");
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
openPicker.FileTypeFilter.Add(".gif");
Windows.Storage.StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
Windows.Storage.Streams.IRandomAccessStream stram
= await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
Windows.UI.Xaml.Media.Imaging.BitmapImage img =
new Windows.UI.Xaml.Media.Imaging.BitmapImage();
img.SetSource(stram);
userPhoto.Source = img;
}
}
private void Button_Click_3(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(typeof(NotePage));
}
}
}
<file_sep>/README.md
# Motion-Diary
windows 8 store app
## Course
>* Software Engneering school of Tongji University
>* Windows programming
>* Prof: Fan
## Functions
* Dialy motion
* Dialy note
* Scores everyday
* Motion history
## Environment
OS: Windows 8/8.1
|
ed5797de75cb3c4c754f1cb82be8c65369b9c69e
|
[
"Markdown",
"C#"
] | 2
|
C#
|
Xuchen1591/Motion-Diary
|
b569f511b1106ab78469d725bb782b5f07b552e5
|
2b5bb1d7d143e0d0e4d6a3903522eeeb1fc46449
|
refs/heads/master
|
<repo_name>MarianaSouza/DeterminePrimeNumberInC<file_sep>/README.md
# DeterminePrimeNumberInC
This program determines whether a number is prime or not in C.
<file_sep>/DeterminePrimeNumberC/DeterminePrimeNumberC/main.c
#include <stdio.h>
#include <math.h>
int main()
{
double Number;
double Div;
Number = 0;
printf("This program identifies whether a number is prime.\n");
printf("Please give me a number: ");
scanf_s("%lf", &Number); //lf means large float and it is being used because Number is Double
if (Number == 1.0)
{
printf("This number is not prime.\n");
return 0;
}
if (Number == 2.0)
{
printf("This number is prime.\n");
return 0;
}
if (Number < 2)
{
printf("Please give me a larger number than 2.\n");
return 0;
}
Div = 2;
while (Div <= sqrt(Number))
{
if (fmod(Number, Div) == 0)
{
printf("This number is NOT prime.\n");
return 0;
}
Div++;
}
printf("This number is prime.\n");
return 0;
}
|
02658a8cb153c4cde9d0d471fcb6f9b2bf7f61a7
|
[
"Markdown",
"C"
] | 2
|
Markdown
|
MarianaSouza/DeterminePrimeNumberInC
|
58b6d8e9f7946ee65cdfadf5e750acb60753e8fa
|
5af03b31025306f692c797120e48f1c1a39ff83f
|
refs/heads/master
|
<repo_name>krajmohan/ferrari-formengine<file_sep>/public_api.d.ts
export * from './app/modules/header/header.module';
|
806855ce911b127b49dfa5be43a7914e70a38a92
|
[
"TypeScript"
] | 1
|
TypeScript
|
krajmohan/ferrari-formengine
|
69fe075ed618e05f352064265e55d7ff9edf292a
|
c889b2bf16a97c42066088b03eaec3239c4213e1
|
refs/heads/master
|
<repo_name>ProgrammingPete/cle-coin<file_sep>/migrations/2_deploy_contracts.js
var ClevelandCoin = artifacts.require("./ClevelandCoin.sol");
module.exports = function(deployer) {
deployer.deploy(ClevelandCoin);
};
<file_sep>/README.md
# Cleveland Coin
ClevelandCoin (`CLE`) is a new Ethereum ERC20 formed in Cleveland, OH, at the
[Crypto Cleveland Meetup](https://www.meetup.com/Crypto-Cleveland/).
It has been developed as a resource to learn how to create Ethereum contracts,
and the goal is to continue researching and adding features until the community
is comfortable releasing the token on the main Ethereum blockchain, by doing an
ICO.
## Getting Started
These instructions will get you a copy of the project up and running on your
local machine for development and testing purposes.
### Prerequisites
What things you need to install the software and how to install them
* NodeJS / NPM:
* https://nodejs.org/en/download/package-manager/
* Yarn
* https://yarnpkg.com/en/docs/install
* ethereumjs-testrpc
* https://github.com/ethereumjs/testrpc
* Truffle:
* http://truffleframework.com/
* MetaMask
* https://metamask.io/
### Installing
After cloning this repository and installing the above dependencies, perform
```
$ yarn install
```
to get the `zeppelin-solidity` boilerplate project files installed. In a new
terminal window, start
```
$ testrpc
```
which starts a new local ethereum blockchain running on `localhost:8545`. You'll
see some output like the following:
```
EthereumJS TestRPC v4.1.3 (ganache-core: 1.1.3)
Available Accounts
==================
(0) 0x2a500247d0a0770e0c71d435f4b84d15fe19d7d3
(1) 0x4199984a9385cdda8440c578f07eb5ee0f29a053
...
Private Keys
==================
(0) 3cbd4919c7b143d50b1edbe29110e4ae176a783c81f5b69c6dbb4f939a73b1e0
(1) b10f6b42990de4c3bfb4dc5cdafa63199c0a1d3aac7703298514cf32757f7e57
...
HD Wallet
==================
Mnemonic: predict abandon immune breeze movie divide seminar frost tragic
grunt lonely monitor
Base HD Path: m/44'/60'/0'/0/{account_index}
Listening on localhost:8545
```
Take note of the `Mnemonic` seed, you'll need it when you setup MetaMask.
Next, perform
```
$ truffle compile
$ truffle migrate
```
which will deploy the contract onto your local ethereum blockchain.
You should see some output like the following:
```
Running migration: 1_initial_migration.js
Deploying Migrations...
... 0xc5e7ab7a26714c17cacd2c7f1e40a80f1af61f99aeaea37e6375ea9f9a763bc5
Migrations: 0xa7bed269f540f687e2ce16a028be1d97f710cee0
Saving successful migration to network...
... 0xa66a64cd76d4c454ab97f7da754737cf87c280534c13e9a72ec4725ad33d6246
Saving artifacts...
Running migration: 2_deploy_contracts.js
Deploying ClevelandCoin...
... 0x0502076951d556e9e697b3807ea82099d65af7f2df2470b96ee89727aa88eb6c
ClevelandCoin: 0xe727f76b086e0881809a8d834a6d7947aafbf344
Saving successful migration to network...
... 0xf65cafc6f8cdc4ca736d80265152543ca989f1a525d3ea5bc696cfa70458d542
Saving artifacts...
```
Take note of the line `ClevelandCoin: 0xe727f76b086e0881809a8d834a6d7947aafbf344`
This is the address that the `ClevelandCoin` contract was deployed to.
Open Chrome, navigate to `https://wallet.ethereum.org`. Open the MetaMask
extension and "Restore from Seed Phrase", using the Mnemonic seed from above.
Also, make sure that MetaMask is pointing at `localhost:8545`, which can be
configured from the dropdown in the top-left corner of MetaMask's window.
In the ethereum wallet browser in Chrome, navigate to the "Contracts" tab, scroll
to the bottom, and click "Watch Token". Copy the contract address that
`truffle migrate` gave you (`0xe727f76b086e0881809a8d834a6d7947aafbf344` in this
example), and click "OK".
If all went well, you should see the `ClevelandCoin` token with a balance of
216,000,000 CLE!
Use MetaMask to create new accounts (which will match the accounts that `testrpc`
displayed to you upon startup - thank the Mnemonic seed phrase for that), switch
between them, and send tokens back and forth using the Ethereum Web Wallet.
## Running the tests
From the project directory
```
$ truffle test
```
## Contributing
Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of
conduct, and the process for submitting pull requests to us.
## Versioning
We use [SemVer](semver.org) for versioning. For the versions available, see the
tags on this repository.
## Authors
* <NAME> - _Initial work_
See also the list of contributors who participated in this project.
## License
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md)
file for details
## Acknowledgments
* [Crypto Cleveland](https://www.meetup.com/Crypto-Cleveland/)
|
4241e5e61f32f5bf2cc58d37e03d57d7aa9640fc
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
ProgrammingPete/cle-coin
|
604d55f00d182f2f878543666b769899db8faf4c
|
f5213d2caf6402ba11103857adfee49695e85b5e
|
refs/heads/master
|
<file_sep>package code.challenge;
import org.junit.Test;
import java.util.GregorianCalendar;
import static org.junit.Assert.assertEquals;
/**
* Created by bemorgan on 1/21/15.
*/
public class BillCalculatorTest {
@Test
public void testNonProrated() {
//suppose a $30/month service is purchased in January, 2015
//a bill in July, 2015 should be for the whole baseFee
GregorianCalendar purchaseDate = BillCalculator.parseDate("2015-01-12 13:14:15");
int billDay = 31;
int billMonth = 7;
int billYear = 2015;
long baseFee = 3000;
assertEquals(baseFee, BillCalculator.calculateBill(baseFee, billYear, billMonth, billDay, purchaseDate));
}
@Test
public void testFuturePurchase() {
//suppose the service is scheduled to start in July 2015,
//then there should be no fee on a January 2015 bill.
GregorianCalendar purchaseDate = BillCalculator.parseDate("2015-07-08 13:14:15");
int billDay = 31;
int billMonth = 1;
int billYear = 2015;
long baseFee = 3000;
assertEquals(0, BillCalculator.calculateBill(baseFee, billYear, billMonth, billDay, purchaseDate));
}
@Test
public void testSimpleProrated() {
//suppose a $30/month service is purchased in on June 25th, 2015
//with a billing cycle that ends on the 20th. The fee should be
//a prorated amount for 25 days of service (June 25th - 30th and
//July 1st - 19th) and should be $25
GregorianCalendar purchaseDate = BillCalculator.parseDate("2015-06-25 13:14:15");
int billDay = 20;
int billMonth = 7;
int billYear = 2015;
long baseFee = 3000;
assertEquals(2500, BillCalculator.calculateBill(baseFee, billYear, billMonth, billDay, purchaseDate));
}
@Test
public void testPurchaseOnBillDate() {
//suppose a $12.34/month service is purchased on January 21st, 2015
//with a billing cycle that ends on the 21st of February. The bill should
//be the entire base fee of $12.34 since they have had the service for the
//entire billing cycle.
GregorianCalendar purchaseDate = BillCalculator.parseDate("2015-01-21 13:14:15");
int billDay = 21;
int billMonth = 2;
int billYear = 2015;
long baseFee = 1234;
assertEquals(baseFee, BillCalculator.calculateBill(baseFee, billYear, billMonth, billDay, purchaseDate));
}
@Test
public void testShortMonthProrated() {
//suppose a $25/month service is purchased on January 31st, 2015
//and that the customer has chosen to be billed on the 30th. Since
//February has 28 days in 2015, the customer will instead be billed
//on the 28th. Their bill should then reflect 28 days of service
//(Jan 31st and Feb 1st - 27th)
//The prorated amount should then be round((25/30)*28) = $23.33
GregorianCalendar purchaseDate = BillCalculator.parseDate("2015-01-31 13:14:15");
int billDay = 30;
int billMonth = 2;
int billYear = 2015;
long baseFee = 2500;
assertEquals(2333, BillCalculator.calculateBill(baseFee, billYear, billMonth, billDay, purchaseDate));
}
@Test
public void testFebruaryLeapYearProrated() {
//suppose a $19/month service is purchased on January 31st, 2016
//and that the customer has chosen to be billed on the 30th. Since
//2016 is a leap year, they will be billed on the 29th of February
//instead. Their bill should reflect 29 days of service (Jan 31st
//and Feb 6th - 28th)
//The prorated amount should be round((19/30)*29) = $18.37
GregorianCalendar purchaseDate = BillCalculator.parseDate("2016-01-31 13:14:15");
int billDay = 30;
int billMonth = 2;
int billYear = 2016;
long baseFee = 1900;
assertEquals(1837, BillCalculator.calculateBill(baseFee, billYear, billMonth, billDay, purchaseDate));
}
@Test
public void testNonProratedNewYear() {
//suppose a $40/month service is purchased in July 2015
//and that the customer has chosen to be billed on the 15th.
//a bill for January 2016 should be the full baseFee
//This bill cycle spans from 2015 to 2016
GregorianCalendar purchaseDate = BillCalculator.parseDate("2015-07-06 13:14:15");
int billDay = 15;
int billMonth = 1;
int billYear = 2016;
long baseFee = 4000;
assertEquals(baseFee, BillCalculator.calculateBill(baseFee, billYear, billMonth, billDay, purchaseDate));
}
@Test
public void testProratedNewYear() {
//suppose a $19.99/month service is purchased December 20th, 2015
//and that the customer has chosen to be billed on the 15th.
//A bill for January 2016 should reflect 26 days of service
//(Dec 20th - Dec 31st and Jan 1st - Jan 14)
//The prorated amount should be round((19.99/30)*26) = 17.32
GregorianCalendar purchaseDate = BillCalculator.parseDate("2015-12-20 13:14:15");
int billDay = 15;
int billMonth = 1;
int billYear = 2016;
long baseFee = 1999;
assertEquals(1732, BillCalculator.calculateBill(baseFee, billYear, billMonth, billDay, purchaseDate));
}
@Test(expected = IllegalArgumentException.class)
public void testNonsenseBaseFee() {
//check that an exception is thrown when a negative baseFee is provided
GregorianCalendar purchaseDate = BillCalculator.parseDate("2015-01-03 13:14:15");
int billDay = 21;
int billMonth = 1;
int billYear = 2015;
long baseFee = -2000;
BillCalculator.calculateBill(baseFee, billYear, billMonth, billDay, purchaseDate);
}
@Test(expected = IllegalArgumentException.class)
public void testNonsenseBillYear() {
//check that an exception is thrown when a negative billYear is provided
GregorianCalendar purchaseDate = BillCalculator.parseDate("2015-01-03 13:14:15");
int billDay = 21;
int billMonth = 1;
int billYear = -10;
long baseFee = 2000;
BillCalculator.calculateBill(baseFee, billYear, billMonth, billDay, purchaseDate);
}
@Test(expected = IllegalArgumentException.class)
public void testNonsenseBillMonth() {
//check that an exception is thrown when a nonsense billMonth is provided
GregorianCalendar purchaseDate = BillCalculator.parseDate("2015-01-03 13:14:15");
int billDay = 21;
int billMonth = 13;
int billYear = 2015;
long baseFee = 2000;
BillCalculator.calculateBill(baseFee, billYear, billMonth, billDay, purchaseDate);
}
@Test(expected = IllegalArgumentException.class)
public void testNonsenseBillDay() {
//check that an exception is thrown when a nonsense billDay is provided
GregorianCalendar purchaseDate = BillCalculator.parseDate("2015-01-03 13:14:15");
int billDay = 32;
int billMonth = 1;
int billYear = 2015;
long baseFee = 2000;
BillCalculator.calculateBill(baseFee, billYear, billMonth, billDay, purchaseDate);
}
@Test(expected = IllegalArgumentException.class)
public void testNullPurchaseDate() {
//check that an exception is thrown when a null purchaseDate is provided
GregorianCalendar purchaseDate = null;
int billDay = 21;
int billMonth = 1;
int billYear = 2015;
long baseFee = 2000;
BillCalculator.calculateBill(baseFee, billYear, billMonth, billDay, purchaseDate);
}
}
<file_sep>This is <NAME>'s submission for a code challenge. The original question is below:
```
A company sells services with recurring monthly charges.
Customers are charged in advance for each month's service.
Each customer has a set day of the month when their recurring charges are due. This can be any number from 1 to 31.
A bill cycle is from billing day to billing day minus 1
If an customer's billing day falls on a date that does not exist in a month, then the account is billed on the last day of the month.
If a customer purchases new service, a pro-rated amount is charged for the remaining days in the current bill cycle, including the day on which the service was purchased.
Proration is done by day (not by minute, second, week, etc).
The result must be rounded to the nearest penny.
Code a solution to calculate a pro-rated fee given the following parameters:
Base fee
Bill cycle day
Date of purchase
Include JUnits that verify correct proration is calculated in all cases.
```
My code takes into account these cases:
* The service was purchased during this billing cycle. In this case a prorated amount is returned. If the billing day does not exist in the month, the last day of the month is used. Leap year is also considered when calculating bills for February. The prorated amount is rounded to the nearest cent.
* The service was purchased before this billing cycle. In this case the entire base fee is returned
* The service is scheduled to begin after the current billing cycle. In this case we just return 0.
I made one assumption for the calculation of proration: My formula is (Number of Service Days) * (Base Fee) / 30
Using this formula, a day's service will cost the same in February and in March.
Alternatively, a different daily fee could be charged depending on the month. In this case, a day's service in February would be more expensive than a day's service in March. My solution would require modification to calculate proration this way.
|
96744c7dd24a4acd24b118e49facfe6e0bd542c8
|
[
"Markdown",
"Java"
] | 2
|
Java
|
benjamin-edward-morgan/BillCalculator
|
6107bfe3a741a12d09f125e3ebf79643ede4756c
|
335244167ad20e9ffa86f408682ea8c083a793ab
|
refs/heads/master
|
<file_sep>FactoryBot.define do
factory :repository do
sequence(:name) { |n| "example/repo#{n}" }
sequence(:url) { |n| "<EMAIL>:example/repo#{n}.git" }
end
end
<file_sep>require 'rails_helper'
RSpec.describe BuildVersionImage do
let(:instance) { described_class.new }
let(:version) { FactoryBot.create :version_new }
let(:image_double) do
instance_double(
'Docker::Image',
tag: nil,
push: nil
)
end
before do
allow(Docker::Image).to receive(:build).and_return(image_double)
end
describe '#perform' do
before do
instance.perform(version)
end
it 'uses the correct base image' do
expect(Docker::Image).to have_received(:build).with(a_string_including('FROM 127.0.0.1:5000/rubyup/worker:base'))
end
it 'installs the desired ruby version in the image' do
expect(Docker::Image).to have_received(:build).with(a_string_including('rvm install 2.6.3'))
end
it 'tags the image with the correct name' do
expect(image_double).to have_received(:tag).with(
'repo' => '127.0.0.1:5000/rubyup/worker',
'tag' => 'ruby-2.6.3',
force: true
)
end
it 'pushes the image' do
expect(image_double).to have_received(:push)
end
it 'sets the version state to available' do
expect(version.reload.state).to eq 'available'
end
end
end
<file_sep>class IdentitiesController < ApplicationController
def index
@identities = Identity.all
end
def show
@identity = Identity.find params[:id]
end
def new
@identity = Identity.new
end
def create
@identity = Identity.new(identity_params)
if @identity.save
redirect_to identities_path
else
render :new
end
end
def destroy
Identity.find(params[:id]).delete
redirect_to identities_path
end
private
def identity_params
params.require(:identity).permit(:name, :email, :github_api_key)
end
end
<file_sep>module Jobs
class Retry
InvalidStateError = Class.new(RuntimeError)
def initialize(job:)
self.job = job
end
def call
job.reload
raise InvalidStateError, "Can not retry job with state #{job.state}" unless job.state == 'failed'
job.update! state: 'rescheduled'
UpdateJob.perform_later(job)
end
private
attr_accessor :job
end
end
<file_sep>class Job < ApplicationRecord
belongs_to :repository
belongs_to :identity
belongs_to :version_from, class_name: 'Version'
belongs_to :version_to, class_name: 'Version'
serialize :logs, Array
validates :repository, presence: true
validates :name, presence: true
validates :config, presence: true
validates :state, inclusion: { in: %w(created rescheduled completed failed) }
after_initialize :set_defaults
scope :newest_first, -> { order(id: :desc) }
private
def set_defaults
self.name ||= Template.name
self.config ||= Template.config
self.version_from ||= Version.for_select.second_to_last
self.version_to ||= Version.for_select.last
self.identity ||= Identity.first
self.state ||= 'created'
end
end
<file_sep>class Identity < ApplicationRecord
validates :name, presence: true
validates :email, presence: true, uniqueness: true
validates :github_api_key, presence: true
has_many :jobs
def to_s
"#{name} <#{email}> (##{id})"
end
end
<file_sep>class UpdateJob < ApplicationJob
queue_as :default
def perform(job)
self.job = job
self.log = []
log_message "[#{__method__}]"
docker_create_container
docker_exec_commands
docker_remove_container
github_create_pull_request
complete_job(state: 'completed')
rescue => e
log_message "Error: #{e}\n#{e.backtrace.join($INPUT_RECORD_SEPARATOR)}"
complete_job(state: 'failed')
end
private
attr_accessor :job, :container, :log
def complete_job(state:)
job.state = state
job.logs << log.join($INPUT_RECORD_SEPARATOR)
job.save!
end
def log_message(string)
msg = "[+] #{self.class.name} | #{provider_job_id} | #{string}"
log << msg
puts msg unless Rails.env.test?
end
def docker_create_container
log_message "[#{__method__}]"
self.container = Docker::Container.create(
'Image' => job.version_to.docker_image,
'Cmd' => ['/bin/sh', '-c', 'while true; do sleep 30; done;'],
'WorkingDir' => '/home/rubyup'
)
container.start
end
def docker_exec_commands
script = <<~SCRIPT
#!/bin/bash
set -e
set +x
git clone -b #{job.repository.branch} #{clone_url} workdir
cd workdir
git checkout -b #{working_branch}
grep -q #{job.version_to} .ruby-version && exit 1
sed -i.bak "s/#{job.version_from}/#{job.version_to}/" .ruby-version || true
sed -i.bak "s/#{job.version_from}/#{job.version_to}/" .travis.yml || true
sed -i.bak "s/#{job.version_from}/#{job.version_to}/" Gemfile || true
sed -i.bak "s/#{job.version_from}/#{job.version_to}/" Dockerfile || true
rm *.bak || true; rm .*.bak || true
cd ..
cd workdir
test -f Gemfile.lock && gem install bundler -v $(grep -A1 'BUNDLED WITH' Gemfile.lock | tail -n1 | tr -d '[:space:]')
bundle update nokogiri || true
bundle install
git config --global user.email "#{job.identity.email}"
git config --global user.name "#{job.identity.name}"
git commit -am "#{job.config['message']}"
git push origin #{working_branch}
SCRIPT
container.store_file '/home/rubyup/script.sh', script
docker_exec_command 'sudo chown rubyup.rubyup /home/rubyup/script.sh; chmod +x /home/rubyup/script.sh'
docker_exec_command '/home/rubyup/script.sh'
end
def docker_exec_command(command, options = {})
log_message "[#{__method__}] - #{command}"
stdout, stderr, status = container.exec(['bash', '-l', '-c', command], options)
log_message "STATUS: #{status}"
log_message "STDOUT: #{stdout.join}"
log_message "STDERR: #{stderr.join}"
raise RuntimeError if status != 0
end
def docker_remove_container
log_message "[#{__method__}]"
container.delete(force: true)
end
def github_create_pull_request
client = Octokit::Client.new(access_token: job.identity.github_api_key)
client.api_endpoint = "https://#{job.repository.server}/api/v3/" if job.repository.server != 'github.com'
client.create_pull_request job.repository.path, job.repository.branch, working_branch, job.config['message'], job.config['details']
end
def clone_url
"https://#{job.identity.github_api_key}:x-oauth-basic@#{job.repository.server}/#{job.repository.path}"
end
def working_branch
"rubyup/update/ruby-#{job.version_to}"
end
end
<file_sep>class Template
def self.name
"Update Ruby to #{ruby_version}"
end
def self.config
{
message: name,
details: ":link: #{ruby_link}"
}
end
private
def self.ruby_version
return 'x.y.z' if (version = Version.for_select.last).nil?
version.string
end
def self.ruby_link
return 'https://www.ruby-lang.org/' if (version = Version.for_select.last).nil?
version.link
end
end
<file_sep>class RepositoriesController < ApplicationController
def index
@repositories = Repository.all
end
def show
@repository = Repository.find params[:id]
@jobs = @repository.jobs.newest_first
end
def new
@repository = Repository.new
end
def create
@repository = Repository.new(repo_params)
if @repository.save
redirect_to repositories_path
else
render :new
end
end
def edit
@repository = Repository.find params[:id]
end
def update
@repository = Repository.find params[:id]
if @repository.update(repo_params)
redirect_to repositories_path
else
render :edit
end
end
def destroy
Repository.find(params[:id]).destroy
redirect_to repositories_path
end
private
def repo_params
params.require(:repository).permit(:name, :url, :branch)
end
end
<file_sep>class RemovePrivateKeyFromIdentities < ActiveRecord::Migration[5.2]
def change
remove_column :identities, :private_key
end
end
<file_sep>class CreateJobs < ActiveRecord::Migration[5.2]
def change
create_table :jobs do |t|
t.references :repository, null: false
t.references :identity, null: false
t.string :name, null: false
t.json :config, null: false
t.string :state, null: false
t.text :logs, null: true
t.timestamps
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe Jobs::Retry do
let(:job) { FactoryBot.create :job, state: state }
let(:instance) { described_class.new(job: job) }
describe '#call' do
before do
ActiveJob::Base.queue_adapter = :test
end
context 'with a already retried job' do
let(:state) { 'rescheduled' }
it 'raises an error' do
expect { instance.call }.to raise_error Jobs::Retry::InvalidStateError
end
end
context 'with a faild job' do
let(:state) { 'failed' }
it 'resets the state attribute' do
instance.call
expect(job.reload.state).to eq 'rescheduled'
end
it 'schedules a background execution for the job' do
expect { instance.call }.to have_enqueued_job(UpdateJob).with(job)
end
end
end
end
<file_sep>class AddVersionsToJobs < ActiveRecord::Migration[5.2]
def change
change_table :jobs do |t|
t.references :version_from, null: false
t.references :version_to, null: false
end
end
end
<file_sep>FactoryBot.define do
factory :version do
string { '2.6.3' }
link { 'https://www.ruby-lang.org/en/news/2019/04/17/ruby-2-6-3-released/' }
state { 'available' }
end
factory :version_old, parent: :version do
string { '2.6.2' }
link { 'https://www.ruby-lang.org/en/news/2019/03/13/ruby-2-6-2-released/' }
end
factory :version_new, parent: :version do
string { '2.6.3' }
link { 'https://www.ruby-lang.org/en/news/2019/04/17/ruby-2-6-3-released/' }
end
end
<file_sep>class AddBranchToRepository < ActiveRecord::Migration[6.0]
def change
add_column :repositories, :branch, :string, null: false, default: 'master'
end
end
<file_sep>document.addEventListener('turbolinks:load', function() {
var master_cbs = document.querySelectorAll("[data-behaviour=toggle-all]");
master_cbs.forEach(function(master_cb, i) {
var target_name = master_cb.dataset.target;
master_cb.addEventListener('click', function(e) {
var slave_cbs = document.querySelectorAll('input[name="' + target_name + '"]');
slave_cbs.forEach(function(slave_cb, i) {
slave_cb.checked = e.target.checked;
slave_cb.addEventListener('click', function(e) {
master_cb.checked = false;
});
});
});
});
});
<file_sep>require 'rails_helper'
RSpec.describe Jobs::Create do
let(:identity) { FactoryBot.create :identity}
let(:version_from) { FactoryBot.create :version_old }
let(:version_to) { FactoryBot.create :version_new }
let(:blueprint) do
FactoryBot.build(:job,
repository: nil,
identity: identity,
version_from: version_from,
version_to: version_to
)
end
let(:repo1) { FactoryBot.create :repository }
let(:repo2) { FactoryBot.create :repository }
let(:instance) { described_class.new(blueprint: blueprint, repositories: [repo1.id, repo2.id])}
describe '#call' do
before do
ActiveJob::Base.queue_adapter = :test
end
it 'creates one job per repository based on the given blueprint job' do
expect { instance.call }.to change(Job, :count).by(2)
job = Job.first
expect(job.repository).to eq repo1
expect(job.identity).to eq identity
job = Job.second
expect(job.repository).to eq repo2
expect(job.identity).to eq identity
end
it 'schedules a background execution for each created job' do
expect { instance.call }.to have_enqueued_job(UpdateJob).twice
end
end
end
<file_sep>class JobsController < ApplicationController
helper_method :repositories
def index
@jobs = Job.includes(:repository).newest_first
end
def show
@job = Job.find params[:id]
end
def new
@job = Job.new
end
def create
@job = Job.new(create_job_params)
@job.repository_id = repositories.first
if @job.valid?
Jobs::Create.new(blueprint: @job, repositories: repositories).call
redirect_to jobs_path
else
render :new
end
end
def retry
job = Job.find params[:id]
Jobs::Retry.new(job: job).call
redirect_to job
end
private
def create_job_params
params.require(:job).permit(:name, :identity_id, :version_from_id, :version_to_id, :config).to_h.tap do |hash|
hash[:config] = YAML.load(hash[:config])
end
end
def repositories
ids = params[:repositories]
ids = ids.split(',') if ids.is_a? String
ids || []
end
end
<file_sep>#!/bin/sh
set -e
case $1 in
migrations)
exec rails db:migrate
;;
web)
exec puma -C config/puma.rb
;;
worker)
exec sidekiq
;;
esac
<file_sep>class BuildVersionImage < ApplicationJob
queue_as :default
def perform(version)
self.version = version
Docker.options[:read_timeout] = 15.minutes
docker_build_image
docker_tag_image
docker_push_image
version.update!(state: 'available')
rescue => e
log_message "Error: #{e}\n#{e.backtrace.join($INPUT_RECORD_SEPARATOR)}"
version.update!(state: 'failed')
end
private
attr_accessor :version, :image
def docker_build_image
log_message "[#{__method__}]"
self.image = Docker::Image.build(dockerfile)
end
def docker_tag_image
log_message "[#{__method__}]"
image.tag(
'repo' => version.docker_repo,
'tag' => version.docker_tag,
force: true
)
end
def docker_push_image
log_message "[#{__method__}]"
image.push
end
def dockerfile
<<~BUILD
FROM #{Version.docker_baseimage}
RUN bash -l -c "rvm install #{version.string}"
BUILD
end
def log_message(string)
msg = "[+] #{self.class.name} | #{provider_job_id} | #{string}"
puts msg unless Rails.env.test?
end
end
<file_sep>require 'sidekiq/web'
Rails.application.routes.draw do
root to: redirect('/repositories')
devise_for :users
resources :repositories, only: [:index, :show, :new, :create, :edit, :update, :destroy]
resources :jobs, only: [:index, :show, :new, :create] do
put :retry, on: :member
end
resources :versions, only: [:index, :new, :create]
resources :identities, only: [:index, :show, :new, :create, :destroy]
authenticate :user do
mount Sidekiq::Web => '/sidekiq'
end
end
<file_sep># This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
user = User.find_or_initialize_by(email: '<EMAIL>')
user.password = '<PASSWORD>'
user.password_confirmation = user.password
user.save!
version_261 = Version.find_or_create_by!(
string: '2.6.1',
state: 'failed',
link: 'https://www.ruby-lang.org/en/news/2019/01/30/ruby-2-6-1-released/'
)
version_262 = Version.find_or_create_by!(
string: '2.6.2',
state: 'available',
link: 'https://www.ruby-lang.org/en/news/2019/03/13/ruby-2-6-2-released/'
)
version_263 = Version.find_or_create_by!(
string: '2.6.3',
state: 'available',
link: 'https://www.ruby-lang.org/en/news/2019/04/17/ruby-2-6-3-released/'
)
identity = Identity.find_or_create_by!(
name: 'Ruby Up!',
email: '<EMAIL>',
github_api_key: '<KEY>'
)
repo1 = Repository.find_or_create_by!(
name: 'namespace/repo1',
url: '<EMAIL>:namespace/repo1.git',
branch: 'master'
)
repo2 = Repository.find_or_create_by!(
name: 'namespace/repo2',
url: '<EMAIL>:namespace/repo2.git',
branch: 'master'
)
repo3 = Repository.find_or_create_by!(
name: 'namespace/repo3',
url: '<EMAIL>:namespace/repo3.git',
branch: 'develop'
)
if ENV['SEED_JOBS'] == 'true'
job1 = Job.create!(
repository: repo1,
name: 'Update to Ruby 2.6.3',
identity: identity,
version_from: version_262,
version_to: version_263,
config: Template.config,
state: 'created',
logs: ['First Execution', 'Second Execution']
) if repo1.jobs.count < 1
job2 = Job.create!(
repository: repo1,
name: 'Update to Ruby 2.6.3',
identity: identity,
version_from: version_262,
version_to: version_263,
config: Template.config,
state: 'completed'
) if repo1.jobs.count < 2
job3 = Job.create!(
repository: repo2,
name: 'Update to Ruby 2.6.3',
identity: identity,
version_from: version_262,
version_to: version_263,
config: Template.config,
state: 'failed'
) if repo2.jobs.empty?
end
<file_sep>class Repository < ApplicationRecord
URL_REGEX = /\A(?<user>.+)@(?<server>.[^:]+):(?<path>.+).git\z/
validates :name, presence: true, uniqueness: true
validates :url, presence: true, uniqueness: true, format: { with: URL_REGEX }
has_many :jobs, dependent: :destroy
def job
jobs.last
end
def server
url.match(URL_REGEX)[:server]
end
def path
url.match(URL_REGEX)[:path]
end
end
<file_sep>#!/usr/bin/env bash
set -e
registry="127.0.0.1:5000"
namespace="rubyup"
## Setup a local docker registry
docker stack deploy -c docker-stack-registry.yml rubyup_registry
## Build the socat image
image="$registry/$namespace/socat:latest"
cat Dockerfile.socat | docker build -t $image - # build with no context
docker push $image
## Build the platform image
image="$registry/$namespace/platform:latest"
docker build -t $image .
docker push $image
## Deploy the platform stack
docker stack deploy -c docker-stack-platform.yml rubyup_platform
## Build the worker base image
baseimage="$registry/$namespace/worker:base"
cat Dockerfile.worker | docker build -t $baseimage - # build with no context
docker push $baseimage
<file_sep>require 'rails_helper'
RSpec.describe Version do
let(:instance) { FactoryBot.create :version }
describe '.docker_registry' do
it 'returns the expected value' do
expect(described_class.docker_registry).to eq '127.0.0.1:5000'
end
end
describe '.docker_baseimage' do
it 'returns the expected value' do
expect(described_class.docker_baseimage).to eq '127.0.0.1:5000/rubyup/worker:base'
end
end
describe '#docker_image' do
it 'returns the expected value' do
expect(instance.docker_image).to eq '127.0.0.1:5000/rubyup/worker:ruby-2.6.3'
end
end
describe '#docker_repo' do
it 'returns the expected value' do
expect(instance.docker_repo).to eq '127.0.0.1:5000/rubyup/worker'
end
end
describe '#docker_tag' do
it 'returns the expected value' do
expect(instance.docker_tag).to eq 'ruby-2.6.3'
end
end
end
<file_sep>require 'rails_helper'
RSpec.describe UpdateJob do
let(:instance) { described_class.new }
let(:job) { FactoryBot.create :job }
describe '#perform' do
let(:container_double) do
instance_double(
'Docker::Container',
start: nil,
store_file: nil,
exec: [exec_stdout, exec_stderr, exec_status],
delete: nil
)
end
let(:exec_stdout) { [] }
let(:exec_stderr) { [] }
let(:exec_status) { 0 }
before do
allow(Docker::Container).to receive(:create).and_return(container_double)
end
let!(:req_github_api) do
stub_request(:post, "https://github.example.com/api/v3/repos/#{job.repository.path}/pulls").to_return(status: 200)
end
it 'creates a new docker container' do
instance.perform(job)
expect(Docker::Container).to have_received(:create).with(
'Cmd' => ['/bin/sh', '-c', 'while true; do sleep 30; done;'],
'Image' => '127.0.0.1:5000/rubyup/worker:ruby-2.6.3',
'WorkingDir' => '/home/rubyup'
)
expect(container_double).to have_received(:start)
end
it 'uploads files and executes commands' do
instance.perform(job)
expect(container_double).to have_received(:store_file).with '/home/rubyup/script.sh',
a_string_including('#!/bin/bash')
expect(container_double).to have_received(:exec).with([
'bash', '-l', '-c',
'sudo chown rubyup.rubyup /home/rubyup/script.sh; chmod +x /home/rubyup/script.sh'
], {})
expect(container_double).to have_received(:exec).with([
'bash', '-l', '-c',
'/home/rubyup/script.sh'
], {})
end
it 'uses a https url with token to clone the repo' do
instance.perform(job)
expect(container_double).to have_received(:store_file).with '/home/rubyup/script.sh',
a_string_including('git clone -b master https://github-api-key:x-oauth-basic@github.example.com')
end
it 'creates a github pull request' do
instance.perform(job)
expect(req_github_api.with do |req|
expect(req.headers['Authorization']).to eq 'token github-api-key'
expect(req.body).to be_json_eql({
base: job.repository.branch,
body: ':link: https://www.ruby-lang.org/en/news/2019/04/17/ruby-2-6-3-released/',
head: 'rubyup/update/ruby-2.6.3',
title: 'Update Ruby to 2.6.3'
}.to_json)
end).to have_been_made
end
it 'marks the job as completed' do
instance.perform(job)
expect(job.reload.state).to eq 'completed'
end
end
end
<file_sep>module Jobs
class Create
def initialize(blueprint:, repositories:)
self.blueprint = blueprint
self.repositories = repositories
end
def call
repositories.each do |repo|
job = blueprint.dup
job.repository_id = repo
job.save!
UpdateJob.perform_later(job)
end
end
private
attr_accessor :blueprint, :repositories
end
end
<file_sep>FROM ruby:2.7.1-alpine
MAINTAINER <NAME> <<EMAIL>>
ENV PORT 8080
ENV RAILS_ENV production
ENV RAILS_SERVE_STATIC_FILES true
ENV RAILS_LOG_TO_STDOUT true
ENV SECRET_KEY_BASE changeme
EXPOSE 8080
WORKDIR /usr/local/rubyup
ADD . .
RUN apk update \
&& apk add build-base zlib-dev tzdata nodejs yarn postgresql-dev \
&& rm -rf /var/cache/apk/* \
&& gem install bundler \
&& bundle install --without development test \
&& bundle exec rake assets:precompile \
&& addgroup -S rubyup && adduser -S rubyup -G rubyup -h /usr/local/rubyup \
&& chown -R rubyup.rubyup /usr/local/rubyup \
&& chown -R rubyup.rubyup /usr/local/bundle \
&& apk del build-base yarn
USER rubyup
COPY ./docker-entrypoint.sh /
ENTRYPOINT ["/docker-entrypoint.sh"]
CMD ["web"]
<file_sep># Ruby Up!
---
> :warning: This project is no longer being actively developed or maintained.
>
> Checkout [Depfu](https://depfu.com/blog/update-your-engines) as good alternative.
---
The goal of this project is to automate the update of the used ruby version in multiple GitHub repositories.
At the moment this is mostly a proof of concept and has a few rough edges.<br>
Regarding security it is recommended to run this only on a machine which is only reachable by you (best your local machine).
## Architecture
### Platform (Web UI)
This part of the application allows to manage the repositories which are updated and shows the status of the corresponding update jobs.
### Worker (Sidekiq / Docker API)
The worker is triggered by the creation of jobs in the Web UI and performs the following steps:
* Create new build docker container using the target Ruby version (pre-req.).
* Checks out the repository using the configured GitHub api-key.
* Switches to a new local branch
* Replaces the Ruby version in the configured list of files
* Runs `bundle install`
* Commits the change
* Creates a Pull Request using the configured GitHub API Key
## Setup
See the included `install.sh`. It can setup a complete deployment on a (empty) docker swarm.
## Licence
The application is available as open source under the terms of the MIT License.
<file_sep>FactoryBot.define do
factory :identity do
name { '<NAME>' }
email { '<EMAIL>' }
github_api_key { 'github-api-key' }
end
end
<file_sep>class AddKeysAndIndexes < ActiveRecord::Migration[5.2]
def change
add_foreign_key :jobs, :repositories
add_foreign_key :jobs, :identities
add_foreign_key :jobs, :versions, column: :version_from_id
add_foreign_key :jobs, :versions, column: :version_to_id
end
end
<file_sep>class VersionsController < ApplicationController
def index
@versions = Version.all.order(:string)
end
def new
@version = Version.new
end
def create
@version = Version.new(version_params)
if @version.save
BuildVersionImage.perform_later(@version)
redirect_to versions_path
else
render :new
end
end
private
def version_params
params.require(:version).permit(:string)
end
end
<file_sep>class Version < ApplicationRecord
validates :string, presence: true, uniqueness: true
validates :link, presence: true
validates :state, inclusion: { in: %w(created available failed) }
scope :for_select, -> { where(state: 'available').order(:string) }
after_initialize :set_defaults
class << self
def docker_registry
'127.0.0.1:5000'
end
def docker_baseimage
"#{docker_registry}/rubyup/worker:base"
end
end
def to_s
string
end
def docker_image
"#{docker_repo}:#{docker_tag}"
end
def docker_repo
"#{self.class.docker_registry}/rubyup/worker"
end
def docker_tag
"ruby-#{string}"
end
private
def set_defaults
self.state ||= 'created'
end
end
<file_sep>FactoryBot.define do
factory :job do
association :repository
association :identity
association :version_from, factory: :version_old
association :version_to, factory: :version_new
name { Template.name }
config { Template.config }
state { 'created' }
logs { [] }
end
end
<file_sep>module ApplicationHelper
def job_state_badge(state)
klass = {
'created' => 'secondary',
'rescheduled' => 'secondary',
'completed' => 'success',
'failed' => 'danger'
}.fetch(state)
content_tag :span, class: "badge badge-#{klass}" do
state
end
end
def version_state_badge(state)
klass = {
'created' => 'secondary',
'available' => 'success',
'failed' => 'danger'
}.fetch(state)
content_tag :span, class: "badge badge-#{klass}" do
state
end
end
end
|
4a8771fdc6a3129d0d91f7152dc8dd498710f9b8
|
[
"Ruby",
"JavaScript",
"Markdown",
"Dockerfile",
"Shell"
] | 35
|
Ruby
|
klausmeyer/rubyup
|
016b38626482ff91284bc6b1538346e50fe74095
|
aff6eb028053c29c6139d7a08c2053787f9d12d9
|
refs/heads/master
|
<repo_name>VictorBAR/ProgramaWEB.php<file_sep>/servicos/servicoCategoriaCompetidor.php
<?php
function definirCategoriaCompetidor ($nome, $idade) : ?string {
$categorias = [];
$categorias[] = "infantil";
$categorias[] = "adolescente";
$categorias[] = "adulto";
if (validarNome($nome)){
removerMensagemErro();
if ($idade >= 6 && $idade <= 12){
for ($c = 0 ; $c <= count($categorias); $c++){
if ($categorias[$c] == "infantil") {
setarMensagemSucesso("O competidor ".$nome." irá competir na categoria ".$categorias[$c]);
return null;
}
}
}
if ($idade > 12 && $idade <= 18){
for ($i = 0; $i <= count($categorias); $i++){
if($categorias[$i] == "adolescente"){
setarMensagemSucesso("O competidor ".$nome." irá competir na modalidade ".$categorias[$i]);
return null;
}
}
}
else{
for ($i = 0; $i <= count($categorias); $i++){
if ($categorias[$i] == "adulto"){
setarMensagemSucesso("O competidor ".$nome." irá competir na categoria ".$categorias[$i]);
return null;
}
}
}
}else {
removerMensagemSucesso();
return obterMensagemErro();
}
}<file_sep>/servicos/servicoValidacao.php
<?php
function validarNome(String $nome) : bool {
if (empty($nome)){
setarMensagemErro('O nome não pode ser vazio, por favor preencha-o novamente');
return false;
}
else if (strlen($nome) < 3){
setarMensagemErro('O nome precisar ter mais de 3 caracteres');
return false;
}
else if (strlen($nome) > 40){
setarMensagemErro("O nome só pode conter até 40 caracteres");
return false;
}
return true;
}<file_sep>/index.php
<?php
include 'servicos/servicoMensagemSessao.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
background-color: black;
color: white;
}
</style>
</head>
<body>
<?php
$mensagemDeErro = obterMensagemErro();
if (!empty($mensagemDeErro)) {
echo $mensagemDeErro;
}
$mensagemDeSucesso = obterMensagemSucesso();
if (!empty($mensagemDeSucesso)){
echo $mensagemDeSucesso;
}
?>
<p>FORMULÁRIO PARA INSCRIÇÃO DE COMPETIDORES</p>
<form action="script.php" method="post">
<p>Seu nome <input type="text" name="nome" id=""></p>
<p>Sua idade <input type="number" name="idade" id=""></p>
<p> <input type="submit" value="INSCREVER COMPETIDOR"></p>
</form>
</body>
</html>
|
133bdeaecf6517c2b34830f4f890ca2d2ceb987b
|
[
"PHP"
] | 3
|
PHP
|
VictorBAR/ProgramaWEB.php
|
f4c9ac6b60749a6ccaadede1bc328c53ea8192af
|
84329eed8e0292aea0f22a399695b4c3cd886c2d
|
refs/heads/master
|
<repo_name>maryville-swdv-630-19-sp2-3w/week-5-carasolomon<file_sep>/designPatterns.py
# <NAME> - Week 5 Assignment: Design Patterns
# Factory Pattern
from abc import ABCMeta, abstractclassmethod
class Rooms(metaclass=ABCMeta):
def __init__(self, name, bedrooms, price):
self.name = name
self.bedrooms = bedrooms
self.price = price
@classmethod
def getPrice(self):
pass
def __str__(self):
return '{} dollars per night'.format(self.price)
class PenthouseRoom(Rooms):
def getPrice(self):
return 398
class SingleBedRoom(Rooms):
def getPrice(self):
return 189
class DoubleBedRoom(Rooms):
def getPrice(self):
return 205
class RoomFactory(object):
@classmethod
def create(cls, room, *args):
room = room.lower().strip()
if room == 'penthouseroom':
return PenthouseRoom(*args)
elif room == 'singlebedroom':
return SingleBedRoom(*args)
elif room == 'doublebedroom':
return DoubleBedRoom(*args)
# Facade Pattern
class GetUserAccount:
def __init__(self):
self._account = Account()
self._payment = Payment()
def getInfo(self):
self._account.getAccountNumber()
class Account:
def __init__(self, _name, _address, _accountNumber, _paymentInfo):
self._name = _name
self._address = _address
self._accountNumber = _accountNumber
self._paymentInfo = _paymentInfo
def getAccountNumber(self):
return self._accountNumber
class Payment:
def __init__(self, _accountNumber, _creditCardNumber, _billingAddress):
self._accountNumber = _accountNumber
self._creditCardNumber = _creditCardNumber
self._billingAddress = _billingAddress
def getCardNumber(self):
return self._creditCardNumber
def main():
getInfo = GetUserAccount()
getInfo.getInfo()
# Singleton Pattern - One account instance open at a time
class Account2:
__instance = None
def __new__(cls):
if cls.__instance == None:
cls.__instance = "Open Account"
return cls.__instance
|
99fa379207137a4b06b601880960c1137d6a3b6a
|
[
"Python"
] | 1
|
Python
|
maryville-swdv-630-19-sp2-3w/week-5-carasolomon
|
f2d6da03c56d3a9f9df2e454a7154f26d8aa3a46
|
415228ae4068f1ed39bd44358f86e549a7ed5d8b
|
refs/heads/main
|
<file_sep>#!/usr/bin/env python3
# Created by <NAME>
# Created on May 2021
# This program determines positive/negative/zero numbers
def main():
# this function runs the integer identity
# input
print("Positive, negative or zero?")
integer = int(input("Enter an integer: "))
# process and output
if integer >= 0:
print("{} is a positive number!".format(integer))
elif integer <= 0:
print("{} is a negative number!".format(integer))
elif integer == 0:
print("{} is nothing but a zero!".format(integer))
if __name__ == "__main__":
main()
|
7c3a3fbfc1a111ca057b4941b6926104538f5fa0
|
[
"Python"
] | 1
|
Python
|
Jenoe-Balote/ICS3U-Unit3-04-Python
|
b7e2d27d6cceb26a06c2e71e940252f369d97a80
|
b72ab4eeba527c0f0517e7f02d0cd2e8b99ffabc
|
refs/heads/master
|
<file_sep>from django.db import models
class Pessoa(models.Model):
nome = models.CharField('Nome', max_length=100,blank=True)
cpf = models.CharField('CPF', max_length=14,blank=True)
telefone = models.CharField('Telefone', max_length=9,blank=True)
endereco = models.CharField('Endereco', max_length=250,blank=True)
cep = models.CharField('CEP', max_length=13,blank=True)
cidade = models.CharField('Cidade', max_length=100,blank=True)
bairro = models.CharField('Bairro', max_length=100,blank=True)
estado = models.CharField('estado', max_length=2,blank=True)
email = models.EmailField('Email', max_length=200,blank=True)
class Meta:
verbose_name_plural = 'Clientes'
verbose_name = 'Cliente'
def __str__(self):
return self.nome<file_sep>from django.urls import include, path
from . import views
urlpatterns = [
path('lista_cliente/', views.lista_cliente, name='lista_cliente'),
]<file_sep># Generated by Django 3.1 on 2020-08-08 01:16
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Pessoa',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nome', models.CharField(blank=True, max_length=100, verbose_name='Nome')),
('cpf', models.CharField(blank=True, max_length=14, verbose_name='CPF')),
('telefone', models.CharField(blank=True, max_length=9, verbose_name='Telefone')),
],
options={
'verbose_name': 'Cliente',
'verbose_name_plural': 'Clientes',
},
),
]
<file_sep>from django.forms import ModelForm
from cliente.models import Pessoa
from consultor.models import Consultor, Servico
from agenda.models import Agenda
class ClienteForm(ModelForm):
class Meta:
model = Pessoa
fields = '__all__'
class ConsultorForm(ModelForm):
class Meta:
model = Consultor
fields = '__all__'
class ServicoForm(ModelForm):
class Meta:
model = Servico
fields = '__all__'
class AgendaForm(ModelForm):
class Meta:
model = Agenda
fields = '__all__'<file_sep>from django.shortcuts import render, redirect, get_object_or_404
from cliente.models import Pessoa
from consultor.models import Consultor, Servico
from .forms import ClienteForm, ConsultorForm, ServicoForm, AgendaForm
from conta.forms import UsuarioForm, User
from agenda.models import Agenda
from datetime import *
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.contrib.auth.decorators import login_required
@login_required
def home(request):
data = datetime.now()
lista = Pessoa.objects.all()
total_clientes = Pessoa.objects.count()
total_servicos = Servico.objects.count()
total_agendamentos = Agenda.objects.count()
total_consultores = Consultor.objects.count()
paginator = Paginator(lista,5)
page = request.GET.get('page')
lista = paginator.get_page(page)
return render(request, 'index.html',{'lista':lista,'data':data,'total_clientes':total_clientes,'total_servicos':total_servicos,
'total_agendamentos':total_agendamentos,'total_consultores':total_consultores})
def base(request):
data_base = datetime.now()
return render(request,'base.html',{'data_base':data_base})
@login_required
def cliente(request):
if request.method == 'POST':
form = ClienteForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
form = ClienteForm()
return render(request, 'core/clienteform.html',{'form':form})
@login_required
def consultor(request):
if request.method == 'POST':
form = ConsultorForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
form = ConsultorForm()
return render(request, 'core/consultorform.html',{'form':form})
@login_required
def servico(request):
if request.method == 'POST':
form = ServicoForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
form = ServicoForm()
return render(request, 'core/servicoform.html',{'form':form})
@login_required
def agenda(request):
if request.method == 'POST':
form = AgendaForm(request.POST)
if form.is_valid():
form.save()
return redirect('lista')
else:
form = AgendaForm()
return render(request, 'core/agendaform.html',{'form':form})
@login_required
def lista(request):
relacao = Agenda.objects.all()
paginator = Paginator(relacao,5)
page = request.GET.get('page')
relacao = paginator.get_page(page)
return render(request, 'core/lista.html',{'relacao':relacao})
@login_required
def editar(request, id_agenda):
edite = get_object_or_404(Agenda, id=id_agenda)
if request.method == 'POST':
form = AgendaForm(request.POST, instance=edite)
if form.is_valid():
form.save()
return redirect('lista')
else:
form = AgendaForm(instance=edite)
return render(request, 'core/agendaform.html',{'form':form})
@login_required
def deletar(request, id_agenda):
exclui = Agenda.objects.get(id=id_agenda).delete()
return redirect('lista')
@login_required
def edita_cliente_home(request, id_cliente):
ed = get_object_or_404(Pessoa, id=id_cliente)
if request.method == 'POST':
form = ClienteForm(request.POST, instance=ed)
if form.is_valid():
form.save()
return redirect('home')
else:
form = ClienteForm(instance=ed)
return render(request, 'core/clienteform.html',{'form':form})
@login_required
def deleta_cliente_home(request, id_cliente):
exclui_cliente = Pessoa.objects.get(id=id_cliente).delete()
return redirect('home')
@login_required
def edita_cliente(request, id_cliente):
ed = get_object_or_404(Pessoa, id=id_cliente)
if request.method == 'POST':
form = ClienteForm(request.POST, instance=ed)
if form.is_valid():
form.save()
return redirect('lista_cliente')
else:
form = ClienteForm(instance=ed)
return render(request, 'core/clienteform.html',{'form':form})
@login_required
def deleta_cliente(request, id_cliente):
exclui_cliente = Pessoa.objects.get(id=id_cliente).delete()
return redirect('lista_cliente')
#Editar Consultor
@login_required
def edita_consultor(request, id_consultor):
ed = get_object_or_404(Consultor, id=id_consultor)
if request.method == 'POST':
form = ConsultorForm(request.POST, instance=ed)
if form.is_valid():
form.save()
return redirect('lista_consultor')
else:
form = ConsultorForm(instance=ed)
return render(request, 'core/consultorform.html',{'form':form})
@login_required
def deleta_consultor(request, id_consultor):
exclui_consultor = Consultor.objects.get(id=id_consultor).delete()
return redirect('lista_consultor')
#Editar Servico
@login_required
def edita_servico(request, id_servico):
ed = get_object_or_404(Servico, id=id_servico)
if request.method == 'POST':
form = ServicoForm(request.POST, instance=ed)
if form.is_valid():
form.save()
return redirect('lista_servico')
else:
form = ServicoForm(instance=ed)
return render(request, 'core/servicoform.html',{'form':form})
@login_required
def deleta_servico(request, id_servico):
exclui_servico = Servico.objects.get(id=id_servico).delete()
return redirect('lista_servico')
#Editar Usuário
@login_required
def edita_usuario(request, id_user):
ed = get_object_or_404(User, id=id_user)
if request.method == 'POST':
form = UsuarioForm(request.POST, instance=ed)
if form.is_valid():
form.save()
return redirect('lista_usuario')
else:
form = UsuarioForm(instance=ed)
return render(request, 'conta/add_usuario.html',{'form':form})
@login_required
def deleta_usuario(request, id_user):
exclui_usuario = User.objects.get(id=id_user).delete()
return redirect('lista_usuario')
<file_sep>from django.urls import include, path
from . import views
urlpatterns = [
path('lista_consultor/', views.lista_consultor, name='lista_consultor'),
path('lista_servico/', views.lista_servico, name='lista_servico'),
]<file_sep>from django.contrib import admin
from .models import Consultor, Servico
@admin.register(Consultor)
class ConsultorAdmin(admin.ModelAdmin):
list_display = ('nome', 'telefone')
search_fields = ('nome', 'telefone')
@admin.register(Servico)
class ServicoAdmin(admin.ModelAdmin):
list_display = ('nome', 'pagamento', 'valor_servico')
search_fields = ('nome',)<file_sep>from django.shortcuts import render
from cliente.models import Pessoa
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def lista_cliente(request):
relacao = Pessoa.objects.all()
paginator = Paginator(relacao,5)
page = request.GET.get('page')
relacao = paginator.get_page(page)
return render(request, 'core/lista_cliente.html',{'relacao':relacao})
<file_sep>{% extends "base.html" %}
{% load widget_tweaks %}
{% block body %}
<style type="text/css">
.alert {
padding: 0 15px;
margin-bottom: 1rem;
border: 1px solid transparent;
border-radius: .25rempx
}
.alert p{
padding: 7px 0 7px;
}
.alert.success{
color: #3c763d;
background-color: #dff0d8;
border-color: #d0e9c6;}
</style>
<br>
<br>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
<strong>Listar Agendamentos</strong>
</div>
<div class="panel-body">
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Cliente</th>
<th>Consultor</th>
<th>Serviço</th>
<th>Data</th>
<th>Hora</th>
<th>Status</th>
<th>Valor R$</th>
<th>Forma PG.</th>
<th>Editar</th>
<th>Deletar</th>
</tr>
</thead>
<tbody>
{% for list in relacao %}
<tr>
<td>{{list.cliente}}</td>
<td>{{list.consultor}}</td>
<td>{{list.servico}}</td>
<td>{{list.data}}</td>
<td>{{list.hora}}</td>
<td>{{list.get_status_display}}</td>
<td>{{list.preco}}</td>
<td>{{list.get_pagamento_display}}</td>
<td><a href="{% url 'editar' list.id %}" class="btn btn-info">Editar</a></td>
<td><a href="{% url 'deletar' list.id %}" class="btn btn-danger">Deletar</a></td>
</tr>
{% empty %}
<div class="alert danger">
<p>Sem agendamentos no momento</p>
</div>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
</div>
<div class="text-info">
<span class="step-links">
{% if relacao.has_previous %}
<a href="?page=1"></a>
<a class="text-info" href="?page={{ relacao.previous_page_number }}"> Anterior </a>
{% endif %}
<span class="current">
Paginas {{ relacao.number }} de {{ relacao.paginator.num_pages }}
</span>
{% if relacao.has_next %}
<a class="text-info" href="?page={{ relacao.next_page_number }}"> Próxima </a>
<a href="?page={{ relacao.paginator.num_pages }}"></a>
{% endif %}
</span>
</div>
{% endblock body %}<file_sep>from django.shortcuts import render
from consultor.models import Consultor, Servico
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
def lista_consultor(request):
relacao = Consultor.objects.all()
paginator = Paginator(relacao,5)
page = request.GET.get('page')
relacao = paginator.get_page(page)
return render(request, 'core/lista_consultor.html',{'relacao':relacao})
def lista_servico(request):
relacao = Servico.objects.all()
paginator = Paginator(relacao,5)
page = request.GET.get('page')
relacao = paginator.get_page(page)
return render(request, 'core/lista_servico.html',{'relacao':relacao})
<file_sep>from django.apps import AppConfig
class ConsultorConfig(AppConfig):
name = 'consultor'
<file_sep>from django.contrib import admin
from .models import Agenda
# Register your models here.
@admin.register(Agenda)
class AgendaAdmin(admin.ModelAdmin):
list_display = ('cliente', 'servico', 'consultor', 'data')
search_fields = ('cliente', 'servico', 'consultor')<file_sep>from django.urls import include, path
from . import views
urlpatterns = [
path('novo-usuario/', views.add_usuario, name='add_usuario'),
path('login-usuario/', views.user_login, name='user_login'),
path('logout-usuario/', views.logout_user, name='logout_user'),
path('lista_usuario/', views.lista_usuario, name='lista_usuario'),
]<file_sep># Generated by Django 3.1 on 2020-08-08 01:16
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Consultor',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nome', models.CharField(blank=True, max_length=100, verbose_name='Consultor')),
('telefone', models.CharField(blank=True, max_length=9, verbose_name='Telefone')),
],
options={
'verbose_name': 'Consultor',
'verbose_name_plural': 'Consultores',
},
),
migrations.CreateModel(
name='Servico',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nome', models.CharField(max_length=100, verbose_name='Seviço')),
('pagamento', models.CharField(blank=True, choices=[('D', 'Dinheiro'), ('CD', 'Cartão Debito'), ('CC', 'Cartão Credito')], max_length=2, verbose_name='Pagamento')),
],
options={
'verbose_name': 'Serviço',
'verbose_name_plural': 'Serviços',
},
),
]
<file_sep># TG - Revise Aqui
Projeto de conclusão de curso de Análise e Desenvolvimento de Sistemas<file_sep>from django.db import models
from cliente.models import Pessoa
from consultor.models import Consultor, Servico
class Agenda(models.Model):
cliente = models.ForeignKey(Pessoa, on_delete=models.CASCADE,null=True,blank=True)
consultor = models.ForeignKey(Consultor, on_delete=models.CASCADE,null=True,blank=True)
servico = models.ForeignKey(Servico, on_delete=models.CASCADE,null=True,blank=True)
data = models.DateField(auto_now_add=False, null=True)
hora = models.TimeField(auto_now_add=False, null=True)
status = (
('A', 'Aberto'),
('E', 'Andamento'),
('F', 'Fechado'),
)
status = models.CharField('Status', max_length=1, choices=status, null=True,blank=True)
preco = models.DecimalField('Preço', max_digits=7, decimal_places=2,null=True,blank=True)
pag = (
('D', 'Dinheiro'),
('CD', 'Cartão Debito'),
('CC', 'Cartão Credito'),
)
pagamento = models.CharField('Pagamento', max_length=2, choices=pag, null=True,blank=True)
class Meta:
verbose_name_plural = 'Agendas'
verbose_name = 'Agenda'
def __str__(self):
return "%s" % self.cliente<file_sep># Generated by Django 3.1 on 2020-08-09 17:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cliente', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='pessoa',
name='bairro',
field=models.CharField(blank=True, max_length=100, verbose_name='Bairro'),
),
migrations.AddField(
model_name='pessoa',
name='cep',
field=models.CharField(blank=True, max_length=13, verbose_name='CEP'),
),
migrations.AddField(
model_name='pessoa',
name='cidade',
field=models.CharField(blank=True, max_length=100, verbose_name='Cidade'),
),
migrations.AddField(
model_name='pessoa',
name='email',
field=models.EmailField(blank=True, max_length=200, verbose_name='Email'),
),
migrations.AddField(
model_name='pessoa',
name='endereco',
field=models.CharField(blank=True, max_length=250, verbose_name='Endereco'),
),
migrations.AddField(
model_name='pessoa',
name='estado',
field=models.CharField(blank=True, max_length=2, verbose_name='estado'),
),
]
<file_sep>from django.db import models
class Consultor(models.Model):
nome = models.CharField('Consultor', max_length=100,blank=True)
telefone = models.CharField('Telefone', max_length=9,blank=True)
class Meta:
verbose_name = 'Consultor'
verbose_name_plural = 'Consultores'
def __str__(self):
return self.nome
class Servico(models.Model):
nome = models.CharField('Seviço', max_length=100)
pag = (
('D', 'Dinheiro'),
('CD', 'Cartão Debito'),
('CC', 'Cartão Credito'),
)
pagamento = models.CharField('Pagamento', max_length=2, choices=pag,blank=True)
valor_servico = models.CharField('Valor Serviço', max_length=100,blank=True)
class Meta:
verbose_name = 'Serviço'
verbose_name_plural = 'Serviços'
def __str__(self):
return self.nome<file_sep>from django.urls import include, path
from . import views
urlpatterns = [
path('cliente/', views.cliente, name='cliente'),
path('consultor/', views.consultor, name='consultor'),
path('servico/', views.servico, name='servico'),
path('agenda/', views.agenda, name='agenda'),
path('lista/', views.lista, name='lista'),
path('editar/<int:id_agenda>/', views.editar, name='editar'),
path('deletar/<int:id_agenda>/', views.deletar, name='deletar'),
path('edita_cliente/<int:id_cliente>/', views.edita_cliente, name='edita_cliente'),
path('deleta_cliente/<int:id_cliente>/', views.deleta_cliente, name='deleta_cliente'),
path('edita_cliente_home/<int:id_cliente>/', views.edita_cliente_home, name='edita_cliente_home'),
path('deleta_cliente_home/<int:id_cliente>/', views.deleta_cliente_home, name='deleta_cliente_home'),
path('edita_consultor/<int:id_consultor>/', views.edita_consultor, name='edita_consultor'),
path('deleta_consuktor<int:id_consultor>/', views.deleta_consultor, name='deleta_consultor'),
path('edita_servico/<int:id_servico>/', views.edita_servico, name='edita_servico'),
path('deleta_servico/<int:id_servico>/', views.deleta_servico, name='deleta_servico'),
path('edita_usuario/<int:id_user>/', views.edita_usuario, name='edita_usuario'),
path('deleta_usuario/<int:id_user>/', views.deleta_usuario, name='deleta_usuario'),
]<file_sep>from django.contrib import admin
from .models import Pessoa
@admin.register(Pessoa)
class PessoaAdmin(admin.ModelAdmin):
list_display = ('nome', 'cpf','telefone')
search_fields = ('nome', 'cpf','telefone')<file_sep>from django.shortcuts import render, redirect
from .forms import UsuarioForm, User
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from cliente.models import Pessoa
def add_usuario(request):
if request.method == 'POST':
form = UsuarioForm(request.POST)
if form.is_valid():
u = form.save()
u.set_password(u.password)
u.save()
return redirect('home')
else:
form = UsuarioForm()
return render(request, 'conta/add_usuario.html',{'form':form})
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('<PASSWORD>')
user = authenticate(username=username, password=<PASSWORD>)
if user:
login(request,user)
return redirect('home')
else:
messages.error(request, 'usuário ou senha invalidos!')
return render(request, 'conta/login.html')
def logout_user(request):
logout(request)
return redirect('user_login')
def lista_usuario(request):
relacao = User.objects.all()
paginator = Paginator(relacao,5)
page = request.GET.get('page')
relacao = paginator.get_page(page)
return render(request, 'core/lista_usuario.html',{'relacao':relacao})
<file_sep># Generated by Django 3.1 on 2020-08-08 01:16
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('consultor', '0001_initial'),
('cliente', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Agenda',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('data', models.DateField(null=True)),
('hora', models.TimeField(null=True)),
('status', models.CharField(blank=True, choices=[('A', 'Aberto'), ('E', 'Andamento'), ('F', 'Fechado')], max_length=1, null=True, verbose_name='Status')),
('preco', models.DecimalField(blank=True, decimal_places=2, max_digits=7, null=True, verbose_name='Preço')),
('pagamento', models.CharField(blank=True, choices=[('D', 'Dinheiro'), ('CD', 'Cartão Debito'), ('CC', 'Cartão Credito')], max_length=2, null=True, verbose_name='Pagamento')),
('cliente', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='cliente.pessoa')),
('consultor', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='consultor.consultor')),
('servico', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='consultor.servico')),
],
options={
'verbose_name': 'Agenda',
'verbose_name_plural': 'Agendas',
},
),
]
|
a129e5d1c10e438de85dd2d5cc8c47ba9bf7fc5c
|
[
"Markdown",
"Python",
"HTML"
] | 22
|
Python
|
eliseupc/TG---Revise-Aqui-
|
69c3bc7706b8b983db5a109416b0f3fa56eec090
|
9442f0ed5371b50ef9c5a9e77b27eb5eb4c0357b
|
refs/heads/master
|
<repo_name>amir734jj/dotfiles<file_sep>/README.md
# dotfiles
Collection of my .files
- `.bashrc`
- `.gitconfig`
<file_sep>/.bashrc
alias open=nautilus
export UWM_PASSWORD="<PASSWORD>"
export LOCAL_PASSWORD="<PASSWORD>"
# dos2unix fast ...
function dos2unix() {
tr -d '\r' < "$1" > t
mv -f t "$1"
}
export -f dos2unix
# login to AFS fast ...
function klog() {
echo "AFS Login ...";
echo ${UWM_PASSWORD} | kinit <EMAIL>;
aklog;
tokens;
printf "\nFinished Login ...\n"
}
export -f klog
# flush-dns fast ...
function flush-dns() {
echo "Flushing DNS";
sudo systemd-resolve --flush-caches;
sudo systemd-resolve --statistics;
}
export -f flush-dns
# login to andrew fast ...
function andrew() {
sshpass -p ${UWM_PASSWORD} ssh <EMAIL> -p 53211 -tt
}
export -f andrew
# login to local fast ...
function amir-pc() {
sshpass -p ${LOCAL_PASSWORD} ssh <EMAIL> -p 53211 -tt
}
export -f amir-pc
function publish() {
git add .;
git commit -m "wip ...";
git push;
}
export -f publish
export PATH="/snap/bin:$PATH"
export PATH="$PATH:$HOME/.dotnet/tools/"
export PATH="$PATH:$HOME/.local/bin"
|
9d70a6b9c5e4f52f752d058f6741847e80fd85a1
|
[
"Markdown",
"Shell"
] | 2
|
Markdown
|
amir734jj/dotfiles
|
e725ce4eb839d015851bd24551fa539eb16b38aa
|
a071df14077f2b24a2400abd4158576ec5d08bfd
|
refs/heads/master
|
<file_sep>import LoaderManager = laya.net.LoaderManager;
import Handler = laya.utils.Handler;
import Loader = laya.net.Loader;
import DH from "../../data/DH";
import {getBtnData, getBtnLink, getUILink} from "../Mgr/view/ui/comp/Comp";
import Conf from "../../data/Conf";
/**
* Created by ShanFeng on 6/5/2017.
*/
export default class Preloader extends LoaderManager {
private preArr: string[][];
constructor() {
super();
this.preArr = [
//橙光菜单
[
"local/img/sys/game_menu2.png",
"local/img/sys/game_menu2_pitch.png",
"local/img/sys/game_menu3.png",
"local/img/sys/game_menu3_pitch.png"
],
//选项资源
this.parseBtn(DH.instance.story.sys.MessageBox.choiceButtonIndex),
//对话框资源
[getUILink(DH.instance.story.sys.MessageBox.talk.bgImg.path)]
];
this.next();
}
parseBtn(btnIdx: number) {
let bd = getBtnData(btnIdx);
return [getBtnLink(bd.image1.path), getBtnLink(bd.image2.path)];
}
private next(): void {
if (this.preArr.length) {
super.load(this.preArr.shift(), Handler.create(this, this.next), Handler.create(this, this.progress), Loader.IMAGE, 2, true, "preload", false);
} else {
if (Conf.info.single) {
//todo:story.sys.skipTitle是否跳过标题
DH.instance.story.gotoChapter(DH.instance.story.sys.startStoryId);
delete DH.instance.binLoader;
} else {
//Todo:该处可提前至开始剧情赋值之后实现提前载入,但实际意义待考
require(["js/mod/loader/StepLoader"], (StepLoader) => {
DH.instance.binLoader = new StepLoader.default(DH.instance.story.sys.startStoryId);
});
}
// todo:开始预载伺服
}
}
private progress() {
}
}<file_sep>import Dictionary = laya.utils.Dictionary;
import Scene from "./Scene";
import {Cmd} from "../../data/sotry/Story";
/**
* Created by ShanFeng on 5/3/2017.
*/
export default class CmdList extends Dictionary {
constructor() {
super();
this.set(100, "显示文章");
this.set(101, "剧情分歧");
this.set(1010, "剧情分歧EX");
this.set(1011, "剧情分歧EX2");
this.set(102, "剧情分歧结束");
this.set(103, "自动播放剧情");
this.set(104, "快进剧情");
this.set(105, "数值输入");
this.set(106, "提示消息框");
this.set(107, "注释");
this.set(108, "分支选项内容");
this.set(109, "消失对话框");
this.set(110, "打开指定网页");
this.set(111, "禁用开启菜单功能");
this.set(112, "悬浮组件开关");
this.set(150, "刷新UI画面");
this.set(151, "返回游戏界面");
this.set(200, "条件分歧");
this.set(201, "条件分歧结束");
this.set(202, "循环");
this.set(203, "以上反复");
this.set(204, "按钮分歧");
this.set(205, "按钮分歧结束");
this.set(206, "跳转剧情");
this.set(207, "数值操作");
this.set(208, "返回标题画面");
this.set(209, "中断循环");
this.set(210, "等待");
this.set(211, "除此之外的场合");
this.set(212, "按钮分歧内容");
this.set(213, "二周目变量");
this.set(214, "呼叫游戏界面");
this.set(215, "字符串");
this.set(216, "高级数值操作");
this.set(217, "高级条件分歧");
this.set(218, "强制存档读档");
this.set(219, "气泡式效果");
this.set(251, "呼叫子剧情");
this.set(301, "天气");
this.set(302, "震动");
this.set(303, "画面闪烁");
this.set(304, "准备转场");
this.set(305, "转场开始");
this.set(306, "更改场景色调");
this.set(307, "插入到BGM鉴赏");
this.set(308, "插入到CG鉴赏");
this.set(400, "显示图片");
this.set(401, "淡出图片");
this.set(402, "移动图片");
this.set(403, "显示心情");
this.set(404, "旋转图片");
this.set(405, "资源预加载(仅web用)");
this.set(406, "显示动态图片");
this.set(407, "变色");
this.set(501, "播放背景音乐");
this.set(502, "播放音效");
this.set(503, "播放语音");
this.set(504, "播放背景音效");
this.set(505, "淡出背景音乐");
this.set(506, "停止音效");
this.set(507, "停止语音");
this.set(508, "淡出音效");
}
/**
* 打印解析结果
*/
printCmdArr(cmdArr: Cmd[]) {
for (let i in cmdArr) {
let cmd = cmdArr[i];
console.log("cid:", i, "code:", cmd.code, this.get(cmd.code), this.getDetails(cmd));
}
}
getDetails(cmd: Cmd) {
switch (cmd.code) {
case 100:
return cmd.para[2];
case 203:
case 209:
case 211:
case 102:
case 108:
case 212:
case 201:
case 205:
return "=> " + cmd.links[0];
case 101:
case 1010:
case 1011:
case 204:
return cmd.links;
case 200:
case 217:
return cmd.para[5] + " ? " + cmd.links[0] + " : " + cmd.links[1];
case 210:
return cmd.para[0] + " frames";
case 207:
return cmd.para[4];
case 206:
case 251:
return "==> " + cmd.para[0];
default:
return "";
}
}
}
/*
等待集合:
case 100://"显示文章"
//状态指令
case 210://等待
case 103://"自动播放剧情"
case 104://"快进剧情"
//数值
case 105://"数值输入"
case 207://"数值操作"
case 213://"二周目变量"
case 215://"字符串"
case 216://"高级数值操作"
//显示控制指令
case 110://"打开指定网页";
case 111://"禁用开启菜单功能";
case 112://"悬浮组件开关";
//资源管理指令
case 405://"资源预加载(仅web用)";
//剧情指令
case 206://"跳转剧情"
case 251: //"呼叫子剧情"
//界面指令
case 150:// "刷新UI画面"
case 151: //"返回游戏界面"
case 208: //"返回标题画面"
case 214: //"呼叫游戏界面"
case 218: //"强制存档读档"
//显示
case 100://"显示文章"
case 106://"提示消息框"
case 107://"注释"
case 109://"消失对话框"
case 219://"气泡式效果"
case 301://"天气"
case 302://"震动"
case 303://"画面闪烁"
case 304://"准备转场"
case 305://"转场开始"
case 306://"更改场景色调"
case 307://"插入到BGM鉴赏"
case 308://"插入到CG鉴赏"
case 400://"显示图片"
case 401://"淡出图片"
case 402://"移动图片"
case 403://"显示心情"
case 404://"旋转图片"
case 406://"显示动态图片"
case 407://"变色"
//声音
case 501://"播放背景音乐"
case 502://"播放音效"
case 503://"播放语音"
case 504://"播放背景音效"
case 505://"淡出背景音乐"
case 506://"停止音效"
case 507://"停止语音"
case 508://"淡出音效"
*/
<file_sep>import {Cmd} from "../../data/sotry/Story";
import {Mgr} from "./Mgr";
/**
* Created by ShanFeng on 5/15/2017.
*/
export default class AssMgr extends Mgr {
exe(cmd: Cmd) {
switch (cmd.code) {
case 405://"资源预加载(仅web用)";
}
}
}
<file_sep>import Handler = laya.utils.Handler;
import Loader = laya.net.Loader;
import Byte = laya.utils.Byte;
import Color = laya.utils.Color;
import Conf from "../../data/Conf";
import DH, {IBinloader} from "../../data/DH";
import DStory, {
BGM,
BGMItem,
CG,
CGItem,
Cmd,
CusUI,
CusUIItem,
DChapter,
DFLayer,
DFLayerItem,
GameMenu,
IdxBtn,
ImgBtn,
MsgBox,
Music,
NameWin,
Path,
Replay,
SaveData,
Setting,
TalkWin,
Title,
VPRect
} from "../../data/sotry/Story";
import Preloader from "./Preloader";
/**
* Created by ShanFeng on 4/24/2017.
* assetsmap、storymap加载器
* 结果序列化之后自行回收
* 分包情况下追建StepLoader用于后继剧情待载
* 宿主置于DH.binLoader
*/
export class BinLoader implements IBinloader {
single: boolean;
private bufArr: any[] = [];
/**
* bin加载器
* 负责mapbin/gamebin的加载及解析
* @param localTest 是否本地测试模式(数据文件放在oplayer/local)
*/
constructor(localTest: boolean = false) {
//本地测试
Conf.localTest.on = localTest;
if (Conf.localTest.on) {
this.load(Conf.localTest.mb);
return;
}
let url: string = Conf.domain.cdn + "web/" +
Conf.info.gid + "/" + Conf.info.ver + "/Map" +
(Conf.info.qlty != "0" ? "_" + Conf.info.qlty : "") + ".bin";
this.load(url);
//todo:jason格式的resourceBin下载&解析
/*url = (Conf.query("testPath") ? Conf.webApi.testSvr : Conf.webApi.svr) +
"api/oapi_map.php?action=create_bin&" +
"guid=" + Conf.info.gid +
"&version=" + Conf.info.ver +
"&quality=" + Conf.info.qlty;
this.loadJason(url);*/
if (Conf.info.miniPath) {
url = Conf.domain.cdn + Conf.info.miniPath;
this.load(url);
}
}
private load(url: string) {
let idx: number = this.bufArr.push(url);
Laya.loader.load(url,
Handler.create(this, this.completeHandler, [idx], true),
Handler.create(this, BinLoader.progressHandler, [url], true),
Loader.BUFFER, 0, true, "bin", false);
}
private static progressHandler(fName: string, p: number) {
DH.instance.eventPoxy.event(Conf.LOADING_PROGRESS, [fName, p]);
}
private completeHandler(idx: number, ab: ArrayBuffer) {
this.bufArr[idx - 1] = new Byte(ab);
laya.net.Loader.clearResByGroup("bin");
if (this.bufArr.every(fullyLoadedTester)) {
for (let i: number = 0; i < this.bufArr.length; i++) {
let byte: Byte = this.bufArr[i];
let len: number = byte.getInt32();
if (Conf.info.qlty == "31")
for (let i: number = 0; i < len; i++)
DH.instance.resMap.set(byte.getUTFBytes(byte.getInt32()), {
size: byte.getInt32(), md5: byte.getUTFBytes(byte.getInt32()),
info: byte.getUTFBytes(byte.getInt32()), obj: {w: NaN, h: NaN}
});
else
for (let i: number = 0; i < len; i++)
DH.instance.resMap.set(byte.getUTFBytes(byte.getInt32()), {
size: byte.getInt32(),
md5: byte.getUTFBytes(byte.getInt32())
});
if (byte.bytesAvailable > 0)
console.log("%c something left in assets bin", 'color: #FF5555');
byte.clear();
}
Conf.info.single = this.single = this.bufArr.length == 1;
this.loadChapter(this.single ? Conf.starName.single : Conf.starName.multiple);
}
function fullyLoadedTester(ele: any): boolean {
return ele instanceof Byte;
}
}
/**
* 分包数据仅包含storyInfo
* 单包数据含剧情
* @param s
*/
loadChapter(s: string | number) {
if (typeof s == "number") {
s = `game${s}.bin`;
}
Laya.loader.load(Conf.localTest.on ? Conf.localTest.sb : DH.instance.getResLink(s),
Handler.create(this, this.sCompleteHandler, null, true),
Handler.create(this, BinLoader.progressHandler, [s], true),
Loader.BUFFER, 0, false, "bin", false);
}
private sCompleteHandler(ab: ArrayBuffer) {
let byte: Byte = new Byte(ab);
if (byte.readUTFBytes(6) == "ORGDAT") {
//reset story
let story: DStory = DH.instance.story = new DStory();
//for header
Conf.info.ver = story.header.ver = byte.getInt32();
Conf.frameworks.width = story.header.gWidth = byte.getInt32();
Conf.frameworks.height = story.header.gHeight = byte.getInt32();
story.header.mPWid = byte.getInt32();
story.header.mPHei = byte.getInt32();
story.header.gUid = parseUTF();
story.header.title = parseUTF();
story.header.gVer = byte.getInt32();
story.header.crc32 = byte.getInt32();
byte.pos += 4;//project main len
//for system
byte.pos += 4;//system len
story.sys.fontName = parseUTF();
story.sys.fontSize = byte.getInt32();
//Todo:该平台特性化操作应转移至控制层
//0211 移动端字体较大,pc端较小,原始字体大小h5一行全是字可能顶出屏幕空间
if (Laya.Browser.onMobile || Laya.Browser.onIOS) {
story.sys.fontSize *= 0.85;
} else {
story.sys.fontSize *= 0.8;
}
story.sys.fontColor4Msg = new Color(parseUTF());
story.sys.fontColor4UI = new Color(parseUTF());
if (Conf.info.ver >= 101) {
story.sys.fontStyle = byte.getInt32();
}
story.sys.skipTitle = byte.getInt32() != 0;
story.sys.startStoryId = byte.getInt32();
story.sys.autoUpdate = byte.getInt32() != 0;
story.sys.icon = parsePath();
story.sys.showAD = byte.getInt32() != 0;
story.sys.authorWords = parseUTF();
story.sys.authorWordsTime = byte.getInt32();
story.sys.autoRun = byte.getInt32() != 0;
story.sys.showSysMenu = byte.getInt32() != 0;
story.sys.SEClick = parseMusic();
story.sys.SEMove = parseMusic();
story.sys.SECancel = parseMusic();
story.sys.SEError = parseMusic();
story.sys.title = parseTitle(); //标题画面
story.sys.gMenu = parseGameMenu();//菜单
story.sys.CG = parseCG();//CG
story.sys.BGM = parseBGM();//BGM
story.sys.SaveData = parseSaveData();//SAVE
story.sys.MessageBox = parseMsgBox();//对话框
story.sys.Replay = parseReplay();//回放
story.sys.Setting = parseSetting();//设置
story.sys.Buttons = parseImgBtnArr();
story.sys.UIInitSave = byte.getInt32() != 0;
if (Conf.info.ver >= 103) {
story.sys.Cuis = parseCusUIArr();
story.sys.MenuIndex = byte.getInt32();
} else {
story.sys.Cuis = null;
story.sys.MenuIndex = 0;
}
//for commands
//兼容单包、分包策略
if (this.single) {
byte.pos += 4;
story.name = parseUTF();
story.dChapterArr = parseChapterArr();
}
if (Conf.info.ver >= 104) {
story.fLayerArr = parseFLayerArr();
}
if (byte.bytesAvailable > 0) {
console.log("%c something left in story bin", 'color: #FF5555');
}
byte.clear();
//region For game data init
DH.instance.preloader = new Preloader();
Laya.stage.size(Conf.frameworks.width, Conf.frameworks.height);
//endregion
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Parse function~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
function parseUTF(): string {
return byte.getUTFBytes(byte.getInt32());
}
function parsePath(): Path {
byte.pos += 4;//structure len
return {from: byte.getInt32(), path: parseUTF()}
}
function parseMusic(): Music {
byte.pos += 4;//structure len
return {path: parsePath(), vol: byte.getInt32()}
}
function parseTitle(): Title {
byte.pos += 4;//structure len
return {
showLog: byte.getInt32() != 0,
logoImage: parsePath(),
titleImage: parsePath(),
drawTitle: byte.getInt32() != 0,
bgm: parseMusic(),
buttons: parseIdxBtnArr()
}
}
function parseIdxBtnArr(): IdxBtn[] {
let arr: IdxBtn[] = [];
let len = byte.getInt32();
for (let i = 0; i < len; i++) {
arr.push(parseIdxBtn());
}
return arr;
}
function parseIdxBtn(): IdxBtn {
byte.pos += 4; //structure len
return {idx: byte.getInt32(), x: byte.getInt32(), y: byte.getInt32()};
}
function parseImgBtnArr(): ImgBtn[] {
let arr: ImgBtn[] = [];
let len = byte.getInt32();
for (let i = 0; i < len; i++) {
arr.push(parseImgBtn());
}
return arr;
}
function parseImgBtn(): ImgBtn {
byte.pos += 4; //structure len
return {
name: parseUTF(),
image1: parsePath(),
image2: parsePath(),
x: byte.getInt32(),
y: byte.getInt32()
}
}
function parseGameMenu(): GameMenu {
byte.pos += 4;
return {bgImg: parsePath(), buttons: parseIdxBtnArr()};
}
function parseCG(): CG {
byte.pos += 4;
return {
bgImg: parsePath(),
column: byte.getInt32(),
spanRow: byte.getInt32(),
spanCol: byte.getInt32(),
showMsg: byte.getInt32() != 0,
msgX: byte.getInt32(),
msgY: byte.getInt32(),
zoom: byte.getInt32(),
cgx: byte.getInt32(),
cgy: byte.getInt32(),
noPic: parsePath(),
CGList: parseCGList(),
vpRect: parseVPRect(),
backButton: parseIdxBtn(),
closeButton: parseIdxBtn()
}
}
function parseVPRect(): VPRect {
byte.pos += 4;
return {x: byte.getInt32(), y: byte.getInt32(), w: byte.getInt32(), h: byte.getInt32()};
}
function parseCGList(): CGItem[] {
let arr: CGItem[] = [];
let len = byte.getInt32();
for (let i = 0; i < len; i++) {
arr.push(parseCGItem());
}
return arr;
}
function parseCGItem(): CGItem {
byte.pos += 4;
return {name: parseUTF(), path: parsePath(), msg: parseUTF()};
}
function parseBGM(): BGM {
byte.pos += 4;
return {
bgImg: parsePath(),
column: byte.getInt32(),
spanRow: byte.getInt32(),
spanCol: byte.getInt32(),
showPic: byte.getInt32() != 0,
showMsg: byte.getInt32() != 0,
px: byte.getInt32(),
py: byte.getInt32(),
mx: byte.getInt32(),
my: byte.getInt32(),
nx: byte.getInt32(),
ny: byte.getInt32(),
noName: parseUTF(),
noPic: parsePath(),
bgmList: parseBgmItemList(),
vpRect: parseVPRect(),
selectButton: parseIdxBtn(),
closeButton: parseIdxBtn()
}
}
function parseBgmItemList(): BGMItem[] {
let arr: BGMItem[] = [];
let len = byte.getInt32();
for (let i = 0; i < len; i++) {
arr.push(parseBGMItem());
}
return arr;
}
function parseBGMItem(): BGMItem {
byte.pos += 4;
return {
name: parseUTF(),
bgmPath: parsePath(),
picPath: parsePath(),
msg: parseUTF()
}
}
function parseSaveData(): SaveData {
byte.pos += 4;
return {
showMapName: byte.getInt32() != 0,
showDate: byte.getInt32() != 0,
bgImg: parsePath(),
max: byte.getInt32(),
column: byte.getInt32(),
spanRow: byte.getInt32(),
spanCol: byte.getInt32(),
showMinPic: byte.getInt32() != 0,
nameX: byte.getInt32(),
nameY: byte.getInt32(),
dateX: byte.getInt32(),
dateY: byte.getInt32(),
picX: byte.getInt32(),
picY: byte.getInt32(),
zoom: byte.getInt32(),
vpRect: parseVPRect(),
backButton: parseIdxBtn(),
closeButton: parseIdxBtn()
}
}
function parseMsgBox(): MsgBox {
byte.pos += 4;
return {
faceStyle: byte.getInt32(),
choiceButtonIndex: byte.getInt32(),
talk: parseTalkWin(),
name: parseNameWin()
}
}
function parseTalkWin(): TalkWin {
byte.pos += 4;
let tw: TalkWin = {
backX: byte.getInt32(),
backY: byte.getInt32(),
bgImg: parsePath(),
FaceBorderImage: parsePath(),
FaceBorderX: byte.getInt32(),
FaceBorderY: byte.getInt32()
};
tw.textX = byte.getInt32();
byte.pos += 4;
tw.textY = byte.getInt32();
byte.pos += 4;
tw.buttons = parseIdxBtnArr();
return tw;
}
function parseNameWin(): NameWin {
byte.pos += 4;
return {
backX: byte.getInt32(),
backY: byte.getInt32(),
bgImg: parsePath(),
isCenter: byte.getInt32() != 0,
textX: byte.getInt32(),
textY: byte.getInt32(),
}
}
function parseReplay(): Replay {
byte.pos += 4;
return {
bgImg: parsePath(),
closeButton: parseIdxBtn(),
vpRect: parseVPRect()
}
}
function parseSetting(): Setting {
byte.pos += 4;
return {
bgImg: parsePath(),
barNone: parsePath(),
barMove: parsePath(),
BgmX: byte.getInt32(),
BgmY: byte.getInt32(),
SeX: byte.getInt32(),
SeY: byte.getInt32(),
VoiceX: byte.getInt32(),
VoiceY: byte.getInt32(),
ShowFull: byte.getInt32() != 0,
ShowAuto: byte.getInt32() != 0,
ShowBGM: byte.getInt32() != 0,
ShowSE: byte.getInt32() != 0,
ShowVoice: byte.getInt32() != 0,
ShowTitle: byte.getInt32() != 0,
closeButton: parseIdxBtn(),
fullButton: parseIdxBtn(),
winButton: parseIdxBtn(),
AutoOn: parseIdxBtn(),
AutoOff: parseIdxBtn(),
TitleButton: parseIdxBtn()
}
}
function parseCusUIArr(): CusUI[] {
let arr: CusUI[] = [];
let len = byte.getInt32();
for (let i = 0; i < len; i++) {
arr.push(parseCusUI());
}
return arr;
}
function parseCusUI(): CusUI {
byte.pos += 4;
return {
loadEvent: parseCmdArr(),
afterEvent: parseCmdArr(),
controls: parseCusUIItemArr(),
showEffect: byte.getInt32(),
isMouseExit: byte.getInt32() != 0,
isKeyExit: byte.getInt32() != 0
}
}
function parseCusUIItemArr(): CusUIItem[] {
let arr: CusUIItem[] = [];
let len = byte.getInt32();
for (let i = 0; i < len; i++) {
arr.push(parseCusUIItem());
}
return arr;
}
function parseCusUIItem(): CusUIItem {
byte.pos += 4;
return {
cmdArr: parseCmdArr(),
type: byte.getInt32(),
useStr: byte.getInt32() != 0,
image1: parseUTF(),
image2: parseUTF(),
strIdx: byte.getInt32(),
useVar: byte.getInt32() != 0,
x: byte.getInt32(),
y: byte.getInt32(),
useIdx: byte.getInt32() != 0,
index: byte.getInt32(),
maxIdx: byte.getInt32(),
color: new Color(parseUTF())
}
}
function parseFLayerArr(): DFLayer[] {
let arr: DFLayer[] = [];
let len = byte.getInt32();
for (let i = 0; i < len; i++) {
arr.push(parseFLayer());
}
return arr;
}
function parseFLayer(): DFLayer {
return {
cmdArr: parseCmdArr(),
x: byte.getInt32(),
y: byte.getInt32(),
name: parseUTF(),
itemArr: parseFLayerItemArr()
}
}
function parseFLayerItemArr(): DFLayerItem[] {
let arr: DFLayerItem[] = [];
let len = byte.getInt32();
for (let i = 0; i < len; i++) {
arr.push(parseFLayerItem());
}
return arr;
}
function parseFLayerItem(): DFLayerItem {
return {
type: byte.getInt32(),
x: byte.getInt32(),
y: byte.getInt32(),
image: parseUTF(),
useStr: byte.getInt32() != 0,
idxOfStr: byte.getInt32(),
strIdx: byte.getInt32(),
varIdx: byte.getInt32(),
color: new Color(parseUTF())
}
}
function parseChapterArr(): DChapter[] {
let arr: DChapter[] = [];
let len = byte.getInt32();
for (let i = 0; i < len; i++) {
arr.push(parseDchapter());
}
return arr;
}
function parseDchapter(): DChapter {
byte.pos += 4;
return {
name: parseUTF(),
id: byte.getInt32(),
cmdArr: parseCmdArr()
}
}
function parseCmdArr(): Cmd[] {
let arr: Cmd[] = [];
let len = byte.getInt32();
for (let i = 0; i < len; i++) {
arr.push(parseCmd());
}
return arr;
}
function parseCmd(): Cmd {
byte.pos += 4;
let c = byte.getInt32();
byte.pos += 4;
let p = parsePara();
return {code: c, para: p};//{code: byte.getInt32(), idt: byte.getInt32(), para: parsePara()};
}
function parsePara(): string[] {
let arr: string[] = [];
let len = byte.getInt32();
for (let i = 0; i < len; i++) {
arr.push(parseUTF());
}
return arr;
}
/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Parse function end~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
}
}
<file_sep>/**
* Created by ShanFeng on 5/8/2017.
*/
import Sprite = laya.display.Sprite;
import Event = laya.events.Event;
import {MenuEnum} from "../ui/UIFac";
import {Cmd} from "../../../../data/sotry/Story";
import {Layer} from "./Layer";
import {Menu} from "../ui/comp/Menu";
import {MSG} from "../ui/comp/MSG";
import Chapter from "../../../cmd/chapter/Chapter";
export default class UILayer extends Layer {
ml: Sprite;
msg: MSG;
constructor() {
super();
this.ml = new Sprite();
this.ml.zOrder = 100;
this.addChild(this.ml);
}
exe(cmd: Cmd) {
switch (cmd.code) {
//UI交互类
case 100 : {//"显示文章"
this.showMSG(cmd);
break;
}
case 109: //"消失对话框"
this.showMSG();
break;
case 101: //剧情分歧
case 1010: //剧情分歧EX
case 1011: //剧情分歧EX2
case 204: { //按钮分歧
this.showSelector(cmd);
return;
}
//UI控制指令
case 151: //"返回游戏界面"
this.clearMenu();
break;
case 208: //"返回标题画面"
this.showMenu(MenuEnum.title);
break;
case 214: //"呼叫游戏界面"
this.showMenu(parseInt(cmd.para[0]));
break;
case 110: //"打开指定网页";
break;
case 111: //"禁用开启菜单功能";
break;
case 150: //"刷新UI画面"
break;
}
}
private showMSG(cmd: Cmd = null) {
if (!cmd) {
if (this.msg && this.msg.parent)
this.removeChild(this.msg);
} else
this.addChildAt(this.msg = this.uiFac.getMSG(cmd), 0);
}
private showSelector(cmd: Cmd) {
this.addChild(this.uiFac.getSelector(cmd));
}
showMenu(idx: number) {
if (idx < 10000)
this.clearMenu();
let m: Menu = this.uiFac.getMenu(idx);
m.once(Event.CLOSE, this, this.closeMenu, [idx]);
this.ml.addChild(m);
}
private clearMenu() {
while (this.ml.numChildren) {
let m = <Menu>this.ml.getChildAt(0);
if (m.idx < 10000)
m.close();
this.ml.removeChild(m);
}
}
private closeMenu(idx: number = NaN) {
if (idx > 10000)
this.ml.removeChild(this.uiFac.getMenu(idx));
else
this.clearMenu();
if (this.ml.numChildren == 0)
this.dh.cmdLine.insertChapter(new Chapter({
id: NaN,
name: "code_151(close win)",
cmdArr: [{code: 151, para: [""], links: []}]
}));
}
checkHotarea(cmd: Cmd) {
return this.uiFac.getHotarea().check(cmd);
}
reset() {
while (this.ml.numChildren)
this.ml.removeChildAt(0);
if (this.msg && this.msg.parent)
this.removeChild(this.msg);
}
};<file_sep>import {Cmd} from "../../data/sotry/Story";
/**
* Created by ShanFeng on 5/8/2017.
*/
export interface ILinkage {
link?: number
}
export default class Scene implements ILinkage {
link: number;
cmdArr: Cmd[] = [];
constructor(link: number = -1) {
this.link = link;
}
};<file_sep>import {Cmd} from "../../../../data/sotry/Story";
import {Layer} from "./Layer";
/**
* Created by ShanFeng on 5/29/2017.
*/
export default class FloatLayer extends Layer {
constructor() {
super();
}
exe(cmd: Cmd) {
switch (cmd.code) {
case 112: {//"悬浮组件开关";
if (cmd.para[0] == "1")
this.addChild(this.uiFac.getFLayer());
else
this.removeChild(this.uiFac.getFLayer());
break;
}
}
}
reset() {
}
}<file_sep>import {Cmd} from "../../data/sotry/Story";
import {Mgr} from "./Mgr";
/**
* Created by ShanFeng on 5/8/2017.
*/
export default class VideoMgr extends Mgr{
exe(cmd: Cmd) {
switch (cmd.code) {
case 600://play
case 601://operate
}
}
}<file_sep>import {Cmd} from "../../data/sotry/Story";
import {IMgr} from "./Mgr";
import SoundManager = laya.media.SoundManager;
import SoundChannel = laya.media.SoundChannel;
/**
* Created by ShanFeng on 5/8/2017.
*/
enum ChannelEnum {bg, fx, vo, bfx}
export default class AudioMgr implements IMgr {
private channels: SoundChannel[] = [];
exe(cmd: Cmd) {
switch (cmd.code) {
case 501://"播放背景音乐"
this.play(ChannelEnum.bg, cmd.para[0], parseInt(cmd.para[1]));
break;
case 502://"播放音效"
this.play(ChannelEnum.fx, cmd.para[0], parseInt(cmd.para[1]));
break;
case 503://"播放语音"
this.play(ChannelEnum.vo, cmd.para[0], parseInt(cmd.para[1]));
break;
case 504://"播放背景音效"
this.play(ChannelEnum.bfx, cmd.para[0], parseInt(cmd.para[1]));
break;
case 505://"淡出背景音乐"
this.fadeOut(ChannelEnum.bg, parseInt(cmd.para[0]));
break;
case 508://"淡出音效"
this.fadeOut(ChannelEnum.fx, parseInt(cmd.para[0]));
break;
case 506://"停止音效"
this.stop(ChannelEnum.fx);
break
case 507://"停止语音"
this.stop(ChannelEnum.vo);
}
}
update(speed: number) {
}
fadeOut(c: ChannelEnum, t: number) {
}
play(c: ChannelEnum, url: string, v: number) {
switch (c) {
case ChannelEnum.bg:
// this.channels[c] = SoundManager.playSound(url);
break;
case ChannelEnum.fx:
// this.channels[c] = SoundManager.playSound(url);
break;
case ChannelEnum.vo:
// this.channels[c] = SoundManager.playSound(url);
break;
case ChannelEnum.bfx:
// this.channels[c] = SoundManager.playSound(url);
}
}
stop(c: ChannelEnum) {
// this.channels[c].stop();
}
pause() {
}
resume() {
}
};
/*
501 播放背景音乐 0:背景音乐的相对路径 1:音量 2:显示信息 3 网盘还是本地
502 播放音效 0:音效的相对路径 1:音量 2:显示信息 3 网盘还是本地
503 播放语音 0:语音的相对路径 1:音量 2:显示信息 3 网盘还是本地
504 播放背景音效 0:背景音效的相对路径 1:音量 2:显示信息 3 网盘还是本地
505 淡出背景音乐 0:时间
506 停止音效 0:空
507 停止语音 0:空
508 淡出音效 0:时间*/
<file_sep>/**
* Created by ShanFeng on 5/15/2017.
*/
export interface ISnape {
}
export default class Snapper {
}<file_sep>import {Cmd} from "../../data/sotry/Story";
/**
* Created by ShanFeng on 5/22/2017.
*/
export interface IMgr {
exe(cmd: Cmd)
update(speed: number): void;
}
export class Mgr implements IMgr {
exe(cmd: Cmd) {
}
update(speed: number): void {
}
}<file_sep>import Graphics = laya.display.Graphics;
import DH from "../../../../../data/DH";
import {Path} from "../../../../../data/sotry/Story";
import Sprite = laya.display.Sprite;
import Event = laya.events.Event;
import Point = laya.maths.Point;
import Handler = laya.utils.Handler;
import Text = laya.display.Text;
/**
* Created by ShanFeng on 5/31/2017.
*/
const GRAPHICS_BG_PATH_SHIFTER = "graphics/background/";
function getBGLink(key: string) {
return DH.instance.getResLink(GRAPHICS_BG_PATH_SHIFTER + key);
}
const UI_PATH_SHIFTER = "graphics/ui/";
export function getUILink(key: string) {
return DH.instance.getResLink(UI_PATH_SHIFTER + key);
}
const OTHER_PATH_SHIFTER = "graphics/other/";
export function getOtherLink(key: string) {
return DH.instance.getResLink(OTHER_PATH_SHIFTER + key);
}
const BUTTON_PATH_SHIFTER = "graphics/button/";
export function getBtnLink(key: string) {
return DH.instance.getResLink(BUTTON_PATH_SHIFTER + key);
}
const GRAPHICS_PATH_SHIFTER = "graphics/";
function getGameImgLink(key: string) {
return DH.instance.getResLink(GRAPHICS_PATH_SHIFTER + key);
}
const AUDIO_BG_PATH_SHIFTER = "audio/bgm/";
function getBGAudioLink(key: string) {
return DH.instance.getResLink(AUDIO_BG_PATH_SHIFTER + key);
}
//todo:移植到GameLayer范畴内
export class GameImg extends Sprite {
tween: [string, number, number, number, number][] = [];
constructor(path: string, other: boolean = false) {
super();
this.loadImage(other ? getOtherLink(path) : getGameImgLink(path));
}
reload(path: string, other: boolean = false) {
this.graphics.clear();
this.loadImage(other ? getOtherLink(path) : getGameImgLink(path), 0, 0, 0, 0, Handler.create(this, this.com));
return this;
}
com(e) {
while (this.graphics.cmds && this.graphics.cmds.length > 1)
this.graphics.cmds.shift();
}
moveTo(property: string, value: number, duration: number, passed: number = 0) {
if (duration <= 1)
this[property] = value;
else
this.tween.push([property, value, duration, passed, this[property]]);
return this;
}
update(s: number = 1) {
if (this.tween.length)
for (let t of this.tween) {
if (s == 0) {
this[t[0]] = t[1];
return this.tween.splice(this.tween.indexOf(t), 1);
}
let p = ++t[3] * s / t[2];
this[t[0]] = t[4] + (t[1] - t[4]) * (p > 1 ? 1 : p);
if (p == 1)
this.tween.splice(this.tween.indexOf(t), 1);
}
}
}
export function getBtnData(idx: number) {
return DH.instance.story.sys.Buttons[idx];
}
export class UIImg extends Sprite {
constructor(path: string, repos = null) {
super();
this.loadImage(getUILink(path), 0, 0, 0, 0, repos);
}
}
export class OtherImg extends Sprite {
constructor(path: string, repos = null) {
super();
this.loadImage(getOtherLink(path), 0, 0, 0, 0, repos);
}
}
export class BGImg extends Sprite {
constructor(path: string) {
super();
this.loadImage(getBGLink(path));
}
}
export class Label extends Sprite {
tf: Text;
constructor(str: string = "") {
super();
this.addChild(this.tf = new Text());
this.tf.text = str;
this.tf.size(20, 20);
}
update(v) {
this.tf.text = DH.instance.replaceVTX(v);
}
}
export class Button extends Sprite {
private _toggled: boolean;
i1: Graphics;
i2: Graphics;
idx: number;
constructor(idx: number, private cHandler = null, private repos = null, private toggle: boolean = false) {
super();
this.init(getBtnData(idx));
//todo:体验纠结
this.mouseThrough = true;
}
init({name, image1, image2, x, y}) {
this.name = name;
//如果图一为空则互换图一图二
if (image1.path.length == 0) {
image1 = image2;
image2.path = '';
}
if (image1.path.length) {
this.graphics = this.i1 = new Graphics();
this.i1.loadImage(getBtnLink(image1.path), 0, 0, 0, 0, this.completeHandler);
}
if (image2.path.length) {
this.i2 = new Graphics();
this.i2.loadImage(getBtnLink(image2.path));
}
this.x = x;
this.y = y;
this.on(Event.CLICK, this, this.click);
if (!this.toggle) {
this.on(Event.MOUSE_OVER, this, this.switchImg);
this.on(Event.MOUSE_OUT, this, this.restoreImg);
}
}
update(idx) {
this.reInit(getBtnData(idx - 1));
}
private reInit({name, image1, image2, x, y}) {
this.name = name;
//如果图一为空则互换图一图二
if (image1.path.length == 0) {
image1 = image2;
image2.path = '';
}
if (image1.path.length) {
this.graphics = this.i1 = new Graphics();
this.i1.loadImage(getBtnLink(image1.path), 0, 0, 0, 0, this.completeHandler);
}
if (image2.path.length) {
this.i2 = new Graphics();
this.i2.loadImage(getBtnLink(image2.path));
} else
this.i2 = null;
}
completeHandler(e) {
this.size(e.width, e.height);
if (this.repos)
this.repos(e);
}
get toggled(): boolean {
return this._toggled;
}
set toggled(value: boolean) {
this._toggled = value;
this.alpha = value ? .2 : 1;
}
private click(e: Event) {
if (this.toggle) {
this.toggled = !this._toggled;
}
if (this.cHandler)
this.cHandler.call(null, e);
// else
// console.log(this.name, "clicked");
}
private switchImg(e: Event) {
if (this.i2)
this.graphics = this.i2;
else {
this.alpha = .2;
}
}
private restoreImg(e: Event) {
if (this.i2)
this.graphics = this.i1;
else {
this.alpha = 1;
}
}
}
export class Slider extends Sprite {
private bar: UIImg;
private barMask: Sprite;
constructor(bg: Path, fg: Path) {
super();
this.constructView(bg, fg);
}
private constructView(bg: Path, fg: Path) {
this.addChild(new UIImg(bg.path));
this.barMask = new Sprite();
this.bar = new UIImg(fg.path, Handler.create(this, this.initMask, null, true));
this.bar.on(Event.MOUSE_DOWN, this, this.mdHandler);
this.bar.on(Event.MOUSE_UP, this, this.muHandler);
this.stage.on(Event.MOUSE_UP, this, this.muHandler);
this.stage.on(Event.MOUSE_OUT, this, this.muHandler);
}
private initMask(tex) {
this.barMask.graphics.drawRect(0, 0, tex.width, tex.height, "#FFFFFF");
this.barMask.x = -50;
this.barMask.width = tex.width;
this.bar.mask = this.barMask;
this.addChild(this.bar);
}
private mdHandler(e: Event) {
// this.on(Event.MOUSE_MOVE, this, this.changeHandler);
this.stage.on(Event.MOUSE_MOVE, this, this.changeHandler);
this.changeHandler(e);
}
private muHandler(e: Event) {
// this.off(Event.MOUSE_MOVE, this, this.changeHandler);
this.stage.off(Event.MOUSE_MOVE, this, this.changeHandler);
}
private changeHandler(e: Event): void {
let v: number;
let mX: number = this.globalToLocal(new Point(e.stageX, e.stageY)).x;
//取值的最大范围
let max: number = this.bar.x + this.bar.width;
//取值的最小范围
let min: number = this.bar.x;
if (mX > min && mX < max) {
this.barMask.x = mX - this.barMask.width;
v = (this.barMask.x + this.barMask.width) / (this.bar.width);
} else if (mX <= min) {
this.barMask.x = -this.barMask.width;
v = 0;
} else if (mX >= max) {
this.barMask.x = this.bar.x;
v = 1;
}
this.event(Event.CHANGE, v);
}
/**
* 设置位置,0~1
* @param v
*/
public setValue(v: number) {
this.barMask.x = this.bar.width * v - this.barMask.width;
}
}<file_sep>import Conf from "../Conf";
import DH from "../DH";
import Color = laya.utils.Color
/**
* Created by ShanFeng on 4/10/2017.
*/
interface Header {
ver?: number
gWidth?: number
gHeight?: number
mPWid?: number
mPHei?: number
gUid?: string
title?: string
gVer?: number
crc32?: number
}
export interface Path {
from: number
path: string
}
export interface IdxBtn {
idx: number
x: number
y: number
}
export interface ImgBtn {
name: string
image1: Path
image2: Path
x: number
y: number
}
export interface Music {
path: Path
vol: number
}
export interface Title {
showLog: boolean
logoImage: Path
titleImage: Path
drawTitle: boolean
bgm: Music
buttons: IdxBtn[]
}
export interface GameMenu {
bgImg: Path
buttons: IdxBtn[]
}
export interface CGItem {
name: string
path: Path
msg: string
}
export interface VPRect {
x: number
y: number
w: number
h: number
}
export interface CG {
bgImg: Path
column: number
spanRow: number
spanCol: number
showMsg: Boolean
msgX: number
msgY: number
zoom: number
cgx: number
cgy: number
noPic: Path
CGList: CGItem[]
vpRect: VPRect
backButton: IdxBtn
closeButton: IdxBtn
}
export interface BGMItem {
name: string
bgmPath: Path
picPath: Path
msg: string
}
export interface BGM {
bgImg: Path
column: number
spanRow: number
spanCol: number
showPic: boolean
showMsg: boolean
px: number
py: number
mx: number
my: number
nx: number
ny: number
noName: string
noPic: Path
bgmList: BGMItem[]
vpRect: VPRect
selectButton: IdxBtn
closeButton: IdxBtn
}
export interface SaveData {
showMapName: boolean
showDate: boolean
bgImg: Path
max: number
column: number
spanRow: number
spanCol: number
showMinPic: boolean
nameX: number
nameY: number
dateX: number
dateY: number
picX: number
picY: number
zoom: number
vpRect: VPRect
backButton: IdxBtn
closeButton: IdxBtn
}
export interface MsgBox {
faceStyle: number
choiceButtonIndex: number
talk: TalkWin
name: NameWin
}
export interface TalkWin {
backX?: number
backY?: number
bgImg?: Path
FaceBorderImage?: Path
FaceBorderX?: number
FaceBorderY?: number
textX?: number
textY?: number
buttons?: IdxBtn[]
}
export interface NameWin {
backX: number
backY: number
bgImg: Path
isCenter: boolean
textX: number
textY: number
}
export interface Replay {
bgImg: Path
closeButton: IdxBtn
vpRect: VPRect
}
export interface Setting {
bgImg: Path
barNone: Path
barMove: Path
BgmX: number
BgmY: number
SeX: number
SeY: number
VoiceX: number
VoiceY: number
ShowFull: boolean
ShowAuto: boolean
ShowBGM: boolean
ShowSE: boolean
ShowVoice: boolean
ShowTitle: boolean
closeButton: IdxBtn
fullButton: IdxBtn
winButton: IdxBtn
AutoOn: IdxBtn
AutoOff: IdxBtn
TitleButton: IdxBtn
}
export interface CusUI {
loadEvent: Cmd[]
afterEvent: Cmd[]
controls: CusUIItem[]
showEffect: number
isMouseExit: boolean
isKeyExit: boolean
}
export interface CusUIItem {
cmdArr: Array<Cmd>
type: number
useStr: boolean
image1: string
image2: string
strIdx: number
useVar: boolean
x: number
y: number
useIdx: boolean
index: number
maxIdx: number
color: Color
}
export interface DFLayer {
cmdArr: Cmd[]
x: number
y: number
name: string
itemArr: DFLayerItem[]
}
export interface DFLayerItem {
type: number
x: number
y: number
image: string
useStr: boolean
idxOfStr: number
strIdx: number
varIdx: number
color: Color
}
export interface Cmd {
code: number
//trashy idt: number
para: string[]
links?: number[]
}
export class DChapter {
name: string;
id: number;
cmdArr: Cmd[];
constructor({name, id, cmdArr}) {
this.name = name;
this.id = id;
this.cmdArr = cmdArr;
}
}
export default class Story {
name: string;
id: number;
header: Header = {};
sys: any = {};
fLayerArr: DFLayer[];
dChapterArr: DChapter[];
gotoChapter(id: number) {
if (Conf.info.single) {
for (let c of this.dChapterArr) {
if (c.id == id) {
DH.instance.eventPoxy.event(Conf.PLAY_CHAPTER, {
name: c.name,
id: c.id,
cmdArr: c.cmdArr.concat()
});
}
}
} else {
DH.instance.binLoader.loadChapter(id);
}
}
};<file_sep>/**
* Created by ShanFeng on 5/29/2017.
*/
import {BGM, CG, CUI, Game, Menu, Replay, Restore, Save, Setting, Title} from "./comp/Menu";
import DH from "../../../../data/DH";
import {BtnSelector, Selector, SelectorEx, SelectorEx2} from "./comp/Selector";
import {Cmd} from "../../../../data/sotry/Story";
import {MSG} from "./comp/MSG";
import FLayer from "./comp/FLayer";
import {HotareaSelector} from "./comp/Hotarea";
export enum MenuEnum {title, game, replay, CG, BGM, save, restore, setting}
export default class UIFac {
private fLayer: FLayer;
private msg: MSG;
private hotarea: HotareaSelector;
private dh: DH = DH.instance;
private menuArr: Menu[] = [];
getMenu(type: number) {
if (this.menuArr[type] && type < 10000) {
return (<CUI>this.menuArr[type]).exeLoadChapter();
} else
return this.menuArr[type] || this.constructMenu(type);
}
private constructMenu(type: number): Menu {
let m: Menu;
switch (type) {
case -1 :
m = new Title(type, this.dh.story.sys.title);
break;
case 10001://游戏菜单
m = new Game(type, this.dh.story.sys.gMenu);
break;
case 10002://剧情回放
m = new Replay(type, this.dh.story.sys.Replay);
break;
case 10003://CG
m = new CG(type, this.dh.story.sys.CG);
break;
case 10004://BGM
m = new BGM(type, this.dh.story.sys.BGM);
break;
case 10005://存档
m = new Save(type, this.dh.story.sys.SaveData);
case 10006://读档
m = new Restore(type, this.dh.story.sys.SaveData);
break;
case 10007://环境设置
m = new Setting(type, this.dh.story.sys.Setting);
break;
// case 10008://离开游戏 ignore
// break;
// case 10009://自动剧情 移入UILayer
// break;
case 10010://新版商城
break;
default: {
m = new CUI(type, this.dh.story.sys.Cuis[type]);
}
}
return this.menuArr[type] = m;
}
getSelector(cmd: Cmd): Selector {
switch (cmd.code) {
case 101:
return new Selector(cmd);
case 1010:
return new SelectorEx(cmd);
case 1011:
return new SelectorEx2(cmd);
case 204:
return new BtnSelector(cmd);
}
}
getMSG(cmd: Cmd): MSG {
return this.msg ? this.msg.update(cmd) : this.msg = new MSG(cmd);
}
getFLayer() {
return this.fLayer ? this.fLayer : this.fLayer = new FLayer(this.dh.story.fLayerArr);
}
getHotarea() {
return this.hotarea ? this.hotarea : this.hotarea = new HotareaSelector();
}
}<file_sep>import CmdList from "../cmd/CmdList";
import {StateEnum} from "../state/State";
import {Cmd} from "../../data/sotry/Story";
/**
* Created by ShanFeng on 6/27/2017.
*/
export default class Reportor {
showState: boolean = false;
showProcess: boolean = false;
frame: number = 0;
cmdList: CmdList = new CmdList();
constructor() {
}
logProcess(cmd, cc) {
if (this.showProcess)
console.log(cmd.code, "@:" + cc, this.cmdList.get(cmd.code) + this.cmdList.getDetails(cmd));
}
logFrame() {
if (this.showProcess)
console.log("frame:", this.frame++);
}
logRestore(snap) {
console.log("restore to ", snap);
}
logState(idx: StateEnum) {
if (this.showState)
console.log("switch state to:", StateEnum[idx]);
}
printCmdArr(cmdArr: Cmd[]) {
//for dynamic usage
/*if (this.cmdList == null)
require(["js/mod/cmd/CmdList.js"], (CmdList) => {
this.cmdList = new CmdList.default();
for (let s of this.sceneArr)
this.cmdList.printChapter(s, this.sceneArr);
});*/
this.cmdList.printCmdArr(cmdArr);
}
}<file_sep>/**
* Created by ShanFeng on 5/9/2017.
*/
import DH from "../../data/DH";
import Conf from "../../data/Conf";
import {IMgr} from "../Mgr/Mgr";
import {MgrEnum} from "../CmdLine";
import Browser = laya.utils.Browser;
export enum StateEnum {Play, Auto, FF, Pause, Frozen, FrozenAll}
export interface IState {
id: StateEnum
wait(dur: number);
update(...mgrs: IMgr[]): void;
resume();
}
class State implements IState {
id: StateEnum;
protected left: number = 0;
protected uc: number = 0;//update counter
/**动画刷新倍率,用以降低刷新率**/
protected us: number = Browser.onPC ? 1 : 2;//update speed
update(...mgrs: IMgr[]): void {
if (this.left > 0)
if (--this.left == 0)
DH.instance.eventPoxy.event(Conf.ITEM_CHOSEN);
if (++this.uc % this.us == 0)
for (let m of mgrs)
m.update(this.uc = this.us);
}
wait(dur) {
this.left = dur;
}
resume() {
DH.instance.eventPoxy.event(Conf.CMD_LINE_RESUME);
}
}
export class PlayState extends State {
id = StateEnum.Play;
wait(dur) {
}
}
export class PauseState extends State {
id = StateEnum.Pause;
resume() {
}
}
export class AutoState extends State {
id = StateEnum.Auto;
delay = 60;
}
export class FFState extends State {
id = StateEnum.FF;
update(...mgrs: IMgr[]): void {
if (this.left > 0) {
this.left = 0;
this.resume();
}
for (let m of mgrs)
m.update(0);
}
wait(dur) {
}
}
export class Frozen extends State {
id = StateEnum.Frozen;
update(...mgrs): void {
}
}
export class FrozenAll extends State {
id = StateEnum.FrozenAll;
update(...mgrs): void {
if (this.left > 0)
if (--this.left == 0)
DH.instance.eventPoxy.event(Conf.STATE_FROZEN);
}
resume(): any {
}
}
export class StateMgr {
private forcePause: boolean = true;
private dh: DH = DH.instance;
private append: any[] = [];
private states: IState[] = [new PlayState(), new AutoState(), new FFState(), new PauseState(), new Frozen(), new FrozenAll()];
private curState: IState;
constructor() {
this.dh.eventPoxy.on(Conf.STATE_AUTO, this, this.auto);
this.dh.eventPoxy.on(Conf.STATE_FF, this, this.fast);
this.dh.eventPoxy.on(Conf.STATE_CANCEL, this, this.cancel);
this.dh.eventPoxy.on(Conf.STAGE_BLUR, this, this.cancel);
this.dh.eventPoxy.on(Conf.ITEM_CHOSEN, this, this.play, [true]);
this.dh.eventPoxy.on(Conf.STATE_FROZEN, this, this.frozen);
Laya.timer.frameLoop(1, this, this.tick);
this.curState = this.states[StateEnum.Pause];
}
private tick() {
this.dh.reporter.logFrame();//test only
this.dh.cmdLine.mgrArr[MgrEnum.audio].update(1);
this.curState.update(this.dh.cmdLine.mgrArr[MgrEnum.view]);
this.curState.resume();
}
get id() {
return this.curState.id;
}
mark(snap) {
if (snap)
this.append.push(snap.concat(this.curState.id == StateEnum.FF ? StateEnum.Play : this.curState.id));
else if (this.append.length)
this.append = [];
}
restore(): boolean {
this.pause(0, true);
let snap = this.append.pop();
if (snap) {
this.dh.reporter.logRestore(snap);//test only
this.dh.eventPoxy.event(Conf.RESTORE, [snap]);
return true;
}
else
return false;
}
switchState(idx: StateEnum) {
if (this.curState.id != idx) {
this.curState = this.states[idx];
this.dh.reporter.logState(idx);//test only
}
}
play(v: boolean | number = null) {
if (v != null) {
this.forcePause = false;
this.switchState(StateEnum.Play);
} else if (!this.forcePause && this.curState.id != StateEnum.FF)
this.switchState(StateEnum.Play);
}
auto() {
this.switchState(StateEnum.Auto);
}
fast() {
if (!this.forcePause) {
if (this.curState.id == StateEnum.Pause)
this.curState.wait(0);
this.switchState(StateEnum.FF);
}
}
pause(dur: number = 0, force: boolean = false) {
if (force) {
this.forcePause = force;
this.switchState(StateEnum.Pause);
if (dur > 0)
this.curState.wait(dur);
} else if (this.curState.id != StateEnum.FF) {
this.switchState(this.curState.id == StateEnum.Frozen ? StateEnum.FrozenAll : StateEnum.Pause);
if (dur > 0)
this.curState.wait(dur);
}
}
frozen() {
this.forcePause = true;
this.switchState(StateEnum.Frozen);
}
frozenAll() {
this.forcePause = true;
this.switchState(StateEnum.FrozenAll);
}
cancel() {
if (this.curState.id == StateEnum.FF)
this.switchState(StateEnum.Play);
}
}<file_sep>import {Cmd, TalkWin} from "../../../../../data/sotry/Story";
import DH from "../../../../../data/DH";
import {UIImg} from "./Comp";
import Layouter from "./Layouter";
import Conf from "../../../../../data/Conf";
import Sprite = laya.display.Sprite;
import Text = laya.display.Text;
import Event = laya.events.Event;
/**
* Created by ShanFeng on 6/5/2017.
*/
export enum SpeedEnum {Slow, Normal, Fast}
export class MSG extends Sprite {
bgImg: UIImg;
txt: Text = new Text();
dur = [60, 90, 120];
constructor(private cmd: Cmd) {
super();
this.initView();
}
private initView() {
this.size(Laya.stage.width, Laya.stage.height);
DH.instance.story.sys.MessageBox.name;
DH.instance.story.sys.MessageBox.faceStyle;
this.constructTalk(DH.instance.story.sys.MessageBox.talk);
}
constructTalk(tw: TalkWin) {
//bg
if (tw.bgImg) {
this.bgImg = new UIImg(tw.bgImg.path);
this.addChild(this.bgImg);
//text
this.txt = new Text();
this.txt.fontSize = 22;
this.txt.color = "#";
let vArr: string[] = this.cmd.para[1].split(',');
while (vArr.length > 0) {
this.txt.color += parseInt(vArr.shift()).toString(16);
}
this.txt.text = DH.instance.replaceVTX(this.cmd.para[2]);
switch (this.cmd.para[5]) {
case "0":
Layouter.top(this.bgImg);
break;
case "1":
Layouter.center(this.bgImg);
break;
case "2":
Layouter.bottom(this.bgImg);
}
this.txt.x = tw.textX;
this.txt.y = tw.textY;
this.bgImg.addChild(this.txt);
this.once(Event.MOUSE_DOWN, this, this.clickHandler);
}
}
protected clickHandler(e: Event) {
if (this.parent && this.parent.numChildren < 3) {//过滤selector
this.parent.removeChild(this);
DH.instance.eventPoxy.event(Conf.ITEM_CHOSEN);
}
}
/**
* 0:角色名称
* 1:角色名称的颜色
* 2:文本内容
* 3:头像
* 4:头像位置 0左 1右
* 5:文本位置(0上,1中,2下)
* 6:语速(0"极快", 1"很快", 2"一般", 3"较慢", 4"极慢")
* 7:是否显示对话框 0不显示 1显示
* 8:头像来源(网盘还是本地
* 9:对齐方式(0"居左", 1"居中", 2"居右")
* 10:描边大小(0"无", 1"细,1像素", 2"中,3像素", 3"粗,5像素")
* 11:描边颜色
* 12:投影大小(0到5像素)
* 13:投影角度(0到360)
* 14:投影距离(0到5像素)
* 15:投影颜色(RGB)
* 16:额外内容(0关闭1开启,多项间|分隔,每项间,分隔)背景图更换开关,背景图 | 是否自定义XY,X,Y | 强调说话人开关,图层编号,类型 | 双重对话,上或下,点后是否消失
* 17:电影字幕效果 (0关闭1开启,多项间|分隔,每项间,分隔)是否开启 |帧数|起始相对位置类型X,Y(0左(上) 1中 2右(下))|终止相对位置类型X,Y(同前)|起始位置X,Y|终点位置X,Y
* @param cmd
* @returns {MSG}
*/
update(cmd: Cmd) {
this.once(Event.MOUSE_DOWN, this, this.clickHandler);
this.txt.text = DH.instance.replaceVTX(cmd.para[2]);
return this;
}
}
// 0:""
// 1:"255,255,255"
// 2:"\c[0,0,0]\t[4]"
// 3:""
// 4:"1"
// 5:"2"
// 6:"0"
// 7:"0"
// 8:"2"
// 9:"0"
// 10:"0"
// 11:"0,0,0"
// 12:"0"
// 13:"0"
// 14:"0"
// 15:"0,0,0"
// 16:"0,0|1,170,190|0,无,0|0,0,0"
// 17:"0|"<file_sep>/**
* Created by ShanFeng on 6/20/2017.
*/
import DH from "../../../../../data/DH";
import {Cmd} from "../../../../../data/sotry/Story";
import Sprite = laya.display.Sprite;
import Rectangle = laya.maths.Rectangle;
import Event = laya.events.Event;
export class HotareaSelector {
refresh: boolean;
private hotRec: Rectangle;
private hit: [number, number, string];
constructor() {
this.initView();
}
initView() {
this.hotRec = new Rectangle();
Laya.stage.on(Event.MOUSE_MOVE, this, this.mHandler);
Laya.stage.on(Event.MOUSE_DOWN, this, this.mHandler);
Laya.stage.on(Event.MOUSE_UP, this, this.muHandler);
}
protected mHandler(e: Event) {
this.hit = [e.stageX, e.stageY, e.type];
}
protected muHandler(e: Event) {
this.hit = null;
}
check(cmd: Cmd) {
let rec = cmd.para[2].split(",");
if (rec.length > 1) {
this.hotRec.x = parseInt(rec[0]);
this.hotRec.y = parseInt(rec[1]);
this.hotRec.width = parseInt(rec[2]);
this.hotRec.height = parseInt(rec[3]);
} else {
let img = DH.instance.imgDic.get(rec[0]);
if (img) {
this.hotRec.x = img.x;
this.hotRec.y = img.y;
this.hotRec.width = img.width;
this.hotRec.height = img.height;
} else {
this.hotRec.width = this.hotRec.height = 0;
}
}
let bingo = this.hotRec && this.hit && this.hotRec.contains(this.hit[0], this.hit[1]);
if (bingo) {
if (cmd.para[3] == "0")
bingo = this.hit[2] == Event.MOUSE_MOVE;
else
bingo = this.hit[2] == Event.MOUSE_DOWN;
}
return bingo;
}
}<file_sep>/**
* Created by ShanFeng on 6/23/2017.
*/
(function (win, doc, nav) {
/**
* @des 浏览器判断脚本,兼容cmd规范
*/
var ua = nav.userAgent.toLowerCase(), key =
{
ie: "msie",
sf: "safari",
tt: "tencenttraveler"
},
// 正则列表
reg =
{
browser: "(" + key.ie + "|" + key.sf + "|firefox|chrome|opera)",
shell: "(maxthon|360se|360chrome|theworld|se|theworld|greenbrowser|qqbrowser|lbbrowser|bidubrowser)",
tt: "(tencenttraveler)",
os: "(windows nt|macintosh|solaris|linux)",
kernel: "(webkit|gecko|like gecko)"
}, System =
{
"5.0": "Win2000",
"5.1": "WinXP",
"5.2": "Win2003",
"6.0": "WinVista",
"6.1": "Win7",
"6.2": "Win8",
"6.3": "Win8.1"
}, chrome = null, is360Chrome = null, // 360浏览器
is360se = null, // 360级速浏览器
// 特殊浏览器检测
is360 = (function () {
// 高速模式
var result = ua.indexOf("360chrome") > -1 ? !!1 : !1, s;
// 普通模式
try {
if (win.external && win.external.twGetRunPath) {
s = win.external.twGetRunPath;
if (s && s.indexOf("360se") > -1) {
result = !!1;
}
}
}
catch (e) {
result = !1;
}
return result;
})(),
// 判断百度浏览器
isBaidu = (function () {
return ua.indexOf('bidubrowser') > -1 ? !!1 : !1;
})(),
// 判断百度影音浏览器
isBaiduPlayer = (function () {
return ua.indexOf('biduplayer') > -1 ? !!1 : !1;
})(),
// 判断爱帆avant浏览器
isAvant = (function () {
return ua.indexOf('爱帆') > -1 ? !!1 : !1;
})(), isLiebao = (function () {
return ua.indexOf('lbbrowser') > -1 ? !!1 : !1;
})(),
// 特殊检测maxthon返回版本号
maxthonVer = function () {
try {
if (/(\d+\.\d)/.test(win.external.max_version)) {
return parseFloat(RegExp['\x241']);
}
}
catch (e) {
}
}(), browser = getBrowser(), shell = uaMatch(reg.shell), os = uaMatch(reg.os), kernel = uaMatch(reg.kernel);
// ie11
function getBrowser() {
// 检测是否是ie内核 是否是ie10 标识
if ((!!win.ActiveXObject || "ActiveXObject" in win)
&& (ua.match(/.net clr/gi) && ua.match(/rv:(\w+\.\w+)/gi))) {
return [
"msie", ua.match(/rv:(\w+\.\w+)/gi)[0].split(":")[1]
];
}
return uaMatch(reg.browser);
}
/**
* 对ua字符串进行匹配处理
*
* @param {string}
* str 要处理的字符串
* @return {array} 返回处理后的数组
*/
function uaMatch(str) {
var reg = new RegExp(str + "\\b[ \\/]?([\\w\\.]*)", "i"), result = ua.match(reg);
return result ? result.slice(1) : ["", ""];
}
function detect360chrome() {
return 'track' in document.createElement('track') && 'scoped' in document.createElement('style');
}
function isHao123() {
return !!(window.external && window.external.ExtGetAppPath && window.external.ExtGetAppPath());
}
function isIpad() {
return ua.indexOf("ipad") > -1 || ua.indexOf("iphone") > -1;
}
function canvasSupport() {
return !!document.createElement('canvas').getContext;
}
// 保存浏览器信息
if (browser[0] === key.ie) {
if (is360) {
shell = [
"360se", ""
];
}
else if (maxthonVer) {
shell = [
"maxthon", maxthonVer
];
}
else if (shell == ",") {
shell = uaMatch(reg.tt);
}
}
else if (browser[0] === key.sf) {
browser[1] = uaMatch("version") + "." + browser[1];
}
chrome = (browser[0] == "chrome") && browser[1];
// 如果是chrome浏览器,进一步判断是否是360浏览器
if (chrome) {
if (detect360chrome()) {
if ('v8Locale' in window) {
is360Chrome = true;
}
else {
is360se = true;
}
}
}
/*
* 获取操作系统
*/
function getSystem() {
var plat = navigator.platform, isWin = (plat == "Win32") || (plat == "Windows") || (plat == "Win64"),
isMac = (plat == "Mac68K")
|| (plat == "MacPPC") || (plat == "Macintosh") || (plat == "MacIntel");
if (isMac) {
return "Mac";
}
var isUnix = (plat == "X11") && !isWin && !isMac;
if (isUnix) {
return "Unix";
}
var isLinux = (String(plat).indexOf("Linux") > -1);
if (isLinux) {
return "Linux";
}
if (isWin) {
return System[os[1]] || "other";
}
return "other";
}
// 遵循cmd规范,输出浏览器、系统等响应参数
window.exports =
{
cookieEnabled: navigator.cookieEnabled,
isStrict: (doc.compatMode == "CSS1Compat"),
isShell: !!shell[0],
shell: shell,
kernel: kernel,
platform: os,
types: browser,
chrome: chrome,
system: getSystem(),
firefox: (browser[0] == "firefox") && browser[1],
ie: (browser[0] == "msie") && browser[1],
opera: (browser[0] == "opera") && browser[1],
safari: (browser[0] == "safari") && browser[1],
maxthon: (shell[0] == "maxthon") && shell[1],
isTT: (shell[0] == "tencenttraveler") && shell[1],
is360: is360,
is360Chrome: is360Chrome, // 是否是chrome内核的360浏览器
is360se: is360se, // 是否是chrome内核的360极速浏览器
isBaidu: isBaidu,
isHao123: isHao123, // 判断hao123浏览器
isLiebao: isLiebao,
isSougou: (shell[0] == "se"),
isQQ: shell[0] == "qqbrowser",
isIpad: isIpad,
version: '',
noDl: isBaidu || isAvant || isBaiduPlayer, // 浏览器下载入口需排除的浏览器
canvasSupport: canvasSupport() // 是否支持canvas
};
})(window, document, navigator);<file_sep>import Conf from "../../data/Conf";
/**
* Created by ShanFeng on 6/27/2017.
*/
export default class ReportorBase {
constructor() {
if (!Conf.debug)
this.addInterruptor();
}
addInterruptor() {
window.onerror = function (m, f, l, c, e) {
// let eInfo = {
// msg: m,
// file: f,
// line: l,
// column: c,
// error: JSON.stringify(e),
// gIndex: GloableData.getInstance().gameInfo.gIndex,
// guid: GloableData.getInstance().gameMainData.Headr.guid,
// sid: GloableData.getInstance().iMain.storyId,
// pos: GloableData.getInstance().iMain.pos,
// plat: plat
// };
//
// let DataTime = new Date().getTime() / 1000;
// let uploadData = {
// sn: '9',
// sv: '1',
// ei: JSON.stringify(eInfo),
// rt: '1',
// sign: DataTime
};
// AjaxManager.getInstance().sendAjaxPost("http://support.66rpg.com/report/bug", uploadData, this, null);
// // HttpManager.getInstance().sendPostRequest("http://support.66rpg.com/report/bug", uploadData, null, "json", null);
// }
// }
Laya.Browser.onMobile;
/**
* "Win32"
* "Win64"
*/
navigator.platform;
/**
* chrome:"Google Inc.
* FF:""
* IE:""
* safari:"Apple Computer, Inc."
*/
navigator.vendor;
/**
* chrome/FF/IE/safari:"Mozilla"
*/
navigator.appCodeName;
/**
* chrome/FF/safari:"Netscape"
* IE:"Microsoft Internet Explorer"
*/
navigator.appName;
/**
* chrome:"5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3138.0 Safari/537.36"
* FF:"5.0 (Windows)"
* IE:"4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; InfoPath.3)"
* safari:"5.0 (Windows NT 6.2; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2"
*/
navigator.appVersion;
/**
* kw: "Chrome"
* chrome:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3138.0 Safari/537.36'
* kw: "Firefox"
* FF:"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0"
* kw: "MSIE"
* IE:"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; InfoPath.3)"
* kw: "Safari"
* safari:"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2"
*/
navigator.userAgent;
Conf.frameworks.ver;
Conf.info.ver;
Conf.info.gid;
}
}
//"para0|para1|para2|..."
// 错误日志分析:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//o 客户端类型 :采用英文编码,编码定好后,告知我
//o 操作系统
//o 客户端版本号
//x 设备型号
//x 设备ID
//x 浏览器版本
//o 错误类别:崩溃,错误
//o 堆栈
//x 内存总量
//x 内存可用量
//o 用户ID @ external @@ window["commonPlayer"]
//o 游戏ID @ gIndex
//o 时间
//
//
// 程序启动信息:~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//o 客户端类型
//o 操作系统
//o 客户端版本号
//ox 设备型号
//x 浏览器版本
//x 客户端IP
//x 设备ID
//o 时间
// /** 浏览器代理信息。*/
// static userAgent: string;
// /** 表示是否在 ios 设备。*/
// static onIOS: boolean;
// /** 表示是否在移动设备。*/
// static onMobile: boolean;
// /** 表示是否在 iphone设备。*/
// static onIPhone: boolean;
// /** 表示是否在 ipad 设备。*/
// static onIPad: boolean;
// /** 表示是否在 andriod设备。*/
// static onAndriod: boolean;
// /** 表示是否在 Windows Phone 设备。*/
// static onWP: boolean;
// /** 表示是否在 QQ 浏览器。*/
// static onQQBrowser: boolean;
// /** 表示是否在移动端 QQ 或 QQ 浏览器。*/
// static onMQQBrowser: boolean;
// /** 表示是否在移动端 Safari。*/
// static onSafari: boolean;
// /** 微信内*/
// static onWeiXin: boolean;
// /** 表示是否在 PC 端。*/
// static onPC: boolean;
<file_sep>/**
* Created by Lonmee on 4/19/2017.
*/
import {BinLoader} from "./mod/loader/BinLoader";
import Conf from "./data/Conf";
import DH from "./data/DH";
import CmdLine from "./mod/CmdLine";
import Browser = laya.utils.Browser;
import WebGL = laya.webgl.WebGL;
import Reportor from "./mod/reporter/Reporter";
export class OPlayer {
constructor() {
}
init(gid: string, ver: number, m: string, s: string,
qlty: string, path: string, gs: string, gi: string, pf: string) {
Conf.info.gid = gid;
Conf.info.ver = ver;
Conf.info.qlty = qlty;
Conf.info.miniPath = path;
Laya.init(Laya.Browser.width, Laya.Browser.height, WebGL);
DH.instance.reporter = new Reportor();
DH.instance.cmdLine = new CmdLine();
// DH.instance.binLoader = new BinLoader();
DH.instance.binLoader = new BinLoader(true);
}
}
Browser.window.oplayer = new OPlayer();
if (Conf.debug) {//注册到window
Browser.window.conf = Conf;
Browser.window.dh = DH.instance;
}
//console.log('%c this is color! ', 'background: #222; color: #bada55');
//todo:import//region improved @laya.core.js:2745
/*if (isHit = sp.getGraphicBounds().contains(mouseX, mouseY)) {
rgba = sp.graphics._one[0].getPixels(mouseX, mouseY, 1, 1);
alpha = rgba.pop();
pure = rgba.every(function (v){return v == 255}) || rgba.every(function (v){return v == 0});
isHit = !(alpha < 5 && pure);
}*/
//endregion
//todo:waiting
// webgl将影响"submit.shaderValue.color=shader.fillStyle._color._color;"@laya.core.js:4158<file_sep>import {Cmd} from "../../data/sotry/Story";
import {DigitalDic, StringDic} from "./value/ODictionary";
import DH from "../../data/DH";
import {Mgr} from "./Mgr";
import Dictionary = laya.utils.Dictionary;
/**
* Created by ShanFeng on 5/8/2017.
* 尊重用户主逻辑,各数值从1开始
*/
export default class ValueMgr extends Mgr {
vDic = new DigitalDic();
sDic = new StringDic();
exVDic = new DigitalDic();
constructor() {
super();
DH.instance.vDic = this.vDic;
DH.instance.sDic = this.sDic;
DH.instance.exVDic = this.exVDic;
}
exe(cmd: Cmd) {
switch (cmd.code) {
// case 105://"数值输入"//ignore
// 0:数值索引
// 1:数值名称
// 2:显示信息
// break;
// case 150: //"刷新UI画面"
case 218: //"强制存档读档"
//todo:强制
break;
case 207://"数值操作"
//0:数值索引
// 1:操作符id(=,+=,-=,*=,/=,%=)
// 2:操作数为常量(0)、其他数值(1)、随机数(2)、二周目变量(3)、索引变量(4)、服务器时间变量(5)、任务(9)、本地时间变量(10)
// 3:值
// 4:显示信息
// 5:数值(0)或索引(1)
case 213://"二周目变量"
//0:同207数值操作
let v1 = cmd.para[1] == "0" ? 0 : cmd.para[5] == "0" ? this.digByTag(cmd.para[0]) : this.digByType("4", cmd.para[0]);
let v2 = this.digByType(cmd.para[2], cmd.para[3], cmd.para[4]);
if (cmd.code == 207)
this.vDic.set(cmd.para[5] == "0" ? cmd.para[0] : this.vDic.get(cmd.para[0]) - 1, this.calc(v1, v2, cmd.para[1]));
else
this.exVDic.set(cmd.para[5] == "0" ? cmd.para[0] : this.vDic.get(cmd.para[0]) - 1, this.calc(v1, v2, cmd.para[1]));
break;
case 215://"字符串"
//0: 字符串索引 1:字符串内容
this.sDic.set(cmd.para[0], cmd.para[1]);
break;
case 216://"高级数值操作"
// 0:数值索引(二周目为: EX|数值索引)
// 1:操作符id(=,+=,-=,*=,/=,%=)(0,1,2,3,4,5)
// 2:操作数为常量(0)、其他数值(1)、随机数(2)、二周目变量(3)、索引变量(4)、服务器时间变量(5)、 鲜花数(6)、最大值(7)、最小值(8)、任务(9)、本地时间变量(10)
// 3:值或最大、小值 [n|固定数,v(数值)|1(索引位置),x(二周目数值)|1,s|索引数值]
// 4:显示信息
// 5:数值(0)或索引(1)
// 【6:操作index(+,-,*,/,%)(0,1,2,3,4) (若为-1后面忽略 7同2 8同3】
v1 = cmd.para[1] == "0" ? 0 : cmd.para[5] == "0" ? this.digByTag(cmd.para[0]) :
this.parsePara(cmd.para[0], 0) == "EX" ? this.digByType("11", cmd.para[0]) : this.digByType("4", cmd.para[0]);
v2 = this.digByType(cmd.para[2], cmd.para[3]);
//更多操作
if (cmd.para[6] != "-1") {
v2 = this.calc(v2, this.digByType(cmd.para[7], cmd.para[8]), (parseInt(cmd.para[6]) + 1).toString());
}
if (this.parsePara(cmd.para[0], 0) == "EX")
this.exVDic.set(cmd.para[5] == "0" ? cmd.para[0] : this.vDic.get(cmd.para[0]) - 1, this.calc(v1, v2, cmd.para[1]));
else
this.vDic.set(cmd.para[5] == "0" ? cmd.para[0] : this.vDic.get(cmd.para[0]) - 1, this.calc(v1, v2, cmd.para[1]));
break;
}
}
private parsePara(p: string, idx: number) {
return p.split("|")[idx];
}
/**
* @param p1 操作数为常量(0)、其他数值(1)、随机数(2)、二周目变量(3)、索引变量(4)、服务器时间变量(5)、 鲜花数(6)、最大值(7)、最小值(8)、任务(9)、本地时间变量(10)、用数值索引取二周目数值(11)
* @param p2
* @returns {any}
*/
private digByType(type: string, p2: string, p4: string = "") {
switch (parseInt(type)) {
case 0:
return parseInt(p2);
case 1:
return this.vDic.get(p2);
case 2:
let base = parseInt(this.parsePara(p2, 0));
let top = p4 != "" ? parseInt(this.parsePara(p2, 1)) : parseInt(this.parsePara(p2, 1)) + 1;
return Math.floor(Math.random() * (top - base)) + base;
case 3:
return this.exVDic.get(p2);
case 4:
return this.vDic.get(this.vDic.get(p2) - 1);
case 5:
return;
case 6:
return;
case 7://max
return Math.max();
case 8://min
return Math.min();
// case 9://task discarded
case 10://local time
return new Date();
case 11://扩展二周目索引数值
return this.exVDic.get(this.vDic.get(p2) - 1);
}
}
private digByTag(p: string) {
switch (this.parsePara(p, 0)) {
case "EX" :
return this.exVDic.get(this.parsePara(p, 1));
case "MO" :
//移入view模块处理
return "MO";
case "FL" :
case "PT" :
// case "PA" ://discard
return this.exVDic.get(this.parsePara(p, 0));
default:
return this.vDic.get(p);
}
}
private digByChar(p: string) {
switch (this.parsePara(p, 0)) {
case "n" :
return this.digByType("0", this.parsePara(p, 1));
case "v" :
return this.digByType("1", this.parsePara(p, 1));
case "x" :
return this.digByType("3", this.parsePara(p, 1));
case "s" :
return this.digByType("4", this.parsePara(p, 1));
default:
return parseInt(p);
}
}
/**
* @param v1
* @param v2
* @param op 操作符id(=,+=,-=,*=,/=,%=)
* @returns {number}
*/
private calc(v1: number, v2: number, op: string) {
switch (parseInt(op)) {
case 0:
return /*v1 = */v2;
case 1:
return v1 + v2;
case 2:
return v1 - v2;
case 3:
return v1 * v2;
case 4:
return v1 / v2;
case 5:
return v1 % v2;
}
}
judge(para) {
/**
* EX/MO/FL/PT/PA(discard)
* 【若为鼠标按下】 1:矩形类型 2:矩形大小(x,y,w,h)或图片编号 3:0是经过1是按下 4:有无else(1,0)】
* 【若为平台】0:PT| 1:0 2:0 3:平台[1pc,2web,3Android,4IOS,5H5],4:有无else(1,0) 5:显示信息
* 【若为支付】0:PA| 加上 二周目变量 1:是否为恢复购买 2:商品名称(ID) 3:无 4:有无else留位 5:说明
* 【若为任务】长度+1 0:0 1:6(关系index不在指定范围) 2:0 3:0 4:有无else(1,0) 5:显示信息 6:TA|任务编号
* @type {number}
*/
let v2;
switch (this.parsePara(para[0], 0)) {
case "MO" :
return;
// case "PA" :discard
// break;
case "FL" :
case "EX" :
case "PT" :
default :
v2 = para[2] == "2" ? this.digByType("3", para[3]) : this.digByType(para[2], para[3]);
}
return this.compare(this.digByTag(para[0]), v2, para[1]);
}
private compare(v1: number, v2: number, op: string) {
switch (parseInt(op)) {
case 0:
return v1 == v2;
case 1:
return v1 >= v2;
case 2:
return v1 <= v2;
case 3:
return v1 > v2;
case 4:
return v1 < v2;
case 5:
return v1 != v2;
}
}
};<file_sep>/*
import ValueMgr from "./Mgr/ValueMgr";
import VideoMgr from "./Mgr/VideoMgr";
import AudioMgr from "./Mgr/AudioMgr";
import {Cmd, DChapter} from "../data/sotry/Story";
import {StateEnum, StateMgr} from "./state/State";
import AssMgr from "./Mgr/AssMgr";
import {ViewMgr} from "./Mgr/ViewMgr";
import {IMgr} from "./Mgr/Mgr";
import DH from "../data/DH";
import Conf from "../data/Conf";
import Reporter from "./reporter/Reporter";
import Chapter from "./cmd/chapter/Chapter";
import SlicedChapter from "./cmd/chapter/SlicedChapter";
export enum MgrEnum {ass, view, value, audio, video}
/!**
* 逻辑控制器
* 负责命令分发至各管理器
* Created by ShanFeng on 5/2/2017.
* alias "TimeLine"
*!/
export default class CmdLine {
private dh: DH = DH.instance;
private reporter: Reporter;
private cc: number = 0;//call counter
private state: StateMgr;
private assMgr: AssMgr;
private viewMgr: ViewMgr;
private valueMgr: ValueMgr;
private audioMgr: AudioMgr;
private videoMgr: VideoMgr;
mgrArr: IMgr[] = [
this.assMgr = new AssMgr(),
this.viewMgr = new ViewMgr(),
this.valueMgr = new ValueMgr(),
this.audioMgr = new AudioMgr(),
this.videoMgr = new VideoMgr()
];
private chapter: SlicedChapter;
private cmdArr: Cmd[] = [];
private curSid: number = 0;
private nextSid: number = 0;
private curCid: number = 0;
constructor() {
this.reporter = this.dh.reporter;
this.state = new StateMgr();
this.dh.eventPoxy.on(Conf.PLAY_CHAPTER, this, this.playHandler);
this.dh.eventPoxy.on(Conf.RESTORE, this, this.restore);
this.dh.eventPoxy.on(Conf.ITEM_CHOSEN, this, this.nextScene);
this.dh.eventPoxy.on(Conf.CMD_LINE_RESUME, this, this.update);
}
printScene() {
this.reporter.printSceneArr(this.chapter);
}
/!**
* 章节数据准备完毕启动该句柄
* @param c
*!/
playHandler(c: DChapter) {
this.chapter = new Chapter(c);
this.nextScene(0);
this.state.play(true);
}
restore(snap) {
let name = this.chapter.name;
this.curCid = snap[0];
this.curSid = snap[1];
this.chapter = snap[2];
this.cmdArr = this.chapter.getScene(this.curSid).cmdArr;
}
complete() {
if (!this.state.restore()) {
this.state.pause(0, true);
if (this.dh.story.sys.skipTitle)
this.dh.story.gotoChapter(this.dh.story.sys.startStoryId);
else
this.viewMgr.ul.showMenu(-1);
}
}
/!**
* 浮层及高级UI临时命令行插入
* @param chapter
* @returns {number}
*!/
insertChapter(chapter: Chapter) {
if (this.state.id != StateEnum.Frozen && this.state.id != StateEnum.FrozenAll)
this.state.mark([this.curCid, this.curSid, this.chapter]);
this.state.frozen();
this.chapter = chapter;
this.nextScene(0);
}
nextScene(sid: number = NaN) {
if (isNaN(sid))
return;
this.curCid = 0;
let s;
if (s = this.chapter.getScene(sid)) {
this.curSid = sid;
this.nextSid = s.link;
this.cmdArr = s.cmdArr;
} else if (this.chapter.name == "CUI_load") {
this.state.frozenAll();
this.dh.eventPoxy.event(Conf.CUI_LOAD_READY);
} else {
this.complete()
}
return s;
}
update(sid = NaN) {
if (!isNaN(sid))
if (this.nextScene(sid) == null)
return;
while (this.curCid < this.cmdArr.length) {
this.cc++;
let cmd = this.cmdArr[this.curCid++];
this.reporter.logProcess(cmd, this.cc);//test only
switch (cmd.code) {
//需暂停等待
case 208: //"返回标题画面"
case 214: //"呼叫游戏界面"
if (parseInt(cmd.para[0]) == 10008) {
this.state.mark(null);
this.complete();
}
else if (parseInt(cmd.para[0]) == 10009)
this.state.auto();
else {
if (this.state.id < 4)
this.state.mark([this.curCid, this.curSid, this.chapter]);
this.state.frozenAll();
this.viewMgr.exe(cmd);
}
return this.cc = 0;
// case 110: //"打开指定网页";
case 100 : { //"显示文章"
this.state.pause();
this.viewMgr.exe(cmd);
return this.cc = 0;
}
case 101: //剧情分歧
case 1010: //剧情分歧EX
case 1011: //剧情分歧EX2
case 204: { //按钮分歧
this.state.pause(0, true);
this.viewMgr.exe(cmd);
return this.cc = 0;
}
case 151: {//"返回游戏界面"
this.state.restore();
this.viewMgr.exe(cmd);
return this.cc = 0;
}
//状态指令
case 210: {//等待
this.state.pause(parseInt(cmd.para[0]));
return this.cc = 0;
}
case 103: {//"自动播放剧情"
if (cmd.para[0] == "1")
this.state.auto();
else
this.state.cancel();
break;
}
case 104: {//"快进剧情"
if (cmd.para[0] == "1")
this.state.fast();
else
this.state.cancel();
break;
}
case 108 :
case 212 :
case 211 :
case 102 :
case 205 :
case 201 :
return this.update(cmd.links[0]);
//repeat end
case 203:
//repeat interrupt
case 209: {
if (this.cc > 8000) {
this.nextSid = cmd.links[0];
return this.cc = 0;
} else
return this.update(cmd.links[0]);
}
case 206 : //跳转剧情
case 251: {//呼叫子剧情
this.state.mark(cmd.code == 206 ? null : [this.curCid, this.curSid, this.chapter]);
this.state.pause(0, true);
this.dh.story.gotoChapter(parseInt(cmd.para[0]));
this.reporter.logTrans(cmd, [this.curCid, this.curSid, this.chapter]);//test only
return this.cc = 0;
}
//条件分歧
case 200: {
let bingo;
if (cmd.para[0].split("|")[0] == "MO") {
bingo = this.viewMgr.ul.checkHotarea(cmd);
this.nextSid = cmd.links[bingo ? 0 : 1];
if (bingo && cmd.para[3] == '1')
return this.cc = 0;
} else
return this.update(cmd.links[this.valueMgr.judge(cmd.para) ? 0 : 1]);
}
case 217: {//高级条件分歧
let len = parseInt(cmd.para[3]);
let bingo;
for (let i = 4; i < 4 + len; i++) {
let p = cmd.para[i].split("&");
if (cmd.para[0] == "0") { // cmd.para[0] || : &&;
if (p[0].split("|")[0] == "MO") {
let moCmd: Cmd = {code: 200, idt: NaN, para: p};
this.viewMgr.exe(moCmd);
bingo = this.viewMgr.ul.checkHotarea(moCmd);
} else {
bingo = this.valueMgr.judge(p);
}
if (bingo)
break;
}
else {
if (p[0].split("|")[0] == "MO") {
let moCmd: Cmd = {code: 200, idt: NaN, para: p};
bingo = this.viewMgr.ul.checkHotarea(moCmd);
} else {
bingo = this.valueMgr.judge(p);
}
if (!bingo)
break;
}
bingo = cmd.para[0] != "0";
}
return this.update(cmd.links[bingo ? 0 : 1]);
}
default: {//非逻辑命令分发
for (let mgr of this.mgrArr)
mgr.exe(cmd);
if (this.state.id == StateEnum.FF)
this.viewMgr.update(0);
}
}
}
return this.update(this.nextSid);
}
};*/
<file_sep>/**
* Created by ShanFeng on 4/1/2017.
*/
namespace gnk.data {
interface IIterator<T> {
next(): T;
pre(): T;
reset(): number;
}
export class Iterator<T> implements IIterator<T> {
protected idx: number;
/**
* 依据数组生成迭代器,使用数组引用进行管理修饰;
* 迭代器可动态同步数组变化;
* @param arr
*/
constructor(protected arr: T[]) {
this.idx = -1;
}
next(): T {
if (this.idx < this.arr.length - 1) {
return this.arr[++this.idx];
} else {
return null;
}
}
pre(): T {
if (this.idx < 0) {
this.idx = 0;
}
if (this.idx != 0) {
return this.arr[--this.idx];
} else {
return null;
}
}
/**
* 复位游标
* @param idx [可指定游标位置, 缺省-1:起始位置]
* @returns {number}
*/
reset(idx: number = -1): number {
if (idx < this.arr.length && idx > -2) {
this.idx = idx;
} else if (idx >= this.arr.length) {
this.idx = this.arr.length - 1;
} else {
this.idx = -1;
}
return this.idx;
}
}
export class LoopIterator<T> extends Iterator<T> implements IIterator<T> {
constructor(arr: T[]) {
super(arr);
}
next(): T {
if (this.idx < this.arr.length - 1) {
return this.arr[++this.idx];
} else {
return this.arr[this.idx = 0];
}
}
pre(): T {
if (this.idx < 0) {
this.idx = 0;
}
if (this.idx != 0) {
return this.arr[--this.idx];
} else {
return this.arr[this.idx = this.arr.length - 1];
}
}
}
}<file_sep>import Scene from "../Scene";
import {Cmd, DChapter} from "../../../data/sotry/Story";
/**
* Created by ShanFeng on 5/8/2017.
*/
export default class Chapter extends DChapter {
private curId: number = 0;
private repeat: [number[], Cmd[][]] = [[], []];
constructor(dc: DChapter) {
super(dc);
//值传开关,当前为数据轻量化关掉,但传入参数会被吸收导致外部数据缺失,外部可使用concat()方法复制一份作为入参
// this.cmdArr = this.cmdArr.concat();
this.formScene();
}
/**
* 欢迎 ╮ ( ̄ 3 ̄) ╭
* @param branch
* @returns {Scene}
*/
private formScene(otl = null) {
let ote = [];
while (this.curId < this.cmdArr.length) {
let cmd: Cmd = this.cmdArr[this.curId++];
switch (cmd.code) {
/*********************repeat*********************/
case 202 : //start
this.repeat[0].push(this.curId);
if (this.repeat[1][this.repeat[0].length - 1] == null)
this.repeat[1].push([]);
break;
case 209 : //interrupt
this.repeat[1][parseInt(cmd.para[0]) - 1].push(cmd);
break;
case 203 : //end
this.repeat[1].reverse();
while (this.repeat[1][this.repeat[0].length - 1].length > 0)
this.repeat[1][this.repeat[0].length - 1].pop().links = [this.curId];
this.repeat[1].pop();
this.repeat[1].reverse();
cmd.links = [this.repeat[0].pop()];
break;
/*********************repeat end*****************/
/*********************branch*********************/
//switch
case 101: //剧情分歧
case 1010:
case 1011:
case 204: //按钮分歧
case 200: //条件分歧
case 217: //高级条件分歧
let te = this.formScene(cmd.links = cmd.code == 200 || cmd.code == 217 ? [this.curId] : []);
while (te.length)
te.pop().push(this.curId);
break;
//options
case 108: //分支选项内容
case 212: //按钮分歧内容
if (otl.length == 0)
cmd.links = [this.curId];
else
ote.push(cmd.links = []);
otl.push(this.curId);
break;
case 211: //条件分歧else内容
otl.push(this.curId);
ote.push(cmd.links = []);
break;
//end
case 102: //剧情分歧
case 205: //按钮分歧
ote.push(cmd.links = []);
return ote;
case 201: //条件分歧
if (otl.length == 1)
otl.push(this.curId);
ote.push(cmd.links = []);
return ote;
/*********************branch end*****************/
default:
}
}
}
}<file_sep>import ValueMgr from "./Mgr/ValueMgr";
import VideoMgr from "./Mgr/VideoMgr";
import AudioMgr from "./Mgr/AudioMgr";
import {Cmd, DChapter} from "../data/sotry/Story";
import {StateEnum, StateMgr} from "./state/State";
import AssMgr from "./Mgr/AssMgr";
import {ViewMgr} from "./Mgr/ViewMgr";
import {IMgr} from "./Mgr/Mgr";
import DH from "../data/DH";
import Conf from "../data/Conf";
import Reporter from "./reporter/Reporter";
import Chapter from "./cmd/chapter/Chapter";
export enum MgrEnum {ass, view, value, audio, video}
/**
* 逻辑控制器
* 负责命令分发至各管理器
* Created by ShanFeng on 5/2/2017.
* alias "TimeLine"
*/
export default class CmdLine {
snap: any;
private dh: DH = DH.instance;
private reporter: Reporter;
private cc: number;//call counter
private state: StateMgr;
private assMgr: AssMgr;
private viewMgr: ViewMgr;
private valueMgr: ValueMgr;
private audioMgr: AudioMgr;
private videoMgr: VideoMgr;
mgrArr: IMgr[] = [
this.assMgr = new AssMgr(),
this.viewMgr = new ViewMgr(),
this.valueMgr = new ValueMgr(),
this.audioMgr = new AudioMgr(),
this.videoMgr = new VideoMgr()
];
private chapter: Chapter;
private cmdArr: Cmd[];
private curCid: number;
constructor() {
this.reporter = this.dh.reporter;
this.state = new StateMgr();
this.dh.eventPoxy.on(Conf.PLAY_CHAPTER, this, this.playHandler);
this.dh.eventPoxy.on(Conf.RESTORE, this, this.restore);
this.dh.eventPoxy.on(Conf.ITEM_CHOSEN, this, this.update);
this.dh.eventPoxy.on(Conf.CMD_LINE_RESUME, this, this.update);
}
printCmdArr() {
console.log("scene id: " + this.chapter.id + "\nscene name: " + this.chapter.name);
this.reporter.printCmdArr(this.cmdArr);
}
/**
* 章节数据准备完毕启动该句柄
* @param c
*/
playHandler(c: DChapter) {
this.chapter = new Chapter(c);
this.cmdArr = this.chapter.cmdArr;
if (this.snap) {
this.curCid = this.snap[1];
this.state.switchState(this.snap[2]);
this.snap = null;
} else {
this.curCid = 0;
this.state.play(true);
}
//for preview cmd
// DH.instance.cmdLine.printCmdArr();
}
restore(snap) {
this.snap = snap;
this.dh.story.gotoChapter(snap[0]);
}
complete() {
if (this.state.id == StateEnum.Frozen) {
this.state.frozenAll();
if (this.chapter.name == "CUI_load")
this.dh.eventPoxy.event(Conf.CUI_LOAD_READY);
} else if (!this.state.restore()) {
if (this.dh.story.sys.skipTitle)
this.dh.story.gotoChapter(this.dh.story.sys.startStoryId);
else
this.viewMgr.ul.showMenu(-1);
}
}
/**
* 浮层及高级UI临时命令行插入
* @param chapter
* @returns {number}
*/
insertChapter(chapter: Chapter) {
if (this.state.id < StateEnum.Frozen) {//equl (this.state.id != StateEnum.Frozen && this.state.id != StateEnum.FrozenAll)
console.log("temp inster:" + chapter.name + " @ story: " + this.chapter.id + ":" + (this.curCid - 1) + ":" + this.state.id);
this.state.mark([this.chapter.id, this.curCid]);
}
this.curCid = 0;
this.chapter = chapter;
this.cmdArr = chapter.cmdArr;
this.state.frozen();
}
update(cid = NaN) {
if (!isNaN(cid))
this.curCid = cid;
while (this.curCid < this.cmdArr.length) {
this.cc++;
let cmd = this.cmdArr[this.curCid++];
this.reporter.logProcess(cmd, this.cc);//test only
switch (cmd.code) {
//需暂停等待
case 208: //"返回标题画面"
case 214: //"呼叫游戏界面"
if (parseInt(cmd.para[0]) == 10008) {
this.state.mark(null);
this.complete();
}
else if (parseInt(cmd.para[0]) == 10009)
this.state.auto();
else {
if (this.state.id < StateEnum.Frozen) {
console.log("open win:" + parseInt(cmd.para[0]) + " @ story: " + this.chapter.id + ":" + (this.curCid - 1) + ":" + this.state.id);
this.state.mark([this.chapter.id, this.curCid]);
}
this.state.frozenAll();
this.viewMgr.exe(cmd);
}
return this.cc = 0;
// case 110: //"打开指定网页";
case 100 : { //"显示文章"
this.state.pause();
this.viewMgr.exe(cmd);
return this.cc = 0;
}
case 101: //剧情分歧
case 1010: //剧情分歧EX
case 1011: //剧情分歧EX2
case 204: { //按钮分歧
this.state.pause(0, true);
this.viewMgr.exe(cmd);
return this.cc = 0;
}
case 151: {//"返回游戏界面"
this.state.restore();
this.viewMgr.exe(cmd);
return this.cc = 0;
}
//状态指令
case 210: {//等待
this.state.pause(parseInt(cmd.para[0]));
return this.cc = 0;
}
case 103: {//"自动播放剧情"
if (cmd.para[0] == "1")
this.state.auto();
else
this.state.cancel();
break;
}
case 104: {//"快进剧情"
if (cmd.para[0] == "1")
this.state.fast();
else
this.state.cancel();
break;
}
case 108 :
case 212 :
case 211 :
case 102 :
case 205 :
case 201 :
return this.update(cmd.links[0]);
//repeat end
case 203:
//repeat interrupt
case 209: {
if (this.cc > 8000) {
this.curCid = cmd.links[0];
return this.cc = 0;
} else
return this.update(cmd.links[0]);
}
case 206 : //跳转剧情
case 251: {//呼叫子剧情
console.log((cmd.code == 206 ? "goto: " : "insert:") +
parseInt(cmd.para[0]) + " @ story: " + this.chapter.id + ":" + (this.curCid - 1) + ":" + this.state.id);
this.state.mark(cmd.code == 206 ? null : [this.chapter.id, this.curCid]);
this.state.pause(0, true);
this.dh.story.gotoChapter(parseInt(cmd.para[0]));
return this.cc = 0;
}
//条件分歧
case 200: {
let bingo;
if (cmd.para[0].split("|")[0] == "MO") {
bingo = this.viewMgr.ul.checkHotarea(cmd);
this.curCid = cmd.links[bingo ? 0 : 1];
return bingo && cmd.para[3] == '1' ? this.cc = 0 : this.update(this.curCid);
} else
return this.update(cmd.links[this.valueMgr.judge(cmd.para) ? 0 : 1]);
}
case 217: {//高级条件分歧
let len = parseInt(cmd.para[3]);
let bingo;
for (let i = 4; i < 4 + len; i++) {
let p = cmd.para[i].split("&");
if (cmd.para[0] == "0") { // cmd.para[0] || : &&;
if (p[0].split("|")[0] == "MO") {
let moCmd: Cmd = {code: 200, para: p};
this.viewMgr.exe(moCmd);
bingo = this.viewMgr.ul.checkHotarea(moCmd);
} else {
bingo = this.valueMgr.judge(p);
}
if (bingo)
break;
}
else {
if (p[0].split("|")[0] == "MO") {
let moCmd: Cmd = {code: 200, para: p};
bingo = this.viewMgr.ul.checkHotarea(moCmd);
} else {
bingo = this.valueMgr.judge(p);
}
if (!bingo)
break;
}
bingo = cmd.para[0] != "0";
}
return this.update(cmd.links[bingo ? 0 : 1]);
}
default: {//非逻辑命令分发
for (let mgr of this.mgrArr)
mgr.exe(cmd);
if (this.state.id == StateEnum.FF)
this.viewMgr.update(0);
}
}
}
return this.complete();
}
};<file_sep>import Story from "./sotry/Story";
/**
* Created by Lonmee on 4/23/2017.
* 框架静态数据预置
*/
interface Frameworks {
ver?: string
width?: number
height?: number
bgColor?: string
showStatus?: boolean
}
interface Domain {
cdn?: string
resCdn: string
}
interface WebApi {
testSvr: string
svr: string
}
interface LoaderConf {
retry?: number
delay?: number
max?: number
}
interface Info {
storyArr?: Story[];
miniPath?: string;
gid?: string
ver?: number
qlty?: string
single?: boolean
}
interface LocalTest {
on: boolean
mb: string
sb: string
}
/**
* 起始游戏文件名
* 单包、分包
*/
interface StarName {
single: string
multiple: string
}
export default class Conf {
//Event
static STAGE_BLUR: string = "stage_blur";
static LOADING_PROGRESS: string = "loading_progress";
static PLAY_CHAPTER: string = "play_chapter";
static ITEM_CHOSEN: string = "item_chosen";
static RESTORE: string = "restore";
static CMD_LINE_RESUME: string = "cmd_line_resume";
static STATE_AUTO: string = "state_atuo";
static STATE_FF: string = "state_ff";
static STATE_FROZEN: string = "state_froze";
static STATE_CANCEL: string = "state_cancel";
static CUI_LOAD_READY: string = "cui_load_ready";
//static
static debug: boolean = true;//Todo:发布时关掉
static localTest: LocalTest = {on: false, mb: "local/Map.bin", sb: "local/Game.bin"};
static domain: Domain = {
cdn: "http://dlcdn1.cgyouxi.com/",
resCdn: "http://dlcdn1.cgyouxi.com/shareres/",
};
static domain4Test: Domain = {
cdn: "http://testcdn.66rpg.com/",
resCdn: "http://testcdn.66rpg.com/shareres/"
};
static webApi: WebApi = {
testSvr: "//test-cg.66rpg.com/",
svr: "//cgv2.66rpg.com/"
};
static loaderConf: LoaderConf = {};
static starName: StarName = {single: "data/game.bin", multiple: "game00.bin"};
//dynamic
static frameworks: Frameworks = {ver: "1.0", bgColor: "#0", showStatus: false};
static info: Info = {};
constructor() {
//TODO:平台适配设置
/*this.isMobile = Laya.Browser.onMobile;
this.isIos = Laya.Browser.onIOS;
this.isAndroid = Laya.Browser.onAndriod;
this.isAndroidBox = (GloableData.getInstance().mark== 'aBox');
this.isSafrai = Laya.Browser.onSafari;
var ua:string = window.navigator.userAgent.toLowerCase();
if(ua.indexOf('micromessenger') !=-1){
this.isWX = true;*/
//Laya.Browser.onMobile
//navigator.platform
//navigator.appVersion
//navigator.userAgent
}
static query(name: string) {
let reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
let r = window.location.search.substr(1).match(reg);
if (r != null) return (r[2]);
return null;
}
}<file_sep>import Sprite = laya.display.Sprite;
import Event = laya.events.Event;
import {BGImg, Button, Label, OtherImg, Slider, UIImg} from "./Comp";
import DH from "../../../../../data/DH";
import {CusUI, IdxBtn, Path} from "../../../../../data/sotry/Story";
import {MgrEnum} from "../../../../CmdLine";
import {MenuEnum} from "../UIFac";
import Conf from "../../../../../data/Conf";
import {StateEnum} from "../../../../state/State";
import Chapter from "../../../../cmd/chapter/Chapter";
/**
* Created by ShanFeng on 5/29/2017.
*/
export class Menu extends Sprite {
protected btnArr: Button[];
constructor(public idx: number, protected data: any) {
super();
this.initView();
this.initAudio();
this.initListener();
}
close() {
this.event(Event.CLOSE, this.idx);
}
protected initView() {
}
protected initBGImgAndBtns(bgImg: Path, btnArr: IdxBtn[]) {
let bArr: Button[] = [];
//bgImg
if (this.data.bgImg)
this.addChild(new UIImg(this.data.bgImg.path));
//btns
for (let btn of btnArr) {
let db: any = DH.instance.story.sys.Buttons[btn.idx];
// if (db.image1.path == "" && db.image1.path == "")
// continue;
bArr.push(<Button>this.addChild(new Button(btn.idx).pos(btn.x, btn.y)));
}
return bArr;
}
protected initAudio() {
}
protected initListener() {
}
}
export class Title extends Menu {
constructor(ind: number, data: any) {
super(ind, data);
}
protected initView() {
//logo & titleBG
if (this.data.showLog)
this.addChild(new UIImg(this.data.logoImage.path));
if (this.data.drawTitle)
this.addChild(new BGImg(this.data.titleImage.path));
//btns
this.initBGImgAndBtns(null, this.data.buttons)[0].on(Event.CLICK, this, this.clickHandler);
}
protected initListener() {
this.on(Event.ADDED, this, this.addHandler);
this.on(Event.REMOVED, this, this.removeHandler);
this.on(Event.CLICK, this, this.clickHandler);
}
private clickHandler(e: Event) {
DH.instance.story.gotoChapter(DH.instance.story.sys.startStoryId);
this.close();
}
private addHandler(e: Event) {
if (this.data.bgm) {
//todo:待定界面背景音实现位置
//<AudioMgr>DH.instance.mgrArr[MgrEnum.audio]
}
}
private removeHandler(e: Event) {
}
protected initAudio() {
if (this.data.bgm) {
//todo:load audio file
}
}
}
export class Game extends Menu {
btnArr: Button[];
constructor(ind: number, data: any) {
super(ind, data);
}
initView() {
this.btnArr = this.initBGImgAndBtns(this.data.bgImg.path, this.data.buttons);
}
initListener() {
for (let i = 0; i < this.btnArr.length; i++) {
this.btnArr[i].idx = i;
this.btnArr[i].on(Event.CLICK, null, (e: Event) => {
switch ((<Button>e.target).idx) {
case 0:
MenuEnum.save;
break;
case 1:
MenuEnum.restore;
break;
case 2:
MenuEnum.replay;
break;
case 3:
DH.instance.eventPoxy.event(Conf.STATE_AUTO, StateEnum.Auto);
break;
case 4:
MenuEnum.setting;
break;
case 5:
this.close();
break;
}
})
}
}
}
export class Replay extends Menu {
constructor(ind: number, data: any) {
super(ind, data);
}
initView() {
this.initBGImgAndBtns(this.data.bgImg, [this.data.closeButton]);
//vpRect
this.data.vpRect;
}
}
export class CG extends Menu {
constructor(ind: number, data: any) {
super(ind, data);
}
initView() {
this.btnArr = this.initBGImgAndBtns(this.data.bgImg.path, [this.data.closeButton, this.data.backButton]);
//noPic
this.data.noPic;
//vpRect
this.data.vpRect;
//CGList
this.data.CGList;
}
initListener() {
for (let i = 0; i < this.btnArr.length; i++) {
this.btnArr[i].idx = i;
this.btnArr[i].on(Event.CLICK, null, (e: Event) => {
switch ((<Button>e.target).idx) {
case 0:
this.close();
break;
default:
}
});
}
}
}
export class BGM extends Menu {
constructor(ind: number, data: any) {
super(ind, data);
}
initView() {
this.initBGImgAndBtns(this.data.bgImg.path, [this.data.closeButton, this.data.backButton, this.data.selectButton]);
//noPic
this.data.noPic;
//vpRect
this.data.vpRect;
//BGMList
this.data.bgmList;
}
}
export class Save extends Menu {
constructor(ind: number, data: any) {
super(ind, data);
}
initView() {
this.btnArr = this.initBGImgAndBtns(this.data.bgImg.path, [this.data.closeButton, this.data.backButton]);
}
initListener() {
for (let i = 0; i < this.btnArr.length; i++) {
this.btnArr[i].idx = i;
this.btnArr[i].on(Event.CLICK, null, (e: Event) => {
switch ((<Button>e.target).idx) {
case 0:
case 1:
this.close();
break;
default:
}
});
}
}
}
export class Restore extends Menu {
constructor(ind: number, data: any) {
super(ind, data);
}
initView() {
this.btnArr = this.initBGImgAndBtns(this.data.bgImg.path, [this.data.closeButton, this.data.backButton]);
}
initListener() {
for (let i = 0; i < this.btnArr.length; i++) {
this.btnArr[i].idx = i;
this.btnArr[i].on(Event.CLICK, null, (e: Event) => {
switch ((<Button>e.target).idx) {
case 0:
case 1:
this.close();
break;
default:
}
});
}
}
}
export class Setting extends Menu {
idxArr: number[];
btnArr: Button[];
sliders: Array<[Slider, number]>;
constructor(ind: number, data: any) {
super(ind, data);
}
initView() {
this.idxArr = [];
this.btnArr = this.initBGImgAndBtns(this.data.bgImg.path, this.data.ShowTitle ? [this.data.closeButton, this.data.TitleButton] : [this.data.closeButton]);
(<Sprite>this.getChildAt(0)).mouseEnabled = true;
this.idxArr.push(0);
if (this.data.ShowTitle)
this.idxArr.push(1);
//切开初始化用来加toggle
let btnArr: IdxBtn[] = [];
if (this.data.ShowFull) {
btnArr = btnArr.concat([this.data.fullButton, this.data.winButton]);
this.idxArr = this.idxArr.concat([2, 3]);
}
if (this.data.ShowAuto) {
btnArr = btnArr.concat([this.data.AutoOn, this.data.AutoOff]);
this.idxArr = this.idxArr.concat([4, 5]);
}
for (let btn of btnArr) {
let db: any = DH.instance.story.sys.Buttons[btn.idx];
if (db.image1.path == "" && db.image1.path == "")
continue;
this.btnArr.push(<Button>this.addChild(new Button(btn.idx, null, null, true).pos(btn.x, btn.y)));
}
this.sliders = [];
if (this.data.ShowBGM)
this.sliders.push([<Slider>this.addChild(new Slider(this.data.barNone, this.data.barMove).pos(this.data.BgmX, this.data.BgmY)), 0]);
if (this.data.ShowSE)
this.sliders.push([<Slider>this.addChild(new Slider(this.data.barNone, this.data.barMove).pos(this.data.SeX, this.data.SeY)), 1]);
if (this.data.ShowVoice)
this.sliders.push([<Slider>this.addChild(new Slider(this.data.barNone, this.data.barMove).pos(this.data.VoiceX, this.data.VoiceY)), 2]);
}
initListener() {
for (let i = 0; i < this.btnArr.length; i++) {
this.btnArr[i].idx = this.idxArr[i];
this.btnArr[i].on(Event.CLICK, null, (e: Event) => {
switch ((<Button>e.target).idx) {
case 0:
this.close();
// DH.instance.mgrArr[MgrEnum.view].exe({code: 151, para: [], idt: 0});//so crazy
break;
case 1:
DH.instance.mgrArr[MgrEnum.view].exe({code: 208, para: []});//so crazy
break;
case 2:
this.btnArr[2].toggled = false;
this.btnArr[3].toggled = true;
//todo:全屏模式
break;
case 3:
this.btnArr[2].toggled = true;
this.btnArr[3].toggled = false;
//todo:窗口模式
break;
case 4:
this.btnArr[4].toggled = false;
this.btnArr[5].toggled = true;
//todo:手动播放
break;
case 5:
this.btnArr[4].toggled = true;
this.btnArr[5].toggled = false;
//todo:自动播放
break;
}
});
}
for (let i = 0; i < this.sliders.length; i++) {
this.sliders[i][0].on(Event.CHANGE, null, (v: number) => {
switch (this.sliders[i][1]) {
case 0:
//todo:设置乐音音量
v;
break;
case 1:
//todo:设置音效音量
v;
break;
case 2:
//todo:设置语音音量
v;
}
});
}
}
switchFullscreen(on: boolean) {
if (this.data.ShowFull) {
this.btnArr[2].toggled = on;
this.btnArr[3].toggled = !on;
}
}
switchAutoplay(on: boolean) {
if (this.data.ShowFull) {
this.btnArr[4].toggled = on;
this.btnArr[5].toggled = !on;
}
}
setVolume(n: number, v: number) {
this.sliders[n][0].setValue(v);
}
}
export class CUI extends Menu {
bounds: any;
private afterChapter: Chapter;
private loadChapter: Chapter;
private controlSpr: Sprite;
constructor(ind: number, data: CusUI) {
super(ind, data);
data.showEffect;//todo:dcui.showEffect
}
close() {
while (this.bounds && this.bounds.length) {
let ba = this.bounds.pop();
ba[0].unbind(ba[1], ba[2]);
}
while (this.controlSpr.numChildren)
this.controlSpr.removeChildAt(0).destroy(true);
if (this.data.isMouseExit)
DH.instance.eventPoxy.off(Event.RIGHT_CLICK, this, super.close);
if (this.data.isKeyExit)
DH.instance.eventPoxy.off("Escape", this, super.close);
}
protected initView() {
this.addChild(this.controlSpr = new Sprite());
if (this.data.loadEvent.length) {
this.loadChapter = new Chapter({id: NaN, name: "CUI_load", cmdArr: this.data.loadEvent});
}
if (this.data.afterEvent.length)
this.afterChapter = new Chapter({id: NaN, name: "after", cmdArr: this.data.afterEvent});
this.exeLoadChapter();
}
updateControls() {
this.bounds = [];
for (let ctl of this.data.controls) {
switch (ctl.type) {
case 0://按钮
let b;
this.controlSpr.addChild(b = new Button(ctl.useIdx ? DH.instance.vDic.get(ctl.index) - 1 : ctl.index)
.pos(ctl.useVar ? DH.instance.vDic.get(ctl.x) : ctl.x, ctl.useVar ? DH.instance.vDic.get(ctl.y) : ctl.y));
if (ctl.cmdArr.length)
b.on(Event.CLICK, this, this.exe, [new Chapter({
id: NaN,
name: "cui",
cmdArr: ctl.cmdArr.concat()
})]);
if (ctl.useIdx) {
DH.instance.vDic.bind(ctl.index, b.update.bind(b));
this.bounds.push([DH.instance.vDic, ctl.index, b.update]);
}
break;
case 1://字符串
case 2://变量
let l: Label;
if (ctl.type == 1) {
this.controlSpr.addChild(l = new Label(DH.instance.replaceVTX(DH.instance.sDic.get(ctl.index))));
DH.instance.sDic.bind(ctl.index, l.update.bind(l));
this.bounds.push([DH.instance.sDic, ctl.index, l.update]);
} else {
this.controlSpr.addChild(l = new Label(DH.instance.vDic.get(ctl.index)));
DH.instance.vDic.bind(ctl.index, l.update.bind(l));
this.bounds.push([DH.instance.vDic, ctl.index, l.update]);
}
l.pos(ctl.useVar ? DH.instance.vDic.get(ctl.x) : ctl.x, ctl.useVar ? DH.instance.vDic.get(ctl.y) : ctl.y);
break;
case 3://图片
let i = new OtherImg(ctl.useStr ? DH.instance.replaceVTX(DH.instance.sDic.get(ctl.strIdx)) : ctl.image1)
.pos(ctl.useVar ? DH.instance.vDic.get(ctl.x) : ctl.x, ctl.useVar ? DH.instance.vDic.get(ctl.y) : ctl.y);
this.controlSpr.addChild(i);
break;
case 4://滚动条
break;
}
}
this.initListener();
this.exeAfterChapter();
return this;
}
exe(c: Chapter) {
DH.instance.cmdLine.insertChapter(c);
}
exeLoadChapter() {
if (this.loadChapter) {
DH.instance.eventPoxy.once(Conf.CUI_LOAD_READY, this, this.updateControls);
this.exe(this.loadChapter);
} else {
this.updateControls()
}
return this;
}
exeAfterChapter() {
if (this.afterChapter)
this.exe(this.afterChapter);
}
protected initAudio() {
return super.initAudio();
}
protected initListener() {
if (this.data.isMouseExit)
DH.instance.eventPoxy.on(Event.RIGHT_CLICK, this, super.close);
if (this.data.isKeyExit)
DH.instance.eventPoxy.on("Escape", this, super.close);
}
}<file_sep>/**
* Created by Lonmee on 4/23/2017.
*/
declare function require(moduleNames: string[], onLoad: (...args: any[]) => void): void;<file_sep>import DH, {IBinloader} from "../../data/DH";
import Conf from "../../data/Conf";
import Byte = laya.utils.Byte;
import Handler = laya.utils.Handler;
import Loader = laya.net.Loader;
import {Cmd, DChapter} from "../../data/sotry/Story";
/**
* Created by ShanFeng on 5/2/2017.
* alias "ChapterLoader"
*/
export default class StepLoader implements IBinloader {
dh: DH = DH.instance;
constructor(id: number) {
this.loadChapter(id);
}
loadChapter(id: number) {
let fn: string = `game${id}.bin`;
Laya.loader.load(this.dh.getResLink(fn),
Handler.create(this, this.completeHandler, null, false),
Handler.create(this, this.progressHandler, [fn], false),
Loader.BUFFER, 0, true, "bin", false);
}
private progressHandler(fn: string, p: number) {
DH.instance.eventPoxy.event(Conf.LOADING_PROGRESS, [fn, p]);
}
private completeHandler(ab: ArrayBuffer) {
let byte: Byte = new Byte(ab);
byte.pos += 4;
let c: DChapter = {
name: parseUTF(),
id: byte.getInt32(),
cmdArr: parseCmdArr()
};
DH.instance.eventPoxy.event(Conf.PLAY_CHAPTER, c);
function parseCmdArr(): Cmd[] {
let arr: Cmd[] = [];
let len = byte.getInt32();
for (let i = 0; i < len; i++) {
arr.push(parseCmd());
}
return arr;
}
function parseCmd(): Cmd {
byte.pos += 4;
let c = byte.getInt32();
byte.pos += 4;
let p = parsePara();
return {code: c, para: p};//{code: byte.getInt32(), idt: byte.getInt32(), para: parsePara()};
}
function parsePara(): string[] {
let arr: string[] = [];
let len = byte.getInt32();
for (let i = 0; i < len; i++) {
arr.push(parseUTF());
}
return arr;
}
function parseUTF(): string {
return byte.getUTFBytes(byte.getInt32());
}
}
}<file_sep>import Dictionary = laya.utils.Dictionary;
import EventDispatcher = laya.events.EventDispatcher;
import Conf from "./Conf";
import CmdLine from "../mod/CmdLine";
import Story from "./sotry/Story";
import {IMgr} from "../mod/Mgr/Mgr";
import Preloader from "../mod/loader/Preloader";
import {DigitalDic, StringDic} from "../mod/Mgr/value/ODictionary";
import {IState} from "../mod/state/State";
import Reporter from "../mod/reporter/Reporter";
/**
* Created by ShanFeng on 4/24/2017.
* means DataHolder
*/
export interface IBinloader {
loadChapter(id: number);
}
export default class DH {
private static _instance: DH;
eventPoxy: EventDispatcher = new EventDispatcher();
resMap: Dictionary = new Dictionary();
binLoader: IBinloader;
story: Story;
cmdLine: CmdLine;
mgrArr: IMgr[];
preloader: Preloader;
//region 运行时共享数据组
imgDic: laya.utils.Dictionary;
vDic: DigitalDic;
sDic: StringDic;
exVDic: DigitalDic;
//endregion
reporter: Reporter;
state: IState;
static get instance(): DH {
return this._instance ? this._instance : this._instance = new DH();
}
getResLink(key: string): string {
//todo:resource link for local mode
let md5 = this.resMap.get(key.replace(/\\/g, '/').toLowerCase()).md5;
return Conf.domain.resCdn + md5.substring(0, 2) + "/" + md5;
}
replaceVTX(_str: string): string {
let str: string = _str;
//TODO:工具转义有错误,问问工具改还是不改,做了容错。
let regV = /(\\|\/)[Vv]\[([0-9]+)]/;
let regT = /(\\|\/)[Tt]\[([0-9]+)]/;
let regX = /(\\|\/)[Xx]\[([0-9]+)]/;
let reg_val = /(\d+)/;
let regv_val: Array<any> = str.match(regV);
let regt_val: Array<any> = str.match(regT);
let regx_val: Array<any> = str.match(regX);
let val: Array<any>;
if (regv_val) {//替换所有数值
val = regv_val[0].match(reg_val);
if (val) {
_str = _str.replace(regV, this.vDic.get(val[0] - 1));
}
} else if (regt_val) {//替换所有字符串
val = regt_val[0].match(reg_val);
if (val) {
_str = _str.replace(regT, this.sDic.get(val[0] - 1));
}
} else if (regx_val) {//替换所有二周目
val = regx_val[0].match(reg_val);
_str = _str.replace(regX, this.exVDic.get(val[0] - 1));
}
if (str != _str) {
str = this.replaceVTX(_str);
}
regV = null;
regT = null;
regX = null;
reg_val = null;
regv_val = null;
regt_val = null;
regx_val = null;
return str;
}
get help() {
return console.log(
"conf.debug: boolean = [boolean] on //调试模式开关 ps.发布时关掉",
"\ndh.cmdLine.reporter.showState = [boolean] on //状态机log",
"\ndh.cmdLine.reporter.showProcess = [boolean] on //开关执行过程log",
"\ndh.cmdLine.printCmdArr() //打印当前scene详情, 相关事件(206:跳转剧情 / 251:呼叫子剧情)",
"\ndh.story.gotoChapter([chapterId]) //跟据剧情ID跳转到scene",
"\ndh.cmdLine.state.switchState([number] state) //设置播放状态,0:正常、1:自动、2:快进",
"\nshortcut:\"s\"//开关state面板; \"n\"//单步步进; \"z\"//快进",
"\n@ OPlayer:27 new BinLoader([boolean] local?) //开启本地数据模式,文件置于oplayer/local,默认不开启"
);
}
};
/*
* dispatchEvent(new CustomEvent(Conf.EVN_READY, {"detail": this.bufArr.length == 1}));
* addEventListener(Conf.EVN_READY, this.init)
*/
<file_sep>import Sprite = laya.display.Sprite;
import Stat = laya.utils.Stat;
import Event = laya.events.Event;
import Stage = laya.display.Stage;
import Conf from "../../data/Conf";
import DH from "../../data/DH";
import UILayer from "./view/layer/UILayer";
import GameLayer from "./view/layer/GameLayer";
import {Cmd} from "../../data/sotry/Story";
import FloatLayer from "./view/layer/FloatLayer";
import {Layer} from "./view/layer/Layer";
import {IMgr} from "./Mgr";
/**
* Created by Lonmee on 4/23/2017.
*/
export class ViewMgr extends Sprite implements IMgr {
gl: GameLayer;
ul: UILayer;
fl: FloatLayer;
layerArr: Layer[] = [
this.gl = new GameLayer(),
this.ul = new UILayer(),
this.fl = new FloatLayer()
];
dh: DH = DH.instance;
constructor() {
super();
this.initStage();
this.initListener();
}
initStage() {
if (Conf.frameworks.bgColor) {
Laya.stage.bgColor = Conf.frameworks.bgColor;
}
if (Conf.frameworks.showStatus) {
Stat.show();
}
Laya.stage.scaleMode = Stage.SCALE_SHOWALL;
Laya.stage.alignH = Stage.ALIGN_CENTER;
Laya.stage.alignV = Stage.ALIGN_MIDDLE;
Laya.stage.addChild(this);
for (let layer of this.layerArr)
this.addChild(layer);
}
initListener() {//系统用交互事件总代
this.stage.on(Event.KEY_DOWN, this, this.kdHandler);
this.stage.on(Event.KEY_UP, this, this.kuHandler);
this.stage.on(Event.BLUR, this, this.blurHandler);
this.stage.on(Event.RIGHT_CLICK, this, this.rcHandler);
this.dh.eventPoxy.on(Conf.LOADING_PROGRESS, this, this.progress);
}
rcHandler(e: Event) {
this.dh.eventPoxy.event(e.type);
}
kdHandler(e: Event) {
switch (e.nativeEvent.code) {
case "KeyS":
Conf.frameworks.showStatus ? Stat.hide() : Stat.show();
Conf.frameworks.showStatus = !Conf.frameworks.showStatus;
break;
case "KeyN":
this.dh.eventPoxy.event(Conf.ITEM_CHOSEN);
break;
case "KeyZ":
this.dh.eventPoxy.event(Conf.STATE_FF);
break;
case "Escape":
this.dh.eventPoxy.event(e.type);
break;
}
}
kuHandler(e: Event) {
switch (e.nativeEvent.code) {
case "KeyZ":
this.dh.eventPoxy.event(Conf.STATE_CANCEL);
break;
}
}
blurHandler(e: Event) {
this.dh.eventPoxy.event(Conf.STAGE_BLUR);
}
/**
* 加载进度回调
* @param f
* @param p
*/
progress(f: string, p: number) {
// f = f.replace(/(.*\/){0,}([^\.]+).*/ig, "$2");
// console.log(`loading ${f} ${Math.floor(p * 100)}`);
}
/**
* 对cmd进行分流,ui、浮层、游戏
* @param cmd
*/
exe(cmd: Cmd) {
switch (cmd.code) {
//UI控制指令
case 150: //"刷新UI画面"
break;
case 151: //"返回游戏界面"
this.swapUlFl();
break;
case 208: //"返回标题画面"
case 214: //"呼叫游戏界面"
this.swapUlFl("u");
break;
case 218: //"强制存档读档"
break;
case 110: //"打开指定网页";
break;
case 111: //"禁用开启菜单功能";
// UI交互类 & UI控制指令:this.ul.exe(cmd);
// 悬浮组件:this.fl.exe(cmd);
// 视图操作命令:this.gl.exe(cmd);
}
for (let i = this.layerArr.length; i > 0;) {
this.layerArr[--i].exe(cmd);
}
}
update(speed: number) {
for (let i = this.layerArr.length; i > 0;) {
this.layerArr[--i].update(speed);
}
}
swapUlFl(layer: string = "") {
this.addChild(layer == "u" ? this.ul : this.fl);
}
reset() {
for (let i = this.layerArr.length; i > 0;) {
this.layerArr[--i].reset();
}
}
}<file_sep>import Sprite = laya.display.Sprite;
import Event = laya.events.Event;
import Text = laya.display.Text;
import DH from "../../../../../data/DH";
import {Button} from "./Comp";
import Conf from "../../../../../data/Conf";
import {Cmd} from "../../../../../data/sotry/Story";
import Layouter from "./Layouter";
/**
* Created by ShanFeng on 6/2/2017.
*/
export interface ISelectable {
links: number[]
para: string[]
}
export class Selector extends Sprite implements ISelectable {
links: number[];
para: string[];
constructor(cmd: Cmd) {
super();
this.links = cmd.links;
this.para = cmd.para;
this.autoSize = true;
this.initView();
this.layout();
}
protected initView() {
for (let i = 0; i < this.para.length; i++) {
let db = DH.instance.story.sys.Buttons[DH.instance.story.sys.MessageBox.choiceButtonIndex];
if (db.image1.path != "" || db.image1.path != "") {
let btnV: Button = new Button(parseInt(DH.instance.story.sys.MessageBox.choiceButtonIndex), (e: Event) => this.clickHandler(e));
btnV.idx = i;
btnV.y = i * (btnV.height + 10);
let txt: Text = new Text();
txt.fontSize = 22;
txt.color = "#FFFFFF";
txt.text = this.para[i];
txt.x = btnV.width - txt.width >> 1;
txt.y = btnV.height - txt.height >> 1;
btnV.addChild(txt);
this.addChild(btnV);
}
}
}
protected layout() {
Layouter.center(this);
}
protected clickHandler(e: Event) {
DH.instance.eventPoxy.event(Conf.ITEM_CHOSEN, this.links[e.target['idx']]);
this.parent.removeChild(this);
this.destroy(true);
}
}
export class SelectorEx extends Selector {
constructor(cmd: Cmd) {
super(cmd);
}
protected initView(): any {
for (let i = 0; i < this.links.length; i++) {
let db = DH.instance.story.sys.Buttons[DH.instance.story.sys.MessageBox.choiceButtonIndex];
if (db.image1.path != "" || db.image1.path != "") {
let btnV: Button = new Button(parseInt(DH.instance.story.sys.MessageBox.choiceButtonIndex), (e: Event) => this.clickHandler(e));
btnV.idx = i;
btnV.y = i * (btnV.height + 10);
let txt: Text = new Text();
txt.fontSize = 22;
txt.color = "#FFFFFF";
txt.text = this.para[9 + i * 2];
txt.pos(btnV.width - txt.width >> 1, btnV.height - txt.height >> 1);
btnV.addChild(txt);
this.addChild(btnV);
}
}
}
}
export class SelectorEx2 extends Selector {
constructor(cmd: Cmd) {
super(cmd);
}
protected initView(): any {
for (let i = 0; i < this.links.length; i++) {
let db = DH.instance.story.sys.Buttons[DH.instance.story.sys.MessageBox.choiceButtonIndex];
if (db.image1.path != "" || db.image1.path != "") {
let btnV: Button = new Button(parseInt(DH.instance.story.sys.MessageBox.choiceButtonIndex), (e: Event) => this.clickHandler(e));
btnV.idx = i;
btnV.y = i * (btnV.height + 10);
let txt: Text = new Text();
txt.fontSize = 22;
txt.color = "#FFFFFF";
txt.text = this.para[15 + i * 3];
txt.pos(btnV.width - txt.width >> 1, btnV.height - txt.height >> 1);
btnV.addChild(txt);
this.addChild(btnV);
}
}
}
}
export class BtnSelector extends Selector {
constructor(cmd: Cmd) {
super(cmd);
}
protected initView() {
let idx: number = 0;
for (let bStr of this.para) {
let para: string[] = bStr.split(',');
let db: any = DH.instance.story.sys.Buttons[para[0]];
if (db.image1.path == "" && db.image1.path == "")
continue;
let btnV: Button = new Button(parseInt(para[0]), (e: Event) => this.clickHandler(e));
btnV.idx = idx++;
btnV.x = parseInt(para[1]);
btnV.y = parseInt(para[2]);
this.addChild(btnV);
}
}
protected layout() {
//按钮分歧使用绝对坐标
}
}<file_sep>import Dictionary = laya.utils.Dictionary;
/**
* Created by ShanFeng on 6/13/2017.
*/
export interface IBindable {
watcher: Function[][];
bind(key, fun);
unbind(key, fun);
}
class ODic extends Dictionary implements IBindable {
watcher: Function[][] = [];
bind(key, fun) {
if (this.watcher[key])
this.watcher[key].push(fun);
else
this.watcher[key] = [fun];
}
unbind(key, fun = null) {
let wk;
if (wk = this.watcher[key])
if (fun == null || wk.length == 1)
this.watcher[key] = null;
else
wk.splice(wk.indexOf(fun), 1);
}
get(key: any): any {
return super.get(parseInt(key) + 1);
}
set(key: any, value: any): void {
super.set(parseInt(key) + 1, value);
if (this.watcher[key])
for (let fun of this.watcher[key])
fun.call(null, value);
}
}
export class DigitalDic extends ODic {
get(key: any): any {
if (super.get(parseInt(key)) == null)
this.set(key, 0);
return super.get(key);
}
set(key: any, value: any): void {
super.set(key, parseInt(value));
}
}
export class StringDic extends ODic {
get(key: any): any {
let t = super.get(key);
return t ? t : "";
}
}<file_sep>import Sprite = laya.display.Sprite;
import Texture = laya.resource.Texture;
/**
* Created by ShanFeng on 6/6/2017.
*/
export default class Layouter {
static top(s: Sprite, t: Texture = null) {
Layouter.align(s, 2, t);
}
static center(s: Sprite, t: Texture = null) {
Layouter.align(s, 5, t);
}
static bottom(s: Sprite) {
Layouter.align(s, 8);
}
static align(s: Sprite, no: number, t: any = null) {
if (t == null)
t = s;
switch (no) {
case 1:
s.pos(0, 0);
break;
case 2:
s.pos(Laya.stage.width - t.width >> 1, 0);
break;
case 3:
s.pos(Laya.stage.width - t.width, 0);
break;
case 4:
s.pos(0, Laya.stage.height - t.height >> 1);
break;
case 5:
s.pos(Laya.stage.width - t.width >> 1, Laya.stage.height - t.height >> 1);
break;
case 6:
s.pos(Laya.stage.width - t.width, Laya.stage.height - t.height >> 1);
break;
case 7:
s.pos(0, Laya.stage.height - t.height);
break;
case 8:
s.pos(Laya.stage.width - t.width >> 1, Laya.stage.height - t.height);
break;
case 9:
s.pos(Laya.stage.width - t.width, Laya.stage.height - t.height);
}
}
}<file_sep>import Dictionary = laya.utils.Dictionary;
import {Cmd} from "../../../../data/sotry/Story";
import {Layer} from "./Layer";
import {GameImg} from "../ui/comp/Comp";
/**
* Created by ShanFeng on 5/16/2017.
*/
export default class GameLayer extends Layer {
imgDic: Dictionary = new Dictionary();
constructor() {
super();
this.dh.imgDic = this.imgDic;
}
exe(cmd: Cmd) {
switch (cmd.code) {
case 106: //"提示消息框"
case 107: //"注释"
case 219: //"气泡式效果"
case 301: //"天气"
case 302: //"震动"
case 303: //"画面闪烁"
case 304: //"准备转场"
case 305: //"转场开始"
case 306: //"更改场景色调"
case 307: //"插入到BGM鉴赏"
case 308: //"插入到CG鉴赏"
break;
case 400: //"显示图片"
let gi: GameImg;
let imgId = parseInt(cmd.para[0]);
let x = cmd.para[2] == "0" ? parseInt(cmd.para[3]) : this.getValue(cmd.para[3]);
let y = cmd.para[2] == "0" ? parseInt(cmd.para[4]) : this.getValue(cmd.para[4]);
let other = cmd.para.length > 11 && cmd.para[11] == "1";
let url = other ? this.dh.replaceVTX(this.dh.sDic.get(cmd.para[12])) : cmd.para[1];
if (this.imgDic.indexOf(imgId) > -1) {
gi = this.imgDic.get(imgId);
gi.reload(url, other).pos(x, y);
}
else {
this.imgDic.set(imgId, gi = new GameImg(url, other));
this.addChild(gi.pos(x, y));
gi.zOrder = imgId;
}
gi.alpha = parseInt(cmd.para[7]) / 255;
gi.scaleX = cmd.para[8] == "1" ? -parseInt(cmd.para[5]) / 100 : parseInt(cmd.para[5]) / 100;
gi.scaleY = parseInt(cmd.para[6]) / 100;
break;
/*
0:图片ID 1/2/23 远景 背景 前景 3~22 立绘
1:图片相对路径
2:坐标为常量或数值(0,1)
3:x坐标
4:y坐标
5:x缩放率
6:y缩放率
7:不透明度
8:是否镜像(1,0)
9:显示信息
10 网盘还是本地
【11 是否为字符串指定(1,0) 12 字符串索引】*/
case 401: //"淡出图片"
if (this.imgDic.indexOf(cmd.para[0]) > -1) {
this.imgDic.get(cmd.para[0]).destroy(true);
this.imgDic.remove(cmd.para[0]);
}
break;
case 402: //"移动图片"
// 0:图片ID
// 1:图片相对路径
// 2:坐标为常量或数值(0,1)
// 3:x坐标
// 4:y坐标
// 5:x缩放率
// 6:y缩放率
// 7:不透明度
// 8:是否镜像(1,0)
// 9:时间
// 10:显示信息
let i = this.getImg(cmd.para[0]);
if (i) {
let t = parseInt(cmd.para[9]);//time
// i.moveTo("x", cmd.para[2] == "0" ? parseInt(cmd.para[3]) : this.getValue(cmd.para[3]), t);
// i.moveTo("y", cmd.para[2] == "0" ? parseInt(cmd.para[4]) : this.getValue(cmd.para[4]), t);
// i.moveTo("alpha", parseInt(cmd.para[7]) / 255, t);
// i.moveTo("scaleX", cmd.para[8] == "1" ? -parseInt(cmd.para[5]) / 100 : parseInt(cmd.para[5]) / 100, t);
// i.moveTo("scaleY", parseInt(cmd.para[6]) / 100, t);
let tx = cmd.para[2] == "0" ? parseInt(cmd.para[3]) : this.getValue(cmd.para[3]);//x
if (i.x != tx)
i.moveTo("x", tx, t);
let ty = cmd.para[2] == "0" ? parseInt(cmd.para[4]) : this.getValue(cmd.para[4]);//y
if (i.y != ty)
i.moveTo("y", ty, t);
let a = parseInt(cmd.para[7]) / 255;//alpha
if (i.alpha != a)
i.moveTo("alpha", a, t);
let tsX = cmd.para[8] == "1" ? -parseInt(cmd.para[5]) / 100 : parseInt(cmd.para[5]) / 100;//scaleX
if (i.scaleX != tsX)
i.moveTo("scaleX", tsX, t);
let tsY = parseInt(cmd.para[6]) / 100;//scaleY
if (i.scaleY != tsY)
i.moveTo("scaleY", tsY, t);
}
break;
case 403: //"显示心情"
case 404: //"旋转图片"
case 406: //"显示动态图片"
case 407: //"变色"
}
}
getImg(key) {
return this.imgDic.get(key);
}
getValue(key) {
return this.dh.vDic.get(key);
}
update(speed: number) {
for (let c of this._childs)
c.update(speed);
}
};
/*
this.spr = new Sprite();
this.spr.graphics.drawTexture(e);
this.spr.x = this.spr.y = 400;
Laya.stage.addChild(this.spr);
Laya.timer.loop(10, this, this.animateTimeBased);
Laya.timer.frameLoop(1, this, this.animateFrameRateBased);
*/<file_sep>import {IMgr} from "../../Mgr";
import {Cmd} from "../../../../data/sotry/Story";
import Sprite = laya.display.Sprite;
import DH from "../../../../data/DH";
import UIFac from "../ui/UIFac";
/**
* Created by ShanFeng on 5/31/2017.
*/
export class Layer extends Sprite implements IMgr {
protected uiFac: UIFac = new UIFac();
protected dh: DH = DH.instance;
exe(cmd: Cmd) {
}
update(delay: number = 1) {
}
reset() {
while (this.numChildren) {
this.removeChildAt(0);
}
}
}<file_sep>import {DFLayer} from "../../../../../data/sotry/Story";
import {OtherImg} from "./Comp";
import Sprite = laya.display.Sprite;
import Event = laya.events.Event;
import DH from "../../../../../data/DH";
import Chapter from "../../../../cmd/chapter/Chapter";
/**
* Created by ShanFeng on 6/9/2017.
*/
export default class FLayer extends Sprite {
constructor(data: DFLayer[]) {
super();
this.autoSize = true;
this.initView(data);
}
initView(data) {
for (let fd of data) {
this.addChild(new FloatElement(fd));
}
}
}
export class FloatElement extends Sprite {
chapter: Chapter;
constructor(private eleData) {
super();
this.chapter = eleData.cmdArr == 0 ? null : new Chapter({id: NaN, name: "float", cmdArr: eleData.cmdArr});
this.autoSize = true;
this.initView();
}
initView() {
for (let e of this.eleData.itemArr) {
let i;
switch (e.type) {
case 0://图片todo:字符串加载图片
i = new OtherImg(e.useStr ? DH.instance.sDic.get(e.varIdx) : e.image);
i.autoSize = true;
this.pos(e.x, e.y);
this.addChild(i);
this.on(Event.CLICK, this, this.exe);
break;
case 1://字符串
break;
case 2://数值
break;
}
}
}
exe(e:Event) {
// e.stopPropagation();
DH.instance.cmdLine.insertChapter(this.chapter);
}
}
|
461629c5486c8ba267c6d4cf6fa25bdf286b0a53
|
[
"JavaScript",
"TypeScript"
] | 38
|
TypeScript
|
Lonmee/OPlayer
|
7a301a2978d237f5cad8ab09b23c4c711871d8ee
|
77d97960b20b6bc6b5fa96ca1763866768f4f2c2
|
refs/heads/master
|
<repo_name>Jobsity/avivir<file_sep>/sites/all/themes/asociacionvivir/js/asociacionvivir.behaviorsb79e.js
(function ($) {
/**
* The recommended way for producing HTML markup through JavaScript is to write
* theming functions. These are similiar to the theming functions that you might
* know from 'phptemplate' (the default PHP templating engine used by most
* Drupal themes including Omega). JavaScript theme functions accept arguments
* and can be overriden by sub-themes.
*
* In most cases, there is no good reason to NOT wrap your markup producing
* JavaScript in a theme function.
*/
Drupal.theme.prototype.asociacionvivirExampleButton = function (path, title) {
// Create an anchor element with jQuery.
return $('<a href="' + path + '" title="' + title + '">' + title + '</a>');
};
/**
* Behaviors are Drupal's way of applying JavaScript to a page. In short, the
* advantage of Behaviors over a simple 'document.ready()' lies in how it
* interacts with content loaded through Ajax. Opposed to the
* 'document.ready()' event which is only fired once when the page is
* initially loaded, behaviors get re-executed whenever something is added to
* the page through Ajax.
*
* You can attach as many behaviors as you wish. In fact, instead of overloading
* a single behavior with multiple, completely unrelated tasks you should create
* a separate behavior for every separate task.
*
* In most cases, there is no good reason to NOT wrap your JavaScript code in a
* behavior.
*
* @param context
* The context for which the behavior is being executed. This is either the
* full page or a piece of HTML that was just added through Ajax.
* @param settings
* An array of settings (added through drupal_add_js()). Instead of accessing
* Drupal.settings directly you should use this because of potential
* modifications made by the Ajax callback that also produced 'context'.
*/
Drupal.behaviors.asociacionvivirExampleBehavior = {
attach: function (context, settings) {
// By using the 'context' variable we make sure that our code only runs on
// the relevant HTML. Furthermore, by using jQuery.once() we make sure that
// we don't run the same piece of code for an HTML snippet that we already
// processed previously. By using .once('foo') all processed elements will
// get tagged with a 'foo-processed' class, causing all future invocations
// of this behavior to ignore them.
$('.some-selector', context).once('foo', function () {
// Now, we are invoking the previously declared theme function using two
// settings as arguments.
var $anchor = Drupal.theme('asociacionvivirExampleButton', settings.myExampleLinkPath, settings.myExampleLinkTitle);
// The anchor is then appended to the current element.
$anchor.appendTo(this);
});
}
};
$.fn.triangle = function (options) {
var defaults = {
leftHeight: 30, //height of top triangle
offset: 0, //width + offset in top trinagle
rightWidth: 55, //width of right triangle
breakpoint: 944, //hide the right triangle
tRight: false //show the right triangle
//color: color of triangle
//target: element with triangle on top
}
var options = $.extend(defaults, options);
var cssCommon = {
'background': 'transparent',
'border-style': 'solid',
'-moz-transform': 'scale(.9999)',
'width': 10,
'height': 2,
'position': 'absolute',
'z-index': 50
};
this.each(function () {
var o = options;
var el = $(this);
var color = o.color ? o.color : el.css('background-color');
var target = o.target ? o.target : el;
el.prepend('<div id="triangle_right"></div>');
el.prepend('<div id="triangle_top"></div>');
var draw = function () {
var elWidth = el.outerWidth();
var elHeight = el.outerHeight();
var elPaddingTop = parseInt(el.css('padding-top').replace("px", ""));
var elPaddingLeft = parseInt(el.css('padding-left').replace("px", ""));
if ($(window).outerWidth() < o.breakpoint) {
display = 'none';
offset = 0;
} else {
display = 'inherit';
offset = o.offset + o.rightWidth;
}
if (o.tRight) {
var e_right = $("#triangle_right", el).css(cssCommon)
.css({
'border-color': color + ' transparent transparent transparent',
'border-width': elHeight + 'px ' + o.rightWidth + 'px 0px 0px',
'margin-top': '-' + (elPaddingTop) + 'px',
'margin-left': elWidth - elPaddingLeft - 10 + 'px',
'display': display
});
}
;
var e_top = $("#triangle_top", el).css(cssCommon)
.css({
'border-color': 'transparent transparent transparent ' + color,
'border-width': o.leftHeight + 'px 0px 0px ' + (elWidth + o.offset + offset) + 'px',
'margin-top': '-' + (o.leftHeight + elPaddingTop) + 'px',
'margin-left': '-' + elPaddingLeft + 'px'
});
}
$(window).resize(draw);
draw();
return el;
});
};
$.fn.closeButton = function (options) {
var o = $.extend(options);
this.each(function () {
var el = $(this);
var ref = $(o.ref);
var position = function () {
var ref_top = ref.offset().top - parseInt(ref.css('padding-top').replace("px", "")) - o.offset;
el.css({
'position': 'absolute',
'top': ref_top,
'z-index': 100,
});
}
$(window).resize(position);
position();
return el;
});
};
$.fn.adjustImage = function (options) {
var options = $.extend(options);
this.each(function () {
var o = options;
var el = $(this);
var ref = $(o.ref);
var img = $("img", el);
var imgParent = img.parent().css({
'overflow': 'hidden'
});
var center = function () {
el.height(0);
var refHeight = ref.outerHeight();
el.height(refHeight + 1);
//make image wrap to have the same height than the ref object
img.css({
'height': refHeight + 2,
'width': 'auto'
});
//Check that the width of image >= wrapper
if (img.outerWidth() < el.outerWidth()) {
img.css({
'height': 'auto',
'width': el.outerWidth() + 2
});
}
//center the image
if ($(window).outerWidth() > 959) { //mobile breakpoint in 960px
var offsetLeft = (el.outerWidth() - img.outerWidth()) / 2;
offsetLeft = offsetLeft < 0 ? offsetLeft : 0;
var offsetTop = (el.outerHeight() - img.outerHeight()) / 2;
offsetTop = offsetTop > 0 ? offsetTop : 0;
img.css({
'margin-top': -offsetTop,
'margin-left': offsetLeft
});
}
}
$(window).resize(center);
center();
return el;
});
};
function map() { //-0.2115,-78.4146667
var markerPos = $(".node-type-como-llegar .field--name-field-marker-position .field__item").text();
var markerPosLat = parseFloat(markerPos.split(',')[0]);
var markerPosLong = parseFloat(markerPos.split(',')[1]);
var mapZoom = parseInt($(".node-type-como-llegar .field--name-field-map-zoom .field__item").text());
var horOffset = (0.0011 * $(".node-type-como-llegar .l-page").outerHeight()) / 1140;
//console.log(markerPosLat + "/" + markerPosLong + "/" + mapZoom);
//Create the map
var mapCanvas = document.getElementById($('.node-type-como-llegar .map')[0].id);
var latitude = markerPosLat, //centerPosLat,
longitude = markerPosLong + horOffset, //centerPosLong,
map_zoom = mapZoom//16;
//google map custom marker icon - .png fallback for IE11
var is_internetExplorer11 = navigator.userAgent.toLowerCase().indexOf('trident') > -1;
var marker_url = (is_internetExplorer11) ? '/sites/all/themes/asociacionvivir/images/map-selector.png' : '/sites/all/themes/asociacionvivir/images/map-selector.svg';
var map_options = {
center: new google.maps.LatLng(latitude, longitude),
zoom: map_zoom,
scrollwheel: false,
disableDefaultUI: true,
styles: [{
stylers: [{
saturation: -100
}]
}]
}
var map = new google.maps.Map(mapCanvas, map_options);
var marker = new google.maps.Marker({
position: {lat: markerPosLat, lng: markerPosLong},
map: map,
visible: true,
title: 'Asociación Vivir',
icon: marker_url,
});
$(window).resize(function () {
map.panTo({lat: latitude, lng: longitude});
});
}
//Shape for page Publicaciones
function publi_triangle() {
var offset = 54;
var heightRef = $(".l-main").outerHeight() + offset;
$(".node-type-publications .border-left").css('border-bottom-width', heightRef);
$(".node-type-publications .border-right").css('border-top-width', heightRef);
return true;
}
//Shape for page Contáctanos
function contact_triangle() {
var offset = 70;
var heightRef = $(".l-main").outerHeight() + offset;
$(".node-type-contactanos .bg-left-panel").css('border-bottom-width', heightRef);
$(".node-type-contactanos .bg-right-panel").css('border-top-width', heightRef);
return true;
}
function homepage() {
var panelsContainer = $(".node-type-home-page .view-content");
var panels = $(".views-row", panelsContainer);
$.each(panels, function() {
var panel = $(this);
var color = $(".views-field-field-color .field-content", panel).text();
var realColor = 'gray';
switch(color) {
case 'Orange':
realColor = '#F1783C';
break;
case 'Blue':
realColor = '#3598C0';
break;
case 'Ocre':
realColor = '#906D46';
break;
}
panel.css('background-color', realColor);
});
var initPage = $(".node-type-home-page .pane-node-field-description");
var homePage = $(".node-type-home-page .pane-home-page-inside");
var verMas = $(".node-type-home-page .ver-mas").click(function(){
transition(0);
});
var timeout = parseInt($('.node-type-home-page .pane-node-field-time-out').text());
transition(timeout);
function transition(time) {
setTimeout(function () {
$(".node-type-home-page .l-page").css('margin-top', 0);
$(".node-type-home-page .pane-custom").css('display', 'none');
initPage.fadeOut("slow").css({display: "none"});
homePage.fadeIn("slow").css({display: "inherit"});
}, time * 1000);
}
}
function equalTimelineBorders() {
var el = $(".node-type-event .owl-wrapper-outer");
function setHeight() {
var max = 0;
$('.group-footer', el).each(function() {
$(this).height('');
var h = $(this).height();
max = Math.max(max, h);
}).height(max);
}
$(window).on('load resize orientationchange', setHeight);
}
$(window).resize(function () {
publi_triangle();
});
function init () {
$(".pane-node-field-image").adjustImage({
'ref': '.panel-col-first'
});
$(".node-type-testimonial .pane-node-content, .pane-node-field-timeline, .node-type-profile .pane-node-content").triangle({'tRight': false, 'offset': -30});
$(".panel-col-first").triangle({'tRight': true});
$('.webform-submit').click(function () {
contact_triangle();
});
publi_triangle();
}
$(document).ready(function () {
homepage();
equalTimelineBorders();
map();
init();
});
$(window).load(function() {
$(".pane-node-field-image").adjustImage({
'ref': '.panel-col-first'
});
init();
});
})(jQuery);
|
e38078d0aa6a8cb34d5de370bf543b1b3b9f03c2
|
[
"JavaScript"
] | 1
|
JavaScript
|
Jobsity/avivir
|
11ef6baa5f05e7a9e9d11b74359e3c2efab3eb0c
|
bf2529f4fb6948bf3c703d4491315f1e8caff56b
|
refs/heads/master
|
<file_sep>//Authors
//<NAME>
//<NAME>
//<NAME>
//<NAME>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <errno.h>
size_t str_len(char* s)
{
size_t i;
for(i = 0; ; i++, s++)
if(*s == '\0')
return i;
}
char ManageInput()
{
char c = 0;
system ("/bin/stty raw");
system("/bin/stty -echo");
c = getchar();
system ("/bin/stty cooked");
return c;
}
int myatoi(char *s)
{
int len =str_len(s);
int notLetter = 0;
if (*s == '-') {
fprintf(stderr,"Error: Letters passed as page size argument or a negative or 0 number\n");
exit(-1);
}
int res = 0;
int lastRes=0;
int count=0;
while (count < len)
{
if(! isdigit(*s)){
notLetter=1;
}
lastRes=res;
res = res*10 + (*s++ - '0');
if (lastRes>res){
fprintf(stderr,"Error: Integer limit passed\n");
system("/bin/stty echo");
exit(0);
}
count ++;
}
if(notLetter)
return 0;
else
return res;
}
int one_page(FILE* fd, int max) // Writes one page
{
int c;
int n = 0;
while ((c = getc(fd)) != EOF) {
putc(c, stdout);
if (c == '\n') n++;
if (n >= max) break;
}
char c1;
if((c1 = getc(fd)) == EOF){
system("/bin/stty echo");
exit(0);
}else
ungetc(c1, fd);
return (n);
}
int main(int argc, char** argv)
{
(void)argc;
(void)argv;
int pagesize=24;
int n=0;
bool error=false;
FILE *fp;
char c;
if(argc == 2)
{
fp=fopen(argv[1],"r");
if(fp==NULL){
fprintf(stderr,"Error: File couldn't be read\n");
perror("");
exit(-1);
}
n=one_page(fp,pagesize);
if(n<pagesize){
exit(0);
}
}
else if(argc==3){
fp=fopen(argv[1],"r");
if(fp==NULL){
fprintf(stderr,"Error: File couldn't be read\n");
perror("");
error=true;
}
if((pagesize=myatoi( argv[2] ))==0 ){
fprintf(stderr,"Error: Letters passed as page size argument or a negative or 0 number\n");
error=true;
}
if(error)
exit(-1);
n=one_page(fp,pagesize);
if(n<pagesize){
exit(0);
}
}
else{
fprintf(stderr,"Error: Arguments without correct format \n");
fprintf(stderr,"my_more filename [page_size] \n");
exit(0);
}
while(1)
{
c = ManageInput();
if(c == 3 || c == 4 || c == 'q' || c == 20)
exit(0);
else if(c == 13) //Return
{
n=one_page(fp,1);
if(n==0 ){
system("/bin/stty echo");
exit(0);
}
}
else if(c == ' '){
n=one_page(fp,pagesize);
if(n<pagesize ){
system("/bin/stty echo");
exit(0);
}
}
}
}
<file_sep>#######################################################################
###
### CALCULA ALFA, BETA, GAMMA (PASO FORDWARD 1)
### @params: n (integer)
### @params: nudos (vector)
###
### Devolvemos los vectores alfa, beta, gamma
###
#######################################################################
secure_div <- function(n, d)
{
if(d > 1.0e-8)
return(n/d)
else
return(0)
}
compute_alpha <- function(nodes, k)
{
num <- (nodes[k+4] - nodes[k+3])^2
den <- (nodes[k+4] - nodes[k+1])*(nodes[k+4]-nodes[k+2])
return(secure_div(num, den))
}
compute_beta <- function(nodes, k)
{
num_a <- (nodes[k+3] - nodes[k+1])*(nodes[k+4] - nodes[k+3])
den_a <- (nodes[k+4] - nodes[k+1])*(nodes[k+4] - nodes[k+2])
num_b <- (nodes[k+5] - nodes[k+3])*(nodes[k+3] - nodes[k+2])
den_b <- (nodes[k+5] - nodes[k+2])*(nodes[k+4] - nodes[k+2])
return(secure_div(num_a, den_a) + secure_div(num_b, den_b))
}
compute_gamma <- function(nodes, k)
{
num <- (nodes[k+3] - nodes[k+2])^2
den <- (nodes[k+4] - nodes[k+2])*(nodes[k+5]-nodes[k+2])
return(secure_div(num, den))
}
dame_AlfaBetaGamma <- function (n, nodes) {
alpha <- array(0, dim = n)
beta <- array(0, dim = n)
gamma <- array(0, dim = n)
### alfa[1] == alfa[n] == 0
### gamma[1] == gamma[n] == 0
### beta[1] == beta[n] == 1
### Calcular los vectores alfa, beta, gamma
alpha[1] = 0
alpha[n] = 0
beta[1] = 1
beta[n] = 1
gamma[1] = 0
gamma[n] = 0
for(k in 2:(n-1))
{
alpha[k] = compute_alpha(nodes, k);
beta[k] = compute_beta(nodes, k);
gamma[k] = compute_gamma(nodes, k);
}
res <- NULL
res$alfa <- alpha
res$beta <- beta
res$gamma <- gamma
return(res)
}
<file_sep>// scopy.c
#include <unistd.h>
#include <stdlib.h>
#define BUFFER_SIZE 512
main(int argc, char** argv)
{
int c;
char buf[BUFFER_SIZE];
if(argc == 1)
while ((c = read(0, buf, BUFFER_SIZE)) > 0)
write(1, buf, c);
else
{
write(2, "\x1B[31mToo many parameters\n\x1B[37m", 31);
exit(-1);
}
exit(0);
}
<file_sep>CC=gcc
CFLAGS = -Wall -Wextra -Werror -pedantic -std=c99 -O0
CPPFLAGS= -MMD -MP
LDFLAGS=
LDLIBS=
NAME=sortnumbers
SRC=$(shell find . -name '*.c')
OBJ=${SRC:.c=.o}
DEP=${SRC:.c:.d}
-include ${DEP}
all:${NAME}
${NAME}:${OBJ}
clean:
rm -rf *.o *~ *.gch *.d
rm -f ${DEP}
rm -f sortnumbers
<file_sep>rm *.o *.ali
rm $(find -executable -type f)
<file_sep>//Authors
//<NAME>
//<NAME>
//<NAME>
//<NAME>
#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
int str_cmp(char* a, char* b)
{
while(*a != '\0' && *b != '\0')
if(*(a++) != *(b++))
return 0;
return *a == *b;
}
int throw(char* msg, char* arg)
{
printf("\x1B[31mError: %s%s\n\x1B[37m", msg, arg ? arg : "");
return 1;
}
int main(int argc, char** argv)
{
DIR *d;
int i = 1;
struct dirent *entry;
if(argc == 1)
{
i = 0;
argv[0] = ".";
}
for( ; i < argc ; i++)
{if (argc>2){
printf("%s:\n",argv[i]);
}
d = opendir(argv[i]);
if(!d)
return throw("Invalid directory. You may have passed a file.", NULL);
while( (entry = readdir(d)) != NULL )
{
printf("%lu\t%s\n", entry->d_fileno, entry->d_name);
}
closedir(d);
printf("\n");
}
return 0;
}
<file_sep>package packPasaPalabra;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
public class Lista_Usuarios
{
//Lista de usuarios
ArrayList<Usuario> list;
/**
* @Efecto Construie la lista
**/
public Lista_Usuarios()
{
list = new ArrayList<Usuario>();
}
/**
* @param String name : Nombre del fichero donde guardar la lista
* @Efecto Guarda la lista en un fichero
**/
public void Guardar(String name)
{
try
{
PrintWriter pw = new PrintWriter(name, "UTF-8");
list.forEach(l -> pw.println(l.getNombre() + " " + l.getPuntos()));
pw.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
e.printStackTrace();
return;
}
}
/**
* @param Usuario u : EL usuario que anadir
* @Efecto Anadir el usuario U en la lista
**/
public void Incluir_Usuario(Usuario u)
{
list.add(u);
list.sort((s1, s2) -> s1.getPuntos() - s2.getPuntos());
}
/**
* @Efecto Escribe la lista en la consola
**/
public void Visualizar()
{
list.forEach(l -> System.out.println(l.getNombre() + " " + l.getPuntos()) );
}
}
<file_sep>package packPasaPalabra;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import packPasaPalabra.GeneradorPalabras.ErrorNombreFichero;
import packPasaPalabra.GeneradorPalabras.ErrorPalabrasAgotadas;
public class Program
{
public static void main(String[] args)
{
System.out.println("Pobar GeneradorPalabras :");
ProbarGenerador();
System.out.println("END");
System.out.println("Testing Listas Usuarios");
ProbarListaUsuarios();
System.out.println("END");
}
static void ProbarGenerador()
{
GeneradorPalabras gp = new GeneradorPalabras();
try
{
gp.empezar(2);
} catch (ErrorNombreFichero e)
{
e.printStackTrace();
}
while(true)
{
try
{
String str = gp.darPalabra();
System.out.println(str);
}catch(ErrorPalabrasAgotadas e)
{
System.out.println("[INFO] Nos mas palabras");
break;
}
}
}
static void ProbarListaUsuarios()
{
Lista_Usuarios l = new Lista_Usuarios();
Lista_Usuarios lb = new Lista_Usuarios();
Usuario a = new Usuario("Raymond");
Usuario b = new Usuario("Tusk");
Usuario c = new Usuario("H2G2");
a.setPuntos(6);
b.setPuntos(3);
c.setPuntos(42);
l.Incluir_Usuario(a);
l.Incluir_Usuario(b);
l.Incluir_Usuario(c);
l.Visualizar();
String filename = "output";
System.out.println("Guarda en " + filename);
l.Guardar(filename);
}
}
<file_sep>#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
size_t str_len(char* s)
{
size_t i;
for(i = 0; ; i++, s++)
if(*s == '\0')
return i;
}
int throw(char* msg, char* arg)
{
char* str = "\x1B[31mError: ";
char* strb = "\n\x1B[37m";
write(2, str, str_len(str));
write(2, msg, str_len(msg));
if(arg)
write(2, arg, str_len(arg));
write(2, strb, str_len(strb));
return 1;
}
int main(int argc, char** argv)
{
int i;
int file;
if(argc < 2)
exit(throw("Usage: sdelete <file> [<file> ...]", NULL));
for(i = 1 ; i < argc ; i++)
{
file = open(argv[i], O_RDONLY);
if(file < 0)
{
throw("Unable to remove the file : ", argv[i]);
continue;
}
close(file);
if(chdir(argv[i])==0){
throw("Unable to remove becouse is a directory: ", argv[i]);
continue;
}
if(unlink(argv[i]) < 0)
throw("An error occured with the file", argv[i]);
}
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char data[2048];
while(1)
{
scanf("%s", data);
printf("%s\n", data);
}
return 0;
}
<file_sep>for f in ./*.R; do;
val=$(cat $f | grep -e "CODIGO" -c)
if (( $val != 0)); then
echo "TODO : "$f
fi
done
<file_sep>#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#define BUFFER_SIZE 512
int main(int argc, char** argv)
{
int file;
char buf[BUFFER_SIZE];
int c;
if(argc != 2)
exit( (int)write(2, "Not enough parameters\n", 22) - 1);
file = open(argv[1], O_WRONLY | O_TRUNC | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
if(file == -1)
exit( (int)write(2, "Unable to open file\n", 20) - 1);
while ( (c = read(0, buf, BUFFER_SIZE)) > 0)
{
write(1, buf, c);
write(file, buf, c);
}
close(file);
exit(0);
//return 0;
}
<file_sep>#include "msh.h"
int main(void)
{
pid_t pid;
struct t_cmd cmd;
time_t start;
while(1)
{
cmd = prompt();
wait3(NULL, WNOHANG, NULL);
if(cmd.arg_nbr != 0)
{
if(!(pid = fork()))
{
if(!(pid = fork()))
{
execvp(cmd.arg[0], cmd.arg);
perror("RUN");
}
else
{
start = time(NULL);
if(cmd.max_time == -1)
wait(NULL);
else
{
while(!wait3(NULL, WNOHANG, NULL))
{
if(time(NULL) - start > cmd.max_time)
{
kill(pid, SIGKILL);
break;
}
}
}
if(cmd.background)
printf("Child %d is gone home.\n%s", pid, PROMPT_NAME);
}
return 0;
}
else if(pid < 0)
exit(printf("ERROOOOOR END OT ZE WORLD\n"));
else if(!cmd.background)
wait(NULL);
}
}
return 0;
}
<file_sep>package hello;
class siete
{
public static int sum_vect(int data[])
{
int sum = 0;
for(int i = 0 ; i < 10 ; i++)
sum += data[i];
return sum;
}
public static int moy_vect(int data[])
{
return sum_vect(data) / 10;
}
public static int min_vect(int data[])
{
int min = data[0];
for(int i = 1 ; i < 10 ; i++)
min = min > data[i] ? data[i] : min;
return min;
}
public static int num_zero(int data[])
{
int nb = 0;
for(int i = 0 ; i < 10 ; i++)
nb += data[i] == 0 ? 1 : 0;
return nb;
}
public static void state_vect(int data[])
{
boolean cr = true;
boolean dec = true;
for(int i = 0 ; i < 9 ; i++)
{
cr = cr && data[i] <= data[i+1];
dec = dec && data[i] >= data[i+1];
}
if(cr && dec)
System.out.println("Constant");
else if(cr)
System.out.println("Croissant");
else if(dec)
System.out.println("Decroissant");
else
System.out.println("None");
}
}
<file_sep>package packPasaPalabra;
public class Usuario
{
private String name;
private int grade;
/**
* @param String : Nombre del usuario
* @Efecto Construie el usuario con el nombre, y 0 puntos
**/
public Usuario(String nombre)
{
name = nombre;
grade = 0;
}
/**
* @return String: El nombre
**/
public String getNombre()
{
return name;
}
/**
* @return Int : los puntos
**/
public int getPuntos()
{
return grade;
}
/**
* @param Int puntos : la nueava valor para puntos
* @Efecto El nombre (String)
**/
public void setPuntos(int puntos)
{
grade = puntos;
}
/**
* @return boolean : El usuario tiene mas puntos que 'a' ?
**/
public boolean masPuntos(Usuario a)
{
return grade > a.getPuntos();
}
/**
* @return boolean : el usuario es igual a 'u' ?
**/
public boolean iguales(Usuario u)
{
return name == u.getNombre()
&& grade == u.getPuntos();
}
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
int str_cmp(char* a, char* b)
{
while(*a != '\0' && *b != '\0')
if(*(a++) != *(b++))
return 0;
return *a == *b;
}
int throw(char* msg, char* arg)
{
printf("\x1B[31mError: %s%s\n\x1B[37m", msg, arg ? arg : "");
return 1;
}
int visit_directory(char* path)
{
DIR *d;
struct dirent *entry;
struct stat buf;
struct tm *atime;
struct tm *mtime;
char cwd[1024];
getcwd(cwd, 1024);
if(chdir(path))
{
perror(path);
return 1;
}
d = opendir(".");
if(!d)
return throw("Error opening folder current folder", NULL);
while( (entry = readdir(d)) != NULL )
{
if(lstat(entry->d_name, &buf))
return throw("Error reading file attributes", NULL);
atime = localtime(&buf.st_atime);
mtime = localtime(&buf.st_mtime);
printf("%s%s%s%s%s%s%s%s%s%s %lu %lu\t%d/%d/%d %d:%d\t%d/%d/%d %d:%d %s\n",
((buf.st_mode & S_IFLNK) ? "l" :
(buf.st_mode & S_IFDIR) ? "d" : "-"),
(buf.st_mode & S_IRUSR) ? "r" : "-",
(buf.st_mode & S_IWUSR) ? "w" : "-",
(buf.st_mode & S_IXUSR) ? "x" : "-",
(buf.st_mode & S_IRGRP) ? "r" : "-",
(buf.st_mode & S_IWGRP) ? "w" : "-",
(buf.st_mode & S_IXGRP) ? "x" : "-",
(buf.st_mode & S_IROTH) ? "r" : "-",
(buf.st_mode & S_IWOTH) ? "w" : "-",
(buf.st_mode & S_IXOTH) ? "x" : "-",
buf.st_nlink,
buf.st_size,
atime->tm_mday,
atime->tm_mon + 1,
atime->tm_year + 1900,
atime->tm_hour,
atime->tm_min,
mtime->tm_mday,
mtime->tm_mon + 1,
mtime->tm_year + 1900,
mtime->tm_hour,
mtime->tm_min,
entry->d_name);
}
closedir(d);
chdir(cwd);
return 0;
}
int main(int argc, char** argv)
{
int i = 1;
if(argc == 1)
{
i = 0;
argv[0] = ".";
}
for( ; i < argc ; i++)
{
if(argc > 2)
printf("%s:\n", argv[i]);
int e = visit_directory(argv[i]);
if(!e)
continue;
if(argc > 2)
printf("\n");
}
printf("\n");
return 0;
}
<file_sep>package hello;
import java.awt.*;
import java.awt.event.*;
class Main
{
public static void main(String[] args)
{
System.out.println("Begin table");
Board b = new Board(5,5);
b.Display();
b.Set(5);
int data[] = {9,8,7,6,5,4,3,2,1,0};
System.out.println(
"MIN: " + siete.min_vect(data)
+ "\nNumZero: " + siete.num_zero(data)
+ "\nMoy: " + siete.moy_vect(data)
+ "\nSum: " + siete.sum_vect(data));
siete.state_vect(data);
}
}
<file_sep>CC = clang -fsanitize=address
CFLAGS += -std=c99 -Wall -Wextra -Werror -pedantic
CFLAGS += -g -O0
CFLAGS += -I.
DEPFLAGS = -MT $@ -MMD -MP -MF .deps/$*.d
SRC = $(shell find . -name '*.c')
OBJ = $(SRC:.c=.o)
all:my_echo
clean:
rm -rf -- .deps
rm -f -- ${OBJ}
rm -f my_echo
<file_sep>$files="display.c main.c"
clang -fsanitize=address -g -Wall -Wextra -Werror \
-pedantic -O3 $files -o $output && echo "GCC..."
gcc $files -o $output && echo "ok";
<file_sep>javac $(find hello/ -name "*.java") &&
java hello.Main
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#define ARG_NBR 2
#define ARG_NBR_MSG "Wrong number of parameters\n"
#define FILE_STAT_MSG "Unable to read file stats"
int main(int argc, char** argv)
{
struct stat fileInfoA;
struct stat fileInfoB;
if(argc < ARG_NBR + 1 || argc > ARG_NBR + 1)
return printf(ARG_NBR_MSG) - 1;
if(stat(argv[1], &fileInfoA) || stat(argv[2], &fileInfoB))
return printf(FILE_STAT_MSG) - 1;
return fileInfoA.st_mode != fileInfoB.st_mode;
}
<file_sep>//Authors
//<NAME>
//<NAME>
//<NAME>
//<NAME>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
size_t str_len(char* s)
{
size_t i;
for(i = 0; ; i++, s++)
if(*s == '\0')
return i;
}
int throw(char* msg, char* arg)
{
char* str = "\x1B[31mError: ";
char* strb = "\n\x1B[37m";
write(2, str, str_len(str));
write(2, msg, str_len(msg));
if(arg)
write(2, arg, str_len(arg));
write(2, strb, str_len(strb));
return 1;
}
int main(int argc, char** argv)
{
int i;
if(argc < 3)
exit(throw("Usage: many_names <file> <file> [<file> ...]", NULL));
for(i = 2 ; i < argc ; i++)
if(link(argv[1],argv[i]) < 0)
perror("");
return 0;
}
<file_sep>// ccopy.c
#include <stdio.h>
#include <stdlib.h>
main(int argc, char *argv[])
{
int c;
if(argc == 1)
while ((c = getchar()) != EOF)
putchar(c);
else
{
fprintf(stderr, "\x1B[31mToo many arguments !\n\x1B[37m");
exit(-1);
}
exit(0);
}
<file_sep>#######################################################################
###
### CALCULA X (PASO BACKWARD)
### @params: delta (data.frame)
### @params: lambda (vector)
###
### Devolvemos X (data.frame)
###
#######################################################################
dame_X <- function (delta, lambda) {
### Calcular X
n = length(lambda)
#X <- array(0, n);
X <- data.frame(x=double(), y=double())
lastX = delta$x[n];
lastY = delta$y[n];
X = rbind( data.frame(x=lastX, y=lastY), X);
for(i in (n-1):1)
{
lastX = delta$x[i] - lambda[i]*lastX;
lastY = delta$y[i] - lambda[i]*lastY;
X = rbind( data.frame(x=lastX, y=lastY), X);
}
return(X)
}
<file_sep>Rscript programaBspline.R
<file_sep>/* clock.h */
#include <signal.h>
void fnull()
{
return;
}
void wait_time(int seconds)
{
signal(SIGALRM, fnull);
alarm(seconds);
pause();
}
<file_sep>CMD=()
CMD+=(-n 10)
CMD+=(-c 10)
CMD+=(-n 10 -c 10)
CMD+=(--version)
CMD+=(--bytes=42 -c 42)
CMD+=(-q)
CMD+=(-v)
FILES=("files/big_file")
FILES+=("files/simple")
for ((j = 1 ; j < 9 ; j++)); do
echo "\nCMD : tail "${CMD[$j]} ${FILES[1]};
./ctail ${CMD[$j]} ${FILES[1]};
done
for ((j = 1 ; j < 9 ; j++)); do
echo "\nCMD : tail "${CMD[$j]} ${FILES[1]} ${FILES[2]};
./ctail ${CMD[$j]} ${FILES[1]} ${FILES[2]};
done
<file_sep>#include "msh.h"
int main(void)
{
pid_t pid;
struct t_cmd cmd;
while(1)
{
cmd = prompt();
if(cmd.arg_nbr != 0)
{
pid = fork();
if(!pid)
{
execvp(cmd.arg[0], cmd.arg);
perror("RUN:");
}
else
{
if(!cmd.background)
wait(NULL);
}
}
}
return 0;
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#define ARG_NBR 2
#define ARG_NBR_MSG "Wrong number of parameters\n"
#define FILE_STAT_MSG "Unable to operate on file.\n"
#define PARSER_MSG "Unable to parse mask.\n"
int posPow(int a, int p)
{
int res = 1;
while(p-- > 1)
res *= a;
return res;
}
int parseMask(char* raw, unsigned int *value)
{
*value = 0;
while(*raw != '\0')
{
if(*raw < '0' && *raw > '9')
return -1;
*value = *value * 10 + (int)(*raw - '0');
raw++;
}
int decimal = 0;
int shift = 1;
int rem;
while(*value != 0)
{
rem = *value % 10;
*value /= 10;
decimal += rem * posPow(8, shift);
shift++;
}
*value = decimal;
return 0;
}
int main(int argc, char** argv)
{
struct stat fileInfo;
if(argc < ARG_NBR + 1 || argc > ARG_NBR + 1)
return printf(ARG_NBR_MSG) + 1;
if(stat(argv[2], &fileInfo))
return printf(FILE_STAT_MSG) + 1;
unsigned int mask;
if(parseMask(argv[1], &mask))
return printf(PARSER_MSG) - 1;
if(chmod(argv[2], mask))
return printf(FILE_STAT_MSG) + 1;
return 0;
}
<file_sep>#ifndef H_DISPLAY
#define H_DISPLAY
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define PROMPT "O_o >"
#define bool int
#define true 1
#define false 0
typedef struct t_console
{
bool error, run, refresh;
int width, height;
char* prompt;
char* output;
size_t output_len;
void (*displayPrompt)(struct t_console*);
void (*flush)(struct t_console*);
void (*displayLoop)(struct t_console*);
void (*registerTyped)(struct t_console*, char);
} Console;
Console* CreateConsole();
void FreeConsole(Console *c);
#endif
<file_sep>// ctee.c
#include <stdio.h>
#include <stdlib.h>
main(int argc, char* argv[])
{
FILE* fd;
int c;
if (argc != 2) {
fprintf(stderr, "Usage: ctee output_file\n");
exit(1);
}
if ((fd = fopen(argv[1], "w")) == NULL) {
fprintf(stderr, "Cannot write in %s\n", argv[1]);
exit(1);
}
while ((c = getc(stdin)) != EOF) {
putc(c, stdout);
putc(c, fd);
}
fclose(fd);
}
<file_sep>FILES+=("exo1")
FILES+=("exo2")
FILES+=("exo3")
FILES+=("exo4")
FILES+=("exo5")
FILES+=("exo6")
FILES+=("exo7")
FILES+=("exo8")
FILES+=("exo9")
nb=9
for ((i = 1 ; i < ($nb+1) ; i++)); do
file=${FILES[$i]} &&
echo "Compiling "${FILES[$i]} &&
rm $file;
clang -fsanitize=address -g -Wall -Wextra -Werror \
-pedantic -O3 $file".c" -o $file &&
gcc $file".c" -o $file;
done;
<file_sep>git add --all
git commit -m "AUTO"
git push
<file_sep>./ctail big_file
echo ""
./stail big_file
echo ""
./ctail big_file 20
echo ""
./stail big_file 20
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#define ARG_NBR 2
#define ARG_NBR_MSG "Wrong number of parameters.\n"
#define GETCWD_MSG "Unable to get the working dir.\n"
#define FILE_STAT_MSG "Unable to read file stats.\n"
#define FILE_STAT_MSG_PAR "Unable to read file stats : %s.\n"
#define OPENDIR_MSG "Unable to open the working dir.\n"
#define PARSER_MSG "Unable to parse the mask.\n"
int contains(char* stack, char* needle)
{
int p_needle = 0;
while(*stack != '\0')
{
if(*stack == needle[p_needle])
p_needle++;
else
{
if(needle[p_needle] == '\0')
return 1;
else
p_needle = 0;
}
stack++;
}
return *stack == needle[p_needle];
}
unsigned int toMask(unsigned int raw)
{
return raw & (S_IRWXU | S_IRWXG | S_IRWXO);
}
int checkFile(char* name, char* needle,
struct stat fileInfo, unsigned int mask)
{
return contains(name, needle)
&& toMask(fileInfo.st_mode) >= mask;
}
int checkDir(int *found, char* needle, unsigned int mask)
{
DIR *dir;
struct stat fileInfo;
char cwd[1024];
struct dirent *e;
if(getcwd(cwd, sizeof(cwd)) == NULL)
return printf(GETCWD_MSG) - 1;
dir = opendir("./");
if(dir == NULL)
return printf(OPENDIR_MSG) - 1;
while((e = readdir(dir)))
{
if(e->d_name[0] == '.' && e->d_name[1] == '.')
continue;
if(e->d_name[0] == '.' && e->d_name[1] == '\0')
continue;
if(lstat(e->d_name, &fileInfo) == -1)
{
printf(FILE_STAT_MSG_PAR, e->d_name);
continue;
}
if(checkFile(e->d_name, needle, fileInfo, mask))
{
(*found)++;
printf("%s/%s - %o\n", cwd, e->d_name, toMask(fileInfo.st_mode));
}
if(!S_ISREG(fileInfo.st_mode))
{
chdir(e->d_name);
checkDir(found, needle, mask);
chdir(cwd);
}
}
closedir(dir);
return 0;
}
int posPow(int a, int p)
{
int res = 1;
while(p-- > 1)
res *= a;
return res;
}
int parseMask(char* raw, unsigned int *value)
{
*value = 0;
while(*raw != '\0')
{
if(*raw < '0' && *raw > '9')
return -1;
*value = *value * 10 + (int)(*raw - '0');
raw++;
}
int decimal = 0;
int shift = 1;
int rem;
while(*value != 0)
{
rem = *value % 10;
*value /= 10;
decimal += rem * posPow(8, shift);
shift++;
}
*value = decimal;
return 0;
}
int main(int argc, char** argv)
{
int found = 0;
unsigned int mask;
if(argc < ARG_NBR + 1 || argc > ARG_NBR + 1)
return printf(ARG_NBR_MSG) + 1;
if(parseMask(argv[2], &mask))
return printf(PARSER_MSG) + 1;
if(checkDir(&found, argv[1], mask))
return 1;
return found == 0;
}
<file_sep>rm $(find . -name "*.ali") $(find . -name *o)
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
void add(size_t* n, size_t *size, size_t value);
int main()
{
size_t* nb = malloc(sizeof(*nb));
size_t size = 1;
size_t i;
*nb = ULONG_MAX - 10;
for(i = 0 ; i < ULONG_MAX - 5 ; i++)
add(nb, &size, ULONG_MAX - 1);
printf("Mediani\n");
//for(i = 0 ; i < ULONG_MAX - 5 ; i++)
add(nb, &size, ULONG_MAX - 1);
for(i = 0 ; i < size ; i++)
printf("[%lu] %020lu\n", i, nb[i]);
free(nb);
return 0;
}
void add(size_t* n, size_t *size, size_t value)
{
size_t pos = 0;
size_t remain;
while(value > 0)
{
if(pos == *size)
n = realloc(n, sizeof(*n) * ++(*size));
remain = ULONG_MAX - n[pos];
if(remain > value)
{
n[pos] = n[pos] + value;
break;
}
else
{
n[pos++] = value - remain;
value = 1;
}
}
}
<file_sep>// ccopy.c
#include <stdio.h>
#include <stdlib.h>
main(int argc, char *argv[])
{
int c;
int i;
FILE *f = NULL;
for(i = 1 ; i < argc ; i++)
{
f = fopen(argv[i], "r");
if(f)
while ((c = fgetc(f)) != EOF)
putchar(c);
else
{
fprintf(stderr, "\x1B[31mnon-existant file : %s\n\x1B[37m",
argv[i]);
exit(1);
}
fclose(f);
}
if(argc == 1)
while ((c = getchar()) != EOF)
putchar(c);
else
{
fprintf(stderr, "\x1B[31mnon-existant file : %s\n\x1B[37m",
argv[i]);
exit(1);
}
exit(0);
}
<file_sep>#ifndef H_PARSING
#define H_PARSING
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#define FALSE 0
#define TRUE 1
/* TODO
- sys_printf
- sys_fread
- sys_fseek
- sys_fopen
- sys_fclose
//return the char at cursor pos, without moving cursor pos
- sys_readptr()
*/
/*
Internal structure describing an argument
id (short name) (ex: -n > n)
name (name) (ex --bytes -> bytes)
has_value : If TRUE, there is a value to parse after (ex: -n 5)
active: Set on parsing: Is argument present on call. FALSE by default.
value: Set on parsing: value given on call. 0 by default.
*/
struct argument
{
char id;
char* name;
char has_value;
char active;
int value;
};
/*
Structure containing parameters
n_files > number of files sent to the program
files > array of filenames given to the programs
n_args > numbers of existing args, active or not
args > array of arguments, internal structure described above;
*/
typedef struct parameters
{
size_t n_files;
char** files;
size_t n_args;
struct argument *args;
}parameters;
/* Is an argument active ? */
char is_active(parameters *p, char* name);
/* Parse the arguments given, and initialize parameters structure */
int parse_arguments(parameters *p, int argc, char** argv);
/* Custom implementation of memcpy (string.h) */
void mem_cpy(void *a, void *b, size_t len)
{
char *p1, *p2;
p1 = (char*)a;
p2 = (char*)b;
for(; len > 0 ; len--)
*p1++ = *p2++;
}
/* Custom implementation of strlen (string.h) */
size_t str_len(char* s)
{
size_t i;
for(i = 0; ; i++, s++)
if(*s == '\0')
return i;
}
/* Custom implementation of strcmp (string.h)
return 0 if NOT equal
return 1 if equal
*/
int str_cmp(char* a, char* b)
{
while(*a != '\0' && *b != '\0')
if(*(a++) != *(b++))
return 0;
return *a == *b;
}
/* Display en error on STDERR with some formating
return 1, to factorize exit
*/
int throw(char* msg, char* arg)
{
char* str = "\x1B[31mError: ";
char* strb = "\n\x1B[37m";
write(2, str, str_len(str));
write(2, msg, str_len(msg));
if(arg)
write(2, arg, str_len(arg));
write(2, strb, str_len(strb));
return 1;
}
/* Cast a string into an integer, save it to value
return 1 on success
return 0 on fail
*/
int tryparse(char* str, int* value)
{
if(*str == '\0')
return 0;
*value = 0;
while(*str != '\0')
if(*str > 47 && *str < 58)
*value = *value * 10 + (int)(*str++ - 48);
else
return 0;
return 1;
}
/* Constructor for parameter class */
parameters* new_parameters()
{
parameters *p = malloc(sizeof(*p));
p->n_files = 0;
p->n_args = 0;
p->args = NULL;
p->files = NULL;
return p;
}
/* Destructor for parameter class */
void free_parameters(parameters *p)
{
size_t i;
for(i = 0 ; i < p->n_files ; i++)
free(p->files[i]);
free(p->files);
for(i = 0 ; i < p->n_args ; i++)
free(p->args[i].name);
free(p->args);
free(p);
}
/* Register a parameter before parsing
id if the single-char name of the arg
name if the long version
has_value : Argument needs a number ?
*/
void add_parameter(parameters *p, char id, char* name, char has_value)
{
p->n_args++;
p->args = realloc(p->args, sizeof(struct argument) * p->n_args);
p->args[p->n_args - 1].name = malloc(sizeof(char) * str_len(name) + 1);;
mem_cpy(p->args[p->n_args - 1].name, name, str_len(name) + 1);
p->args[p->n_args - 1].id = id;
p->args[p->n_args - 1].has_value = has_value;
p->args[p->n_args - 1].active = FALSE;
p->args[p->n_args - 1].value = 0;
}
/* INTERNAL : add file to parameters */
static void add_file(parameters *p, char* file)
{
p->n_files++;
p->files = realloc(p->files, sizeof(*(p->files)) * p->n_files);
p->files[p->n_files - 1] = malloc(sizeof(char) * str_len(file) + 1);
mem_cpy(p->files[p->n_files - 1], file, str_len(file) + 1);
}
/* INTERNAL : find an argument */
struct argument* search_argument(parameters *p, char* name)
{
size_t i;
for(i = 0 ; i < p->n_args ; i++)
{
if(str_cmp(p->args[i].name, name)
|| (name[1] == '\0' && *name == p->args[i].id))
return p->args + i;
}
return NULL;
}
/* INTERNAL : split --arg=value in arg and value */
void split_arg(char* raw, char** name, char** value)
{
*name = raw + 2;
for(raw += 2 ; *raw != '\0' && *raw != '=' ; raw++) { }
if(*raw == '=')
*raw++ = '\0';
*value = raw;
}
/* INTERNAL : Used to update active and value field in an argument */
int update_parameter(parameters *p, char** argv, int *i, int argc)
{
char* name = NULL;
char* raw_value = NULL;
if(argv[*i][1] == '-')
split_arg(argv[*i], &name, &raw_value);
else
{
name = malloc(sizeof(char) * 2);
name[0] = argv[*i][1];
name[1] = '\0';
}
struct argument *a = search_argument(p, name);
if(raw_value && *raw_value != '\0')
*(raw_value - 1) = '=';
if(!raw_value)
free(name);
if(!a)
return 0;
if(a->has_value)
{
if(raw_value == NULL)
{
if(*i + 1 >= argc || !tryparse(argv[*i + 1], &(a->value) ))
return 0;
*i = *i + 1;
}
else if(!tryparse(raw_value, &(a->value) ))
return 0;
}
a->active = TRUE;
return 1;
}
int parse_arguments(parameters *p, int argc, char** argv)
{
int i;
for(i = 1 ; i < argc ; i++)
{
if(argv[i][0] == '-')
{
if(!update_parameter(p, argv, &i, argc))
return throw("Wrong parameters. Check 'man tail'", NULL) - 1;
}
else
add_file(p, argv[i]);
}
return 1;
}
/* Is an argument active ? */
char is_active(parameters *p, char* name)
{
struct argument *a = search_argument(p, name);
if(!a)
return FALSE;
return a->active;
}
#endif
<file_sep>package packPasaPalabra;
import java.util.ArrayList;
import java.util.Scanner;
import packPasaPalabra.Tokenizador.ErrorEstadoInadecuado;
import packPasaPalabra.Tokenizador.ErrorSeleccionFichero;
public class GeneradorPalabras
{
ArrayList<Palabra> stringList;
@SuppressWarnings("serial")
public static class ErrorNombreFichero extends Exception {
ErrorNombreFichero(String s) {super(s);}
}
@SuppressWarnings("serial")
public static class ErrorPalabrasAgotadas extends Exception {
ErrorPalabrasAgotadas(String s) {super(s);}
}
public GeneradorPalabras()
{
stringList = new ArrayList<Palabra>();
}
/**
* @param Int nLetras : minimal numero de letras en el palabra para anadir le en la lista
* @Efecto Abrir un fichera, y leer los palabras
**/
public void empezar(int nLetras) throws ErrorNombreFichero
{
stringList.clear();
Scanner console = new Scanner(System.in);
System.out.println("Introduzca el nombre del fichero de palabras");
String filename = console.nextLine();
console.close();
try
{
Tokenizador.abrir(filename);
while(true)
{
try
{
if(Tokenizador.hayTokenPalabra())
{
String s = Tokenizador.siguienteTokenPalabra();
Palabra p = new Palabra(s);
if(s.length() >= nLetras && !stringList.contains(s))
stringList.add(p);
}
else
break;
}
catch(Exception e)
{
if(e instanceof Tokenizador.ErrorPosicionInadecuada)
System.out.println("Error en la estructura del fichero");
else
e.printStackTrace();
break;
}
}
Tokenizador.cerrar();
} catch (ErrorSeleccionFichero | ErrorEstadoInadecuado e)
{
if(e instanceof ErrorSeleccionFichero)
throw new ErrorNombreFichero("No puedo buscar el fichero :" + filename);
}
stringList.sort((s1, s2) -> s1.getLongitud() - s2.getLongitud());
}
/**
* @return Palabra name : dar la primera palabra de la lista
* @see Palabra
**/
public Palabra darPalabra() throws ErrorPalabrasAgotadas
{
if(stringList == null || stringList.size() == 0)+
throw new ErrorPalabrasAgotadas("No mas palabras");
else
{
Palabra p = stringList.get(0);
stringList.remove(0);
return p;
}
}
}
<file_sep>/* clock.c */
#include <stdlib.h>
#include "clock.h"
main(int argc, char *argv[])
{
wait_time(atoi(argv[1]));
}
<file_sep>#include "main.h"
int main()
{
Console *c = CreateConsole();
pid_t pid = fork();
if(!pid)
{
c->displayLoop(c);
return 0;
}
while(c->run)
{
char t = getchar();
c->registerTyped(c, t);
}
FreeConsole(c);
}
<file_sep>rm -f $(find hello/ -name "*.class");
<file_sep>#######################################################################
###
### FUNCION COX-DE-BOOR
### @params: i (indice)
### @params: p (grado de la curva)
### @params: u (parametro)
### @params: nudos (vector)
###
### Devolvemos el valor de la funcion base N(i,p,u)
###
#######################################################################
secure_div <- function(n, d)
{
if(d > 1.0e-8)
return(n/d)
else
return(0)
}
N <- function (i, p, u, nodes, min, max)
{
if(p == 0)
{
i = i + 1;
return( if(nodes[i] <= u && u < nodes[i + 1]) 1
else 0 );
}
#if(i < min || i > max)
# return(0);
index = i + 1;
a = secure_div( u - nodes[index],
nodes[index + p] - nodes[index]);
b = secure_div( nodes[index + p + 1] - u,
nodes[index + p + 1] - nodes[index + 1]);
a = if(a <= 1.0e-8) 0 else a * N(i, p-1, u, nodes, min, max);
b = if(b <= 1.0e-8) 0 else b * N(i+1, p-1, u, nodes, min, max);
return(a + b);
if(i >= length(nodes) - p - 1)
return(0);
if(p == 0)
{
return(
if(nodes[i] <= u && u < nodes[i+1]) 1
else 0);
}
i = i + 1;
na = u - nodes[i];
da = nodes[i + p] - nodes[i]
ra = secure_div(na, da)
nb = nodes[i+p+1] - u
db = nodes[i+p+1] - nodes[i+1]
rb = secure_div(nb, db)
return( ra * N(i , p - 1, u, nodes, min, max)
+ rb * N(i + 1, p - 1, u, nodes, min, max))
}
<file_sep>FILES+=("my_more")
nb=1
for ((i = 1 ; i < ($nb+1) ; i++)); do
file=${FILES[$i]} &&
echo "Compiling "${FILES[$i]} &&
rm $file;
clang -fsanitize=address -g -Wall -Wextra -Werror \
-pedantic -O3 $file".c" -o $file &&
gcc $file".c" -o $file;
done;
<file_sep>package packPasaPalabra;
import java.util.Random;
public class Palabra
{
private String str;
/**
* @param String : Palabra que guardar en la classe
* @Efecto Construie la palabra con la palabra da
**/
public Palabra(String s)
{
str = s;
}
/**
* @return El valor de la palabra
**/
public String getValorString()
{
return str;
}
/**
* @return El longitug de la palabra
**/
public int getLongitud()
{
return str.length();
}
/**
* @return, String
* @Efecto, el valor devuelto se obtiene desordenando las letras del objeto
*/
public String getValorDesordenado() {
//List<Character> palDesord = new ArrayList<Character>();
int lon = getLongitud();
String nuevaPal, auxPal ;
nuevaPal = str;
Random randomnum = new Random();
int n;
char c;
for (int i = 0; i < lon-1; i++) { //genera desorden
n= randomnum.nextInt(lon);
n= randomnum.nextInt(lon);
n= randomnum.nextInt(lon);
//System.out.println(n);
c= nuevaPal.charAt(n);
auxPal ="";
auxPal +=c;
for (int j =0; j<n; j++) {
auxPal += nuevaPal.charAt(j);
}
for (int j =n+1; j<lon; j++) {
auxPal += nuevaPal.charAt(j);
}
nuevaPal=auxPal;
}
return nuevaPal;
}
}
<file_sep>#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#define SYS 1
int str_cmp(char* a, char* b)
{
while(*a != '\0' && *b != '\0')
if(*(a++) != *(b++))
return 0;
return *a == *b;
}
size_t str_len(char* s)
{
size_t i;
for(i = 0; ; i++, s++)
if(*s == '\0')
return i;
}
int throw(char* msg, char* arg)
{
char* str = "\x1B[31mError: ";
char* strb = "\n\x1B[37m";
write(2, str, str_len(str));
write(2, msg, str_len(msg));
if(arg)
write(2, arg, str_len(arg));
write(2, strb, str_len(strb));
return 1;
}
int try_parse(char* str, int* value)
{
if(*str == '\0')
return 0;
*value = 0;
while(*str != '\0')
if(*str > 47 && *str < 58)
*value = *value * 10 + (int)(*str++ - 48);
else
return 0;
return 1;
}
int main(int argc, char** argv)
{
int bytes = 10;
char* file;
char c;
int f = 0;
if(argc == 3)
if(!try_parse(argv[2], &bytes))
exit(throw("Unable to parse the number", NULL));
if(argc < 1)
exit(throw("Usage: ctail <filename> [<number of lines>]", NULL));
file = argv[1];
f = open(file, O_RDONLY);
if(!f)
exit(throw("Unable to open the file :", file));
lseek(f, 0, SEEK_END);
for(; bytes > 0 ; bytes--)
if(lseek(f, -1, SEEK_CUR) < 1)
break;
while(read(f, &c, 1) > 0)
write(1, &c, 1);
close(f);
}
<file_sep>#include "sortdynlist.h"
list* empty_list()
{
list *l = malloc(sizeof(*l));
l->next = NULL;
return l;
}
void free_list(list *l)
{
if(l)
free_list(l->next);
free(l);
}
void insert_sorted(list *l, int elt)
{
while(l->next && l->next->data < elt)
l = l->next;
list *n = l->next;
l->next = empty_list();
l->next->data = elt;
l->next->next = n;
}
void print_list(list *h)
{
list *l = h->next;
for( ;l ;l = l->next)
printf("%d%s", l->data, l->next ? "\n" : "");
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <grp.h>
#include <err.h>
#define ARG_NBR 1
#define ARG_NBR_MSG "Wrong number of parameters\n"
#define FILE_STAT_MSG "Unable to read file stats"
int str_cmp(char* a, char* b)
{
int val = 0;
while(*a != 0 || *b != 0)
{
if(*a != 0 && *b != 0)
val += *(a++) - *(b++);
else
val += *a == 0 ? -*(b++) : *(a++);
}
return val;
}
int main(int argc, char** argv)
{
struct group *gr;
if(argc < ARG_NBR + 1 || argc > ARG_NBR + 1)
return printf(ARG_NBR_MSG) - 1;
while(( gr = getgrent()))
{
if(!str_cmp(gr->gr_name, argv[1]))
{
printf("%s\n", *gr->gr_mem);
return 0;
}
}
return 1;
}
<file_sep>#######################################################################
###
### CALCULA LOS PUNTOS DE CONTROL DE LA BSPLINE
### @params: datos (data.frame)
### @params: nudos (vector)
###
### Devolvemos los puntos de control de la bspline (data.frame)
###
#######################################################################
calculaPuntosControl <- function(datos, nudos)
{
nDatos <- dim(datos)[1]
### Paso Forward
ABG <- dame_AlfaBetaGamma(nDatos, nudos)
print("Alfa")
print(ABG$alfa)
print("Beta")
print(ABG$beta)
print("Gamma")
print(ABG$gamma)
print("Computing Lambda & Delta");
LD <- dame_LambdaDelta(datos, ABG$alfa, ABG$beta, ABG$gamma)
print("Lambda")
print(LD$lambda)
print("Delta")
print(LD$delta)
### Paso backward
print("Computing X");
X <- dame_X(LD$delta, LD$lambda)
print("X")
print(X)
### Calcular los puntos de control de la bspline
n <- length(ABG$alfa);
puntosControl <- NULL
puntosControl <- data.frame(x=double(), y=double())
#puntosControl <- data.frame(puntosControl)
rownames(puntosControl) <- NULL
colnames(puntosControl) <- c("x", "y")
#puntosControl <- data.frame(puntosControl)
p = 3;
n = length(nudos) - p - 1;
for(i in 2:n-1)
{
tx = X$x[i-1];
ty = X$y[i-1];
puntosControl = rbind(puntosControl, data.frame(x=tx, y=ty) );
}
puntosControl <- rbind(puntosControl[1,], puntosControl);
puntosControl <- rbind(puntosControl, puntosControl[n-1,]);
return(puntosControl)
}
<file_sep>##########################################################################################
###
### CALCULA LOS VALORES MAXIMOS Y MINIMOS DE LAS COORDENADAS DE LOS PUNTOS DE CONTROL
### @params: puntosControl (data.frame)
###
### Devolvemos xy (data.frame)
###
##########################################################################################
calculaLimites <- function(puntosControl) {
### Valores por defecto
if(length(puntosControl) == 0)
{
xy <- data.frame(x=c(-10,10), y=c(-10,10));
return(xy);
}
minX = puntosControl$x[1];
minY = puntosControl$y[1];
maxX = puntosControl$x[1];
maxY = puntosControl$y[1];
for(i in 1:length(puntosControl$x))
{
tx = puntosControl$x[i];
ty = puntosControl$y[i];
minX = if(tx < minX) tx else minX;
minY = if(ty < minY) ty else minY;
maxX = if(tx > maxX) tx else maxX;
maxY = if(ty > maxY) ty else maxY;
}
xy <- data.frame(x=c(minX, maxX), y=c(minY,maxY));
return(xy)
}
<file_sep>#######################################################################
###
### CALCULA LOS NUDOS UNIFORMES DE UNA BSPLINE
### @params: n (numero de nudos)
### @params: p (grado de la bspline)
###
### Devolvemos un vector de nudos
###
#######################################################################
calculaNudosUniforme <- function(n, p)
{
### Calcular los nudos uniformes de una bspline
length = n + p + 2;
nudos = array(0, length);
print(length);
print("Calculating nodes...");
for(i in 0:length-1)
{
if(i <= p)
{
nudos[i+1] = 0;
}
else if(i < length - p)
{
nudos[i+1] = (i-3) / (n-2);
}
else
{
nudos[i+1] = 1;
}
}
return(nudos)
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <time.h>
typedef struct l_gen
{
char* data;
char* mask;
} l_gen;
void* letter_generator(void* a)
{
l_gen *arg = (struct l_gen*)a;
arg->data[0] = 'a';
return NULL;
}
void* mask_generator(void* a)
{
char* mask = (char*)a;
while(1)
{
for(size_t i = 0 ; i < 80 ; i++)
mask[i] = rand() % 2;
sleep(5);
}
return NULL;
}
int main()
{
pthread_t pMask, pData;
char matrix[80];
char mask[80];
l_gen l_arg = (l_gen){ .data = matrix, .mask = mask};
pthread_create(&pMask, NULL, mask_generator, (void*)mask);
pthread_create(&pData, NULL, letter_generator, (void*)&l_arg);
for(size_t i = 0; i < 5; ++i)
{
printf("%s\n", matrix);
sleep(1);
}
pthread_join(pMask, NULL);
pthread_join(pData, NULL);
return 0;
}
<file_sep>// ccopy.c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#define BUFF_SIZE 512
main(int argc, char *argv[])
{
int c;
char buff[BUFF_SIZE];
int i;
int f;
for(i = 1 ; i < argc ; i++)
{
f = open(argv[i], O_RDONLY);
if(f != -1)
while ((c = read(f, buff, BUFF_SIZE)) > 0)
write(1, buff, c);
else
exit( write(2, "\x1B[31mnon-existant file.\n\x1B[37m", 29) + 1);
close(f);
}
if(argc == 1)
while ((c = read(0, buff, BUFF_SIZE)) != 0)
write(1, buff, c);
exit(0);
}
<file_sep>// my_echo_sys.c (uses the read and write Unix system calls)
#include <unistd.h>
int main()
{
int n;
char buffer[1];
while ((n = read(0, buffer, 1)) > 0) {
write(1, buffer, n);
}
}
<file_sep>/* my_sh1.c */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#define error(a) {perror(a); exit(1);};
#define BUFSIZE 512
#define MAXARG 10
int get_parameters(char *buf, int n, char *argk[], int ma);
int main(int argc, char *argv[])
{
(void)argc;
(void)argv;
int err, n, pid;
char buf[BUFSIZE];
char *arg[MAXARG];
for (n = 0; n < BUFSIZE; n++) buf[n] = '\0';
/* read */
write(1, "my_sh1> ", strlen("my_sh1> "));
while ((n = read(0, buf, BUFSIZE)) > 0)
{
buf[n] = '\n';
n++;
err = get_parameters(buf, n, arg, MAXARG);
if (arg[0] == NULL)
{
write(1, "my_sh1> ", strlen("my_sh1> "));
continue;
}
switch (pid = fork())
{
case -1: error("fork");
break;
case 0: /* child */
execvp(arg[0], arg);
error("exec");
break;
default: /* parent */
printf("%d (%s ...) process created\n", pid, arg[0]);
/* wait until child finishes */
if (wait(NULL) != pid) error("wait"); /* while (wait(NULL) != pid) ; */
for (n = 0; n < BUFSIZE; n++) buf[n] = '\0';
write(1, "my_sh1> ", strlen("my_sh1> "));
break;
}
}
printf("\n");
}
int get_parameters(char *buf, int n, char *argk[], int m)
{
int i, j;
for (i = 0, j = 0; (i < n) && (j < m); j++)
{
/* advance blanks */
while (((buf[i] == ' ') || (buf[i] == '\n')) && (i < n)) i++;
if (i == n) break;
argk[j] = &buf[i];
/* find blank */
while ((buf[i] != ' ') && (buf[i] != '\n')) i++;
buf[i++] = '\0';
}
argk[j] = NULL;
return 0;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
int throw(char* msg, char* arg)
{
printf("\x1B[31mError: %s%s\n\x1B[37m", msg, arg ? arg : "");
return 1;
}
int try_parse(char* str, int* value)
{
if(*str == '\0')
return 0;
*value = 0;
while(*str != '\0')
if(*str > 47 && *str < 58)
*value = *value * 10 + (int)(*str++ - 48);
else
return 0;
return 1;
}
int main(int argc, char** argv)
{
int bytes = 10;
char* file;
char c;
FILE *f = NULL;
if(argc == 3)
if(!try_parse(argv[2], &bytes))
exit(throw("Unable to parse the number", NULL));
if(argc < 1)
exit(throw("Usage: ctail <filename> [<number of lines>]", NULL));
file = argv[1];
f = fopen(file, "r");
if(!f)
exit(throw("Unable to open the file :", file));
fseek(f, 0, SEEK_END);
for(; bytes > 0 ; bytes--)
if(fseek(f, -1, SEEK_CUR))
break;
while(fread(&c, 1, 1, f))
printf("%c", c);
fclose(f);
}
<file_sep>#######################################################################
###
### GENERA PUNTOS SOBRE LA BSPLINE
### (por defecto, 20 PUNTOS)
### @params: bspline (data.frame)
### @params: nPuntos (integer o NULL)
###
### Devolvemos puntos (data.frame) sobre la bspline: coordenadas (x, y)
###
#######################################################################
computePoint <- function(u, bspline)
{
n = length(bspline$puntosControl$x);
p = 3;
px = 0;
py = 0;
for(index in 1:n)
{
i = index - 1;
value_n = N(i, p, u, bspline$nudos, i-p, i);
px = px + bspline$puntosControl$x[index] * value_n;
py = py + bspline$puntosControl$y[index] * value_n;
}
pos = data.frame(x=double(), y=double());
pos = rbind(pos, data.frame(x=px, y=py));
return(pos);
}
puntosEnCurva <- function(bspline, nPuntos=NULL)
{
puntosControl <- bspline$puntosControl
nudos <- bspline$nudos
p <- bspline$p
### Generamos las coordenadas (x, y) y las almacenamos en la variable puntos
puntos <- data.frame(x=double(), y=double())
rownames(puntos) <- NULL
colnames(puntos) <- c("x", "y")
nPuntos = if(is.null(nPuntos)) 20 else nPuntos;
for(i in 0:nPuntos)
{
d = (1/nPuntos) * i;
if(d == 1)
{
break;
}
t = computePoint(d, bspline);
puntos <- rbind(puntos, t);
}
return(puntos)
}
<file_sep>#######################################################################
###
### CALCULA LAMBDA-DELTA (PASO FORDWARD 2)
### @params: datos (data.frame)
### @params: alfa, beta, gamma
###
### Devolvemos lambda (vector) y delta (data.frame)
###
#######################################################################
dame_LambdaDelta <- function (datos, alpha, beta, gamma)
{
n <- length(alpha)
lambda <- array(0, dim=n);
delta <- data.frame(x=double(), y=double())
### Calcular lambda y delta
lambda[1] = gamma[1] / beta[1];
A=datos$x[1] / beta[1];
B=datos$y[1] / beta[1];
delta <- rbind(delta, data.frame(x=A, y=B));
for(i in 2:n)
{
lambda[i] = gamma[i] / (beta[i] - alpha[i]*lambda[i-1]);
A = (datos$x[i] - alpha[i]*delta$x[i-1]) / (beta[i] - alpha[i]*lambda[i-1]);
B = (datos$y[i] - alpha[i]*delta$y[i-1]) / (beta[i] - alpha[i]*lambda[i-1]);
delta <- rbind(delta, data.frame(x=A, y=B));
}
res <- NULL
res$lambda <- lambda
res$delta <- delta
return(res)
}
<file_sep>/*
Sorry, I woke up too late for the exam. So just did this for the sport.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/time.h>
#include <unistd.h>
#include <time.h>
#define ERR_PARA "Not enough parameters, usage : time_checker <nb_tests> <min_time> <max_time> <program> [parameters]\n"
#define ERR_FORK "Unable to create anther process"
#define RUN(a) "\nRuning test %d..",a
#define EXIN(a) " in %lf seconds\n",a
#define MINT "Too fast !\n"
#define MAXT "Too slow !\n"
#define OKT "Perfect !\n"
//Start the program and return the PID
double StartProgram(char* name, char** args)
{
struct timeval s, e;
int pid;
clock_t a, b;
gettimeofday(&s, NULL);
a = clock();
pid = fork();
if(pid < 0) return printf(ERR_FORK) - 100;
else if(pid != 0)
{
if((pid = wait(NULL)) != -1)
{
gettimeofday(&e, NULL);
b = clock();
return e.tv_sec - s.tv_sec;
//return (double)(b - a) / CLOCKS_PER_SEC;
}
}
else
{
execvp(name, args);
perror("RUN:");
}
return 0;
}
int main(int argc, char** argv)
{
int i, tests, max, min;
double time;
if(argc < 5)
printf(ERR_PARA);
tests = atoi(argv[1]);
min = atoi(argv[2]);
max = atoi(argv[3]);
for(i = 0 ; i < tests ; i++)
{
printf(RUN(i + 1));
time = StartProgram(argv[4], argc > 4 ? argv + 4 : NULL);
printf(EXIN(time));
printf(time < min ? MINT : (time > max ? MAXT : OKT));
}
return 0;
}
<file_sep>CC=clang
CFLAGS=-pedantic -O0 -g -fsanitize=address -Wall -Wextra -Werror
EXEC=main
SRC=$(wildcard *.c)
OBJ=$(SRC:.c=.o)
all :
@$(CC) $(SRC) $(CFLAGS) -o $(EXEC)
clean:
rm -rf *.o
rm -f $(EXEC)
<file_sep>#ifndef H_MSH
#define H_MSH
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <time.h>
#define CMD_MAX 512
#define PROMPT_NAME "MSH > "
#define DISP(a) printf("MSH: %s\n", a);
#define bool int
#define true 1
#define false 0
struct t_cmd
{
int background;
char** arg;
size_t arg_nbr;
int max_time;
};
struct t_cmd prompt();
struct t_cmd parsePrompt(char* raw);
struct t_cmd prompt()
{
char buf[CMD_MAX];
size_t l;
printf(PROMPT_NAME);
fflush(stdout);
l = read(0, buf, CMD_MAX);
buf[l] = '\0';
return parsePrompt(buf);
}
int parse(char* str, int* value)
{
int i = 0;
for( ; *str != '\0'; str++)
{
if(*str >= '0' && *str <= '9')
i = i * 10 + (int)(*str - '0');
else
return 0;
}
*value = i;
return 1;
}
struct t_cmd parsePrompt(char* raw)
{
struct t_cmd cmd;
cmd.background = 0;
cmd.max_time = -1;
cmd.arg = NULL;
cmd.arg_nbr = 0;
char cur_token[CMD_MAX];
bool state_token = true;
bool time_token = false;
int i;
i = 0;
while(*raw != '\0')
{
if(*raw == '\n')
{ }
else if(*raw == ' ' && i > 0) //END TOKEN
{
if(state_token && i == 1 &&
(cur_token[0] == 'R' || cur_token[0] == 'S'))
{
cmd.background = cur_token[0] == 'S';
time_token = true;
}
else if(time_token)
{
cur_token[i] = '\0';
if(!parse(cur_token, &(cmd.max_time)))
{
cmd.arg_nbr = 0;
printf("S or R must be followed by positive integer.\n");
return cmd;
}
time_token = false;
}
else
{
cmd.arg_nbr++;
cmd.arg = realloc(cmd.arg, sizeof(char**) * cmd.arg_nbr);
cmd.arg[cmd.arg_nbr - 1] = malloc(sizeof(char) * i);
memcpy(cmd.arg[cmd.arg_nbr - 1], cur_token, i);
}
state_token = false;
i = 0;
}
else
cur_token[i++] = *raw;
raw++;
if(*raw == '\0' && i > 0)
*(--raw) = ' ';
}
return cmd;
}
#endif
<file_sep>FILES=("parsing")
i=1
file=${FILES[$i]} &&
echo "Compiling "${FILES[$i]} &&
rm $file;
clang -fsanitize=address -g -Wall -Wextra -Werror \
-pedantic -O3 $file".c" -o $file &&
gcc $file".c" -o $file;
<file_sep>#include "display.h"
void displayPrompt(Console *c)
{
printf("[%c]%s", c->error ? 'X' : ' ', c->prompt);
(void)c;
}
void registerTyped(Console *c, char t)
{
if(t == 3 || t == 4 || t == 20)
c->run = false;
c->output_len++;
c->output = realloc(c->output, sizeof(char) * c->output_len);
c->output[c->output_len - 1] = t;
c->refresh = true;
}
void displayLoop(Console *c)
{
while(c->run)
{
if(!c->refresh)
continue;
write(1, c->output, c->output_len);
c->flush(c);
}
}
void flush(Console *c)
{
free(c->output);
c->output = NULL;
c->output_len = 0;
}
Console* CreateConsole()
{
Console *c = malloc(sizeof(Console));
c->run = true;
c->error = false;
c->refresh = false;
c->width = 80;
c->height = 50;
c->prompt = " O_o >";
c->displayPrompt = displayPrompt;
c->registerTyped = registerTyped;
c->displayLoop = displayLoop;
c->flush = flush;
system("/bin/stty raw -echo");
return c;
}
void FreeConsole(Console* c)
{
system("/bin/stty cooked");
free(c);
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <error.h>
#define R 0
#define W 1
#define ERR_EXIT(header) { perror(header); exit(-1);}
int main()
{
int chan[2];
char* grep_args[] = { "grep", "-c", "acaf", NULL};
char* who_args[] = { "who", NULL };
if(pipe(chan))
ERR_EXIT("PIPE");
if(!fork())
{
close(STDOUT_FILENO);
dup(chan[W]);
close(chan[R]);
close(chan[W]);
execvp("who", who_args);
ERR_EXIT("WHO_CHILD:");
exit(-1);
}
if(!fork())
{
close(STDIN_FILENO);
dup(chan[R]);
close(chan[W]);
close(chan[R]);
execvp("grep", grep_args);
ERR_EXIT("GREP_CHILD: ");
exit(-1);
}
close(chan[W]);
close(chan[R]);
wait(0);
wait(0);
return 0;
}
<file_sep>#ifndef H_MAIN
#define H_MAIN
#include <stdio.h>
#include <stdlib.h>
#include "display.h"
#endif
<file_sep>#include <stdio.h>
#include "sortdynlist.h"
int parse(char *data, int *value)
{
*value = 0;
int sign = 1;
for(size_t i = 0 ; i < 255 && data[i] != '\0'; ++i)
{
if(!(*value) && data[i] == '-')
sign *= -1;
else if(data[i] > 47 && data[i] < 58)
*value = *value * 10 + data[i] - 48;
else
return 0;
}
*value *= sign;
return 1;
}
void interactiveMode()
{
char data[255];
int value = 0;
list *l = empty_list();
for(;;)
{
scanf("%s", data);
fseek(stdin, 0, SEEK_END);
if(feof(stdin))
break;
if(parse(data, &value))
insert_sorted(l, value);
}
print_list(l);
free_list(l);
}
int batchMode(int argc, char** argv)
{
list *l = empty_list();
int value;
for(int i = 1 ; i < argc ; ++i)
if(!parse(argv[i], &value))
return printf("%s is not a number !\n", argv[i]) + 1;
else
insert_sorted(l, value);
print_list(l);
free_list(l);
return 0;
}
int main(int argc, char** argv)
{
if(argc > 1)
return batchMode(argc, argv);
else
interactiveMode();
return 0;
}
<file_sep>#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
int str_cmp(char* a, char* b)
{
while(*a != '\0' && *b != '\0')
if(*(a++) != *(b++))
return 0;
return *a == *b;
}
size_t str_len(char* s)
{
size_t i;
for(i = 0; ; i++, s++)
if(*s == '\0')
return i;
}
int throw(char* msg, char* arg)
{
char* str = "\x1B[31mError: ";
char* strb = "\n\x1B[37m";
write(2, str, str_len(str));
write(2, msg, str_len(msg));
if(arg)
write(2, arg, str_len(arg));
write(2, strb, str_len(strb));
return 1;
}
int main(int argc, char** argv)
{
char c;
int a, b;
if(argc != 3)
exit(throw("Usage : sappend <file1> <file2>", NULL));
if(str_cmp(argv[1], argv[2]))
exit(throw("You must give me 2 different files...", NULL));
a = open(argv[1], O_WRONLY);
b = open(argv[2], O_RDONLY);
if(a < 0)
exit(throw("Unable to open the file", argv[1]));
if(b < 0)
exit(throw("Unable to open the file", argv[2]));
lseek(a, 0, SEEK_END);
while(read(b, &c, 1) > 0)
write(a, &c, 1);
close(a);
close(b);
return 0;
}
<file_sep>// my_echo_lib.c (uses the fread and fwrite C library functions)
#include <stdio.h>
int main()
{
int n;
char buffer[1];
while ((n = fread(buffer, sizeof(char), 1, stdin)) > 0) {
fwrite(buffer, sizeof(char), n, stdout);
}
}
<file_sep>rm exo1
rm exo2
rm exo3
rm exo4
rm exo5
rm exo6
rm exo7
rm exo8
rm exo9
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <grp.h>
#define ARG_NBR 1
#define ARG_NBR_MSG "Wrong number of parameters\n"
#define FILE_STAT_MSG "Unable to read file stats"
int main(int argc, char** argv)
{
struct stat fileInfo;
int i;
if(argc < ARG_NBR + 1 || argc > ARG_NBR + 1)
return printf(ARG_NBR_MSG) - 1;
for(i = 1 ; i < argc ; i++)
{
if(stat(argv[i], &fileInfo))
return printf(FILE_STAT_MSG) - 1;
}
return 0;
}
<file_sep>//ctail.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "parsing.h"
#define NONE 0
#define FALSE 0
#define TRUE 1
#define BYTES 1
#define LINES 2
#define DISPLAY 1
#define SILENT 2
#define VERSION 1664
int get_offset(FILE *f, int lines, int bytes)
{
if(bytes != -1)
return bytes;
size_t total = 0;
fseek(f, 0, SEEK_END);
while(!fseek(f, -1, SEEK_CUR) && lines)
{
total++;
if((char)*(f->_IO_read_ptr) == '\n' && total > 1)
lines--;
}
total--; //Skip first \n
return total;
}
int display(FILE *f, int lines, int bytes)
{
size_t count = 0;
char *c = NULL;
count = get_offset(f, lines, bytes);
fseek(f, -count, SEEK_END);
c = malloc(sizeof(char) * count + 1);
c[count] = '\0';
fread(c, count, 1, f);
printf("%s", c);
free(c);
return 0;
}
void display_header(parameters *p, int i, char quiet, char verbose)
{
if(verbose || (p->n_files > 1 && !quiet))
printf("%s==> %s <==\n",
i ? "\n" : "",
p->files[i]);
}
void display_follow(FILE *f, char* name, char quiet, char verbose)
{
char c;
if(fread(&c, 1, 1, f))
{
if(verbose || !quiet)
printf("\n==> %s <==\n", name);
printf("%c", c);
}
else
return;
while(fread(&c, 1, 1, f))
printf("%c", c);
}
void tail(parameters *p)
{
char quiet = is_active(p, "q");
char verbose = is_active(p, "v");
char follow = is_active(p, "f");
char retry = is_active(p, "retry") || is_active(p, "F");
int bytes = is_active(p, "c") ? search_argument(p, "bytes")->value : -1;
int lines = is_active(p, "n") ? search_argument(p, "lines")->value : 10;
FILE *f = NULL;
size_t i;
size_t n_files = 0;
FILE **files = NULL;
char **names = NULL;
for(i = 0 ; i < p->n_files ; i++)
{
f = fopen(p->files[i], "r");
if(f)
{
display_header(p, i, quiet, verbose);
display(f, lines, bytes);
if(follow)
{
n_files++;
files = realloc(files, sizeof(*files) * n_files);
names = realloc(names, sizeof(*names) * n_files);
files[n_files - 1] = f;
names[n_files - 1] = p->files[i];
}
else
fclose(f);
}
else
throw("Unable to open file : ", p->files[i]);
}
(void)retry;
while(n_files > 0)
{
for(i = 0 ; i < n_files ; i++)
display_follow(files[i], names[i], quiet, verbose);
}
}
void display_version()
{
printf("Inspired from the version: tail (GNU coreutils) 8.21\n \
Written by <NAME>.\n");
}
void display_help()
{
printf("ctail:\n \
\t-n <nb> or --lines=<nb> : display <nb> last lines.\n \
\t-c <nb> or --bytes=<nb> : display <nb> last bytes.\n\
\t-f or --follow : output appended data as the file grows.\n\
\t-q or --quiet or --silent : Don't show headers.\n\
\t-v or --verbose : Always display header.\n\
\t--help : display help\n\
\t--version : display version\n");
}
int main(int argc, char** argv)
{
parameters *p = new_parameters();
add_parameter(p, 'c', "bytes", TRUE);
add_parameter(p, 'n', "lines", TRUE);
add_parameter(p, 'f', "follow", FALSE);
add_parameter(p, 'F', "F", FALSE);
add_parameter(p, '\0', "max-unchanged-stats", FALSE);
add_parameter(p, '\0', "pid", FALSE);
add_parameter(p, 'q', "quiet", FALSE);
add_parameter(p, 'q', "silent", FALSE);
add_parameter(p, '\0', "retry", FALSE);
add_parameter(p, 's', "sleep-interval", FALSE);
add_parameter(p, 'v', "verbose", FALSE);
add_parameter(p, '\0', "help", FALSE);
add_parameter(p, '\0', "version", FALSE);
if(!parse_arguments(p, argc, argv)){}
else if(is_active(p, "version"))
display_version();
else if(is_active(p, "help"))
display_help();
else
tail(p);
free_parameters(p);
return 0;
}
<file_sep>echo "======i"
cat a
echo "======="
./sappend a b
echo "======o"
cat a
echo "======"
<file_sep>#ifndef H_SORTDYNLIST
#define H_SORTDYNLIST
#include <stdio.h>
#include <stdlib.h>
typedef struct list
{
struct list *next;
int data;
}list;
list* empty_list();
void free_list(list *l);
void insert_sorted(list *l, int elt);
void print_list(list *h);
#endif
|
d4d9fe015ccdeaf6805c50363bea93bf528d79cd
|
[
"Makefile",
"Java",
"C",
"R",
"Shell"
] | 74
|
C
|
Keenuts/upv
|
d54763810b50ca0c49dcfe215e2ef4a775e556fc
|
bd50e1d3f2c5cf863584ea387882d09647da8011
|
refs/heads/master
|
<file_sep>/*
* @(#)Drawing.java
*
* Copyright (c) 1996-2010 by the original authors of JHotDraw and all its
* contributors. All rights reserved.
*
* You may not use, copy or modify this file, except in compliance with the
* license agreement you entered into with the copyright holders. For details
* see accompanying license terms.
*/
package org.jhotdraw.draw;
import edu.umd.cs.findbugs.annotations.Nullable;
import java.awt.Graphics2D;
import org.jhotdraw.draw.io.InputFormat;
import org.jhotdraw.draw.io.OutputFormat;
import org.jhotdraw.xml.*;
import java.awt.font.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.undo.*;
import javax.swing.event.*;
import java.io.*;
/**
* A <em>drawing</em> is a container for {@link Figure}s. A drawing can hold
* multiple figures, but a figure can only be in one drawing at a time. A
* drawing can be in one or multiple {@link DrawingView}s.
* <p>
* {@code Drawing} is essentially a {@link CompositeFigure} with a number of
* additional functionality:
* <ul>
* <li>A drawing notifies a figure and its {@code CompositeFigureListener}'s
* when the figure is added or removed from it. Like with
* {@code CompositeFigure} basic add and remove methods are supplied for use
* cases where this is not desired - for example when figures need to be
* temporarily removed in order to group or ungroup them.</li>
*
* <li>A drawing can find contained figures given a point or a rectangular
* region. Specialized implementations of the {@code Drawing} interface can use
* optimized strategies and data structures to find figures faster.</li>
*
* <li>The drawing object is used by {@code Figure}, {@code Tool} and
* {@code Handle} as a mediator for undoable edit events. This way, undoable
* edit listeners only need to register on the drawing object in order to
* receive all undoable edit events related to changes made in the drawing.</li>
*
* <li>Drawing can hold a number of {@link org.jhotdraw.draw.io.InputFormat}s
* and {@link org.jhotdraw.draw.io.OutputFormat}s, allowing to read and write a
* drawing from/to a stream, a file or the clipboard.</li>
* </ul>
*
* <hr>
* <b>Design Patterns</b>
*
* <p>
* <em>Framework</em><br>
* The following interfaces define the contracts of a framework for structured
* drawing editors:<br>
* Contract: {@link Drawing}, {@link Figure}, {@link DrawingView},
* {@link DrawingEditor}, {@link org.jhotdraw.draw.handle.Handle} and
* {@link org.jhotdraw.draw.tool.Tool}.
*
* <p>
* <em>Model-View-Controller</em><br>
* The following classes implement together the Model-View-Controller design
* pattern:<br>
* Model: {@link Drawing}; View: {@link DrawingView}; Controller:
* {@link DrawingEditor}.
*
* <p>
* <em>Strategy</em><br>
* {@code org.jhotdraw.draw.io.OutputFormat} encapsulates a strategy for writing
* drawings to output streams.<br>
* Strategy: {@link org.jhotdraw.draw.io.OutputFormat}; Context:
* {@link Drawing}.
*
* <p>
* <em>Strategy</em><br>
* {@code org.jhotdraw.draw.io.InputFormat} encapsulates a strategy for reading
* drawings from input streams.<br>
* Strategy: {@link org.jhotdraw.draw.io.InputFormat}; Context: {@link Drawing}.
* <hr>
*
* @author <NAME>
* @version $Id: Drawing.java 717 2010-11-21 12:30:57Z rawcoder $
*/
public interface Drawing extends CompositeFigure, Serializable, DOMStorable, SAMModel {
public void present(SAMActionProposal prop, State state);
/**
* Draws on the <em>canvas area</em>. The canvas is the background area onto
* which the drawing is drawn.
* <p>
* By convention this method is only invoked by {@link DrawingView}.
* <p>
* {@link AttributeKeys} defines a number of attribute keys which can be used to
* determine what to draw on the canvas.
*/
public void drawCanvas(Graphics2D g);
/**
* Adds a figure to the drawing. The drawing sends an {@code addNotify} message
* to the figure after it has been added.
*
* @see Figure#addNotify
*
* @param figure to be added to the drawing
*/
@Override
boolean add(Figure figure);
/**
* Adds a figure to the drawing. The drawing sends an {@code addNotify} message
* to the figure after it has been added.
*
* @see Figure#addNotify
*
* @param index The z-index of the figure.
* @param figure to be added to the drawing
*/
@Override
void add(int index, Figure figure);
/**
* Adds a collection of figures to the drawing. The drawing sends an
* {@code addNotify} message to each figure after it has been added.
*
* @see Figure#addNotify
*
* @param figures to be added to the drawing
*/
void addAll(Collection<? extends Figure> figures);
/**
* Adds a collection of figures to the drawing. The drawing sends an
* {@code addNotify} message to each figure after it has been added.
*
* @see Figure#addNotify
*
* @param index The z-index of the figure.
* @param figures to be added to the drawing
*/
void addAll(int index, Collection<? extends Figure> figures);
/**
* Removes a figure from the drawing. The drawing sends a {@code removeNotify}
* message to the figure before it is removed.
*
* @see Figure#removeNotify
*
* @param figure that is part of the drawing and should be removed
*/
@Override
boolean remove(Figure figure);
/**
* Removes the specified figures from the drawing. The drawing sends a
* {@code removeNotify} message to each figure before it is removed.
*
* @see Figure#removeNotify
*
* @param figures A collection of figures which are part of the drawing and
* should be removed
*/
void removeAll(Collection<? extends Figure> figures);
/**
* Removes a figure temporarily from the drawing.
*
* @see #basicAdd(Figure)
*
* @param figure that is part of the drawing and should be removed
*/
@Override
int basicRemove(Figure figure);
/**
* Removes the specified figures temporarily from the drawing.
*
* @see #basicAddAll(int, Collection)
* @param figures A collection of figures which are part of the drawing and
* should be removed
*/
void basicRemoveAll(Collection<? extends Figure> figures);
/**
* Reinserts a figure which was temporarily removed using basicRemove.
* <p>
* This is a convenience method for calling {@code basicAdd(size(), figure)}.
*
* @param figure that is part of the drawing and should be removed
* @see #basicRemove(Figure)
*/
@Override
void basicAdd(Figure figure);
/**
* Reinserts a figure which was temporarily removed using basicRemove.
*
* @see #basicRemove(Figure)
* @param figure that is part of the drawing and should be removed
*/
@Override
void basicAdd(int index, Figure figure);
/**
* Reinserts the specified figures which were temporarily removed from the
* drawing.
*
*
* @param index The insertion index.
* @param figures A collection of figures which are part of the drawing and
* should be reinserted.
* @see #basicRemoveAll(Collection)
*/
void basicAddAll(int index, Collection<? extends Figure> figures);
/**
* Returns all figures that lie within or intersect the specified bounds. The
* figures are returned in Z-order from back to front.
*/
List<Figure> findFigures(Rectangle2D.Double bounds);
/**
* Returns all figures that lie within the specified bounds. The figures are
* returned in Z-order from back to front.
*/
List<Figure> findFiguresWithin(Rectangle2D.Double bounds);
/**
* Finds a top level Figure. Use this call for hit detection that should not
* descend into children of composite figures.
* <p>
* Use {@link #findFigureInside} If you need to descend into children of
* composite figures.
*/
@Nullable
Figure findFigure(Point2D.Double p);
/**
* Finds a top level Figure. Use this call for hit detection that should not
* descend into the figure's children.
*/
@Nullable
Figure findFigureExcept(Point2D.Double p, Figure ignore);
/**
* Finds a top level Figure. Use this call for hit detection that should not
* descend into the figure's children.
*/
@Nullable
Figure findFigureExcept(Point2D.Double p, Collection<? extends Figure> ignore);
/**
* Finds a top level Figure which is behind the specified Figure.
*/
@Nullable
Figure findFigureBehind(Point2D.Double p, Figure figure);
/**
* Finds a top level Figure which is behind the specified Figures.
*/
@Nullable
Figure findFigureBehind(Point2D.Double p, Collection<? extends Figure> figures);
/**
* Returns a list of the figures in Z-Order from front to back.
*/
List<Figure> getFiguresFrontToBack();
/**
* Finds the innermost figure at the specified location.
* <p>
* In case a {@code CompositeFigure} is at the specified location, this method
* descends into its children and into its children's children until the
* innermost figure is found.
* <p>
* This functionality is implemented using the <em>Chain of Responsibility</em>
* design pattern in the {@code Figure} interface. Since it is often used from a
* drawing object as the starting point, and since {@code Drawing} defines other
* find methods as well, it is defined here again for clarity.
*
* @param p A location on the drawing.
* @return Returns the innermost figure at the location, or null if the location
* is not contained in a figure.
*/
@Override
@Nullable
Figure findFigureInside(Point2D.Double p);
/**
* Sends a figure to the back of the drawing.
*
* @param figure that is part of the drawing
*/
// cette action sera maintenant disponible via present()
// void sendToBack(Figure figure);
/**
* Brings a figure to the front.
*
* @param figure that is part of the drawing
*/
void bringToFront(Figure figure);
/**
* Returns a copy of the provided collection which is sorted in z order from
* back to front.
*/
List<Figure> sort(Collection<? extends Figure> figures);
/**
* Adds a listener for undooable edit events.
*/
void addUndoableEditListener(UndoableEditListener l);
/**
* Removes a listener for undoable edit events.
*/
void removeUndoableEditListener(UndoableEditListener l);
/**
* Notify all listenerList that have registered interest for notification on
* this event type.
*/
void fireUndoableEditHappened(UndoableEdit edit);
/**
* Returns the font render context used to do text leyout and text drawing.
*/
FontRenderContext getFontRenderContext();
/**
* Sets the font render context used to do text leyout and text drawing.
*/
void setFontRenderContext(FontRenderContext frc);
/**
* Returns the lock object on which all threads acting on Figures in this
* drawing synchronize to prevent race conditions.
*/
Object getLock();
/**
* Adds an input format to the drawing.
*/
void addInputFormat(InputFormat format);
/**
* Adds an output format to the drawing.
*/
void addOutputFormat(OutputFormat format);
/**
* Sets input formats for the Drawing in order of preferred formats.
* <p>
* The input formats are used for loading the Drawing from a file and for
* pasting Figures from the clipboard into the Drawing.
*/
void setInputFormats(List<InputFormat> formats);
/**
* Gets input formats for the Drawing in order of preferred formats.
*/
List<InputFormat> getInputFormats();
/**
* Sets output formats for the Drawing in order of preferred formats.
* <p>
* The output formats are used for saving the Drawing into a file and for
* cutting and copying Figures from the Drawing into the clipboard.
*/
void setOutputFormats(List<OutputFormat> formats);
/**
* Gets output formats for the Drawing in order of preferred formats.
*/
List<OutputFormat> getOutputFormats();
}
|
ee1e22589aeee6f137416c64ae3bd593e025cfd6
|
[
"Java"
] | 1
|
Java
|
LaurentPepin/LOG8430
|
9ba5ae1103c87d35c4c8030b9da86aa060720cd8
|
ffbd27c61fad38fa4c8981cb2829da9fa7c4afab
|
refs/heads/master
|
<file_sep># encoding: utf-8
class Sentence
def self.tenses
[:past, :present, :future]
end
def self.expression_forms
[:statement, :question, :negation]
end
def self.is_he_she_it?(pronoun)
["he", "she", "it"].include? pronoun
end
def initialize
@pronouns = YAML.load_file('./db/pronouns.yml')
end
def self.pronouns(person = nil, lang = "eng")
raise "Unknown language. Allowable are 'eng', 'rus'" unless @@pronouns[lang]
if person.nil?
return @@pronouns[lang]
end
raise "Unknown person for pronoun. Allowable are 'first', 'second', 'third'" unless @@pronouns[lang][person]
@@pronouns[lang][person]
end
@@pronouns = {
"eng" => {
"first" => ["i", "you", "we", "they", "he", "she", "it"],
"second" => ["me", "you", "us", "them", "him", "her", "it"],
"third" => ["my", "your", "our", "their", "his", "her", "its"],
},
"rus" => {
"first" => ["я", "вы", "мы", "они", "он", "она", "оно"],
"second" => ["мне/меня", "вас", "нас/нам", "им/их", "ему/его", "ее/ей", "этому"],
"third" => ["мое/мои", "ваше", "наш/наше", "их", "его", "ее", "этого"],
},
}
end
<file_sep>require_relative 'lib/conversation'
Conversation.new.start<file_sep>require_relative 'spec_helper'
require_relative '../lib/english_sentence'
describe English_Sentence do
let(:sentence) { English_Sentence.new }
it "#present_statement_for" do
sentence.present_statement_for("i", "love").should == "i love"
sentence.present_statement_for("you", "love").should == "you love"
sentence.present_statement_for("we", "love").should == "we love"
sentence.present_statement_for("they", "love").should == "they love"
sentence.present_statement_for("he", "love").should == "he loves"
sentence.present_statement_for("she", "love").should == "she loves"
end
it "#present_question_for" do
sentence.present_question_for("i", "love").should == "do i love?"
sentence.present_question_for("you", "love").should == "do you love?"
sentence.present_question_for("we", "love").should == "do we love?"
sentence.present_question_for("they", "love").should == "do they love?"
sentence.present_question_for("he", "love").should == "does he love?"
sentence.present_question_for("she", "love").should == "does she love?"
end
it "#present_question_for" do
sentence.present_negation_for("i", "love").should == "i don't love"
sentence.present_negation_for("you", "love").should == "you don't love"
sentence.present_negation_for("we", "love").should == "we don't love"
sentence.present_negation_for("they", "love").should == "they don't love"
sentence.present_negation_for("he", "love").should == "he doesn't love"
sentence.present_negation_for("she", "love").should == "she doesn't love"
end
it "#past_statement_for" do
sentence.past_statement_for("i", "love").should == "i loved"
sentence.past_statement_for("you", "love").should == "you loved"
sentence.past_statement_for("we", "love").should == "we loved"
sentence.past_statement_for("they", "love").should == "they loved"
sentence.past_statement_for("he", "love").should == "he loved"
sentence.past_statement_for("he", "see").should == "he saw"
sentence.past_statement_for("she", "love").should == "she loved"
sentence.past_statement_for("she", "see").should == "she saw"
end
it "#past_question_for" do
sentence.past_question_for("i", "love").should == "did i love?"
sentence.past_question_for("you", "love").should == "did you love?"
sentence.past_question_for("we", "love").should == "did we love?"
sentence.past_question_for("they", "love").should == "did they love?"
sentence.past_question_for("he", "love").should == "did he love?"
sentence.past_question_for("she", "love").should == "did she love?"
end
it "#past_negation_for" do
sentence.past_negation_for("i", "love").should == "i didn't love"
sentence.past_negation_for("you", "love").should == "you didn't love"
sentence.past_negation_for("we", "love").should == "we didn't love"
sentence.past_negation_for("they", "love").should == "they didn't love"
sentence.past_negation_for("he", "love").should == "he didn't love"
sentence.past_negation_for("she", "love").should == "she didn't love"
end
it "#future_statement_for" do
sentence.future_statement_for("i", "love").should == "i will love"
sentence.future_statement_for("you", "love").should == "you will love"
sentence.future_statement_for("we", "love").should == "we will love"
sentence.future_statement_for("they", "love").should == "they will love"
sentence.future_statement_for("he", "love").should == "he will love"
sentence.future_statement_for("she", "love").should == "she will love"
end
it "#future_question_for" do
sentence.future_question_for("i", "love").should == "will i love?"
sentence.future_question_for("you", "love").should == "will you love?"
sentence.future_question_for("we", "love").should == "will we love?"
sentence.future_question_for("they", "love").should == "will they love?"
sentence.future_question_for("he", "love").should == "will he love?"
sentence.future_question_for("she", "love").should == "will she love?"
end
it "#future_negation_for" do
sentence.future_negation_for("i", "love").should == "i will not love"
sentence.future_negation_for("you", "love").should == "you will not love"
sentence.future_negation_for("we", "love").should == "we will not love"
sentence.future_negation_for("they", "love").should == "they will not love"
sentence.future_negation_for("he", "love").should == "he will not love"
sentence.future_negation_for("she", "love").should == "she will not love"
end
end
<file_sep>class String
def ends_with?(str)
str = str.to_str
tail = self[-str.length, str.length]
tail == str
end
end<file_sep>require_relative 'spec_helper'
require_relative '../lib/conversation'
class Conversation
def waiting_for_answer
"i love"
end
end
describe Conversation do
let(:conversation) { Conversation.new }
let(:verbs) { YAML.load_file('./db/verbs.yml').keys }
it "has a congrats function when companion answers correctly" do
conversation.respond_to?(:congrats).should be_true
end
it "has a upset function when companion answers incorrectly" do
conversation.respond_to?(:upset).should be_true
end
context "when finishing" do
let(:conversation) { Conversation.new }
let(:answer) { "exit" }
it "ends conversation by special answer" do
conversation.want_to_exit?(answer).should be_true
end
end
it "generates tense, form, pronoun and verb for constructing sentence" do
data = conversation.generate_rand_data_for_sentence
tense, form, pronoun, verb = data
Sentence.tenses.should include tense
Sentence.expression_forms.should include form
Sentence.pronouns("first").should include pronoun
verbs.should include verb
end
it "generates rand tense, form, pronoun and verb for constructing sentence" do
data1 = conversation.generate_rand_data_for_sentence
data2 = conversation.generate_rand_data_for_sentence
data1.should_not == data2
end
end
<file_sep># coding: utf-8
require_relative 'sentence'
require_relative 'string'
class Russian_Sentence < Sentence
def initialize
@verbs = YAML.load_file("./db/verbs.yml")
@russian_verbs = YAML.load_file("./db/russian_verbs.yml")
end
def present_statement_for(pronoun, verb)
verb = @russian_verbs[verb]["настоящее"][pronoun]
"#{pronoun} #{verb}"
end
def present_question_for(pronoun, verb)
verb = @russian_verbs[verb]["настоящее"][pronoun]
"#{pronoun} #{verb}?"
end
def present_negation_for(pronoun, verb)
verb = @russian_verbs[verb]["настоящее"][pronoun]
"#{pronoun} не #{verb}"
end
def past_statement_for(pronoun, verb)
verb = @russian_verbs[verb]["прошлое"][pronoun]
"#{pronoun} #{verb}"
end
def past_question_for(pronoun, verb)
verb = @russian_verbs[verb]["прошлое"][pronoun]
"#{pronoun} #{verb}?"
end
def past_negation_for(pronoun, verb)
verb = @russian_verbs[verb]["прошлое"][pronoun]
"#{pronoun} не #{verb}"
end
def future_statement_for(pronoun, verb)
verb = @russian_verbs[verb]["будущее"][pronoun]
"#{pronoun} #{verb}"
end
def future_question_for(pronoun, verb)
verb = @russian_verbs[verb]["будущее"][pronoun]
"#{pronoun} #{verb}?"
end
def future_negation_for(pronoun, verb)
verb = @russian_verbs[verb]["будущее"][pronoun]
"#{pronoun} не #{verb}"
end
end<file_sep>require 'yaml'
require_relative 'russian_sentence'
require_relative 'english_sentence'
class Conversation
def initialize
@verbs = YAML.load_file('./db/verbs.yml')
end
def waiting_for_answer
STDOUT.print "> "
STDIN.gets.chop
end
def want_to_exit?(answer)
answer == "exit"
end
def start
loop do
tense, form, pronoun, verb = generate_rand_data_for_sentence
sentence_rus = construct_russian_sentence_by tense, form, pronoun, verb
sentence_eng = construct_english_sentence_by tense, form, pronoun, verb
show_to_companion sentence_rus
answer = waiting_for_answer
break if want_to_exit? answer
if answer == sentence_eng
congrats
else
upset sentence_eng
end
end
end
def construct_russian_sentence_by(tense, form, pronoun, verb)
index = Sentence.pronouns("first").index(pronoun)
rus_pronoun = Sentence.pronouns("first", "rus")[index]
rus_verb = @verbs[verb]
Russian_Sentence.new.send("#{tense}_#{form}_for", rus_pronoun, rus_verb)
end
def construct_english_sentence_by(tense, form, pronoun, verb)
English_Sentence.new.send("#{tense}_#{form}_for", pronoun, verb)
end
def generate_rand_data_for_sentence
@first_person_pronouns ||= Sentence.pronouns("first")
@verbs_list ||= @verbs.keys
[
Sentence.tenses[rand(Sentence.tenses.length)],
Sentence.expression_forms[rand(Sentence.expression_forms.length)],
@first_person_pronouns[rand(@first_person_pronouns.length)],
@verbs_list[rand(@verbs_list.length)],
]
end
def show_to_companion(message)
STDOUT.puts "< " + message
end
def congrats
# Nothing showing when competitor answers right
end
def upset(expected_sentence)
STDOUT.puts "BAD: No, you are wrong! Right is: '#{expected_sentence}'"
end
end
<file_sep># encoding: utf-8
require_relative 'spec_helper'
require_relative '../lib/sentence'
describe Sentence do
it "can formed with three different tenses" do
Sentence.tenses.should == [:past, :present, :future]
end
it "can stand in three expression forms" do
Sentence.expression_forms.should == [:statement, :question, :negation]
end
it "defines personal pronouns is it he, she or it" do
Sentence.is_he_she_it?("he").should be_true
Sentence.is_he_she_it?("she").should be_true
Sentence.is_he_she_it?("it").should be_true
Sentence.is_he_she_it?("i").should be_false
Sentence.is_he_she_it?("we").should be_false
end
it "has pronouns" do
Sentence.pronouns(nil, "eng").should_not be_nil
Sentence.pronouns(nil, "rus").should_not be_nil
end
it "has english pronouns of first person" do
Sentence.pronouns("first").should == ["i", "you", "we", "they", "he", "she", "it"]
end
it "has english pronouns of second person" do
Sentence.pronouns("second").should == ["me", "you", "us", "them", "him", "her", "it"]
end
it "has english pronouns of third person" do
Sentence.pronouns("third").should == ["my", "your", "our", "their", "his", "her", "its"]
end
it "has russian pronouns of first person" do
Sentence.pronouns("first", "rus").should == ["я", "вы", "мы", "они", "он", "она", "оно"]
end
it "has russian pronouns of second person" do
Sentence.pronouns("second", "rus").should == ["мне/меня", "вас", "нас/нам", "им/их", "ему/его", "ее/ей", "этому"]
end
it "has russian pronouns of third person" do
Sentence.pronouns("third", "rus").should == ["мое/мои", "ваше", "наш/наше", "их", "его", "ее", "этого"]
end
end<file_sep># coding: utf-8
require_relative 'spec_helper'
require_relative '../lib/russian_sentence'
describe Russian_Sentence do
let(:sentence) { Russian_Sentence.new }
it "#present_statement_for" do
sentence.present_statement_for("я", "любить").should == "я люблю"
sentence.present_statement_for("вы", "любить").should == "вы любите"
sentence.present_statement_for("мы", "любить").should == "мы любим"
sentence.present_statement_for("они", "любить").should == "они любят"
sentence.present_statement_for("он", "любить").should == "он любит"
sentence.present_statement_for("она", "любить").should == "она любит"
end
it "#present_question_for" do
sentence.present_question_for("я", "любить").should == "я люблю?"
sentence.present_question_for("вы", "любить").should == "вы любите?"
sentence.present_question_for("мы", "любить").should == "мы любим?"
sentence.present_question_for("они", "любить").should == "они любят?"
sentence.present_question_for("он", "любить").should == "он любит?"
sentence.present_question_for("она", "любить").should == "она любит?"
end
it "#present_negation_for" do
sentence.present_negation_for("я", "любить").should == "я не люблю"
sentence.present_negation_for("вы", "любить").should == "вы не любите"
sentence.present_negation_for("мы", "любить").should == "мы не любим"
sentence.present_negation_for("они", "любить").should == "они не любят"
sentence.present_negation_for("он", "любить").should == "он не любит"
sentence.present_negation_for("она", "любить").should == "она не любит"
end
it "#past_statement_for" do
sentence.past_statement_for("я", "любить").should == "я любил"
sentence.past_statement_for("вы", "любить").should == "вы любили"
sentence.past_statement_for("мы", "любить").should == "мы любили"
sentence.past_statement_for("они", "любить").should == "они любили"
sentence.past_statement_for("он", "любить").should == "он любил"
sentence.past_statement_for("она", "любить").should == "она любила"
end
it "#past_question_for" do
sentence.past_question_for("я", "любить").should == "я любил?"
sentence.past_question_for("вы", "любить").should == "вы любили?"
sentence.past_question_for("мы", "любить").should == "мы любили?"
sentence.past_question_for("они", "любить").should == "они любили?"
sentence.past_question_for("он", "любить").should == "он любил?"
sentence.past_question_for("она", "любить").should == "она любила?"
end
it "#past_negation_for" do
sentence.past_negation_for("я", "любить").should == "я не любил"
sentence.past_negation_for("вы", "любить").should == "вы не любили"
sentence.past_negation_for("мы", "любить").should == "мы не любили"
sentence.past_negation_for("они", "любить").should == "они не любили"
sentence.past_negation_for("он", "любить").should == "он не любил"
sentence.past_negation_for("она", "любить").should == "она не любила"
end
it "#future_statement_for" do
sentence.future_statement_for("я", "любить").should == "я буду любить"
sentence.future_statement_for("вы", "любить").should == "вы будете любить"
sentence.future_statement_for("мы", "любить").should == "мы будем любить"
sentence.future_statement_for("они", "любить").should == "они будут любить"
sentence.future_statement_for("он", "любить").should == "он будет любить"
sentence.future_statement_for("она", "любить").should == "она будет любить"
end
it "#future_question_for" do
sentence.future_question_for("я", "любить").should == "я буду любить?"
sentence.future_question_for("вы", "любить").should == "вы будете любить?"
sentence.future_question_for("мы", "любить").should == "мы будем любить?"
sentence.future_question_for("они", "любить").should == "они будут любить?"
sentence.future_question_for("он", "любить").should == "он будет любить?"
sentence.future_question_for("она", "любить").should == "она будет любить?"
end
it "#future_negation_for" do
sentence.future_negation_for("я", "любить").should == "я не буду любить"
sentence.future_negation_for("вы", "любить").should == "вы не будете любить"
sentence.future_negation_for("мы", "любить").should == "мы не будем любить"
sentence.future_negation_for("они", "любить").should == "они не будут любить"
sentence.future_negation_for("он", "любить").should == "он не будет любить"
sentence.future_negation_for("она", "любить").should == "она не будет любить"
end
end
<file_sep>require_relative 'sentence'
require_relative 'string'
require 'yaml'
class English_Sentence < Sentence
def initialize
@irregular_verbs = YAML.load_file("./db/irregular_verbs.yml")
end
def present_statement_for(pronoun, verb)
verb += "s" if self.class.is_he_she_it? pronoun
"#{pronoun} #{verb}"
end
def present_question_for(pronoun, verb)
do_does = "do"
do_does += "es" if self.class.is_he_she_it? pronoun
"#{do_does} #{pronoun} #{verb}?"
end
def present_negation_for(pronoun, verb)
do_does = "do"
do_does += "es" if self.class.is_he_she_it? pronoun
"#{pronoun} #{do_does}n't #{verb}"
end
def past_statement_for(pronoun, verb)
verb = @irregular_verbs[verb] ? @irregular_verbs[verb]["second"] : verb[0..-2]+"ed" if verb.ends_with? "e"
"#{pronoun} #{verb}"
end
def past_question_for(pronoun, verb)
"did #{pronoun} #{verb}?"
end
def past_negation_for(pronoun, verb)
"#{pronoun} didn't #{verb}"
end
def future_statement_for(pronoun, verb)
"#{pronoun} will #{verb}"
end
def future_question_for(pronoun, verb)
"will #{pronoun} #{verb}?"
end
def future_negation_for(pronoun, verb)
"#{pronoun} will not #{verb}"
end
end
|
97891a645ffe7942b9f2514e3528b6e919d1c6c2
|
[
"Ruby"
] | 10
|
Ruby
|
techtronics/learn-english-16
|
04988e796b0d7396326ff5d0fc55aded2353216a
|
415ffe56b9b3402fb3e2c7f0d3626d3105504115
|
refs/heads/master
|
<repo_name>jenn2318/React-Bootstrap-Test-App<file_sep>/Test/react-bootstrap/src/components/LastCallEats.js
import React, { Component } from 'react'
import { Grid, Row, Col, Image } from 'react-bootstrap';
import './LastCallEats.css';
export default class LastCallEats extends Component {
render() {
return (
<div>
<Image src="assets/atl_ga.jpeg" className="header-image" />
<Grid>
<h2>Food Selections</h2>
<Row>
<Col xs={12} sm={8} className="main-section">
<p>Here are some great selections based on your favortie foods: Please choose some below</p>
</Col>
<Col xs={12} sm={4} className="sidebar-section">
<h2> LastCall Mission</h2>
<p> Here is why we want to be your number one late night food app in Atlanta. We offer selections without you having to search high and low.</p>
</Col>
</Row>
</Grid>
</div>
)
}
}<file_sep>/Test/react-bootstrap/src/components/Home.js
import React, { Component } from 'react'
import { Link } from 'react-router-dom';
import { Jumbotron, Grid, Row, Col, Image, Button } from 'react-bootstrap';
import './Home.css';
export default class Home extends Component {
render() {
return (
<Grid>
<Jumbotron>
<h2>Welcome to LastCall</h2>
<p>This is a Restaurant App that will give suggestions for Late Night Restaurants </p>
<Link to="/about">
<Button bsStyle="primary">Login</Button>
</Link>
</Jumbotron>
<Image src="assets/late_night_dt.jpeg" className="header-image" />
<Row className="show-grid text-center">
<Col sx={12} sm={4} className="container-wrapper">
<Image src="assets/burger.jpeg" circle className="profile-pic" />
<h3>Buy Quick Bites</h3>
<p>These options are Fast Food based</p>
</Col>
<Col sx={12} sm={4} className="container-wrapper">
<Image src="assets/gourmet1.jpeg" circle className="profile-pic" />
<h3>Give Me Gourmet</h3>
<p>If you want more of a home cooked feel</p>
</Col>
<Col sx={12} sm={4} className="container-wrapper">
<Image src="assets/tapas3.jpeg" circle className="profile-pic" />
<h3>Try Some Tapas</h3>
<p>Here you can choose light options</p>
</Col>
</Row>
</Grid>
)
}
}<file_sep>/README.md
# React-Bootstrap-Test-App
Testing React Bootstrap
<file_sep>/Test/react-bootstrap/src/components/About.js
import React, { Component } from 'react'
import { Grid, Col, Image } from 'react-bootstrap';
import './About.css';
export default class About extends Component {
render() {
return (
<div>
ABOUT PAGE
<Image src="assets/late_night_dt.jpeg" className="header-image" />
<Grid>
<Col xs={12} sm={8} smOffest={2}>
<Image src="assets/open_late.jpeg" className="about-late-night" rounded />
<h3>Select Your Zipcode</h3>
<p>We offer selections in restaurants and bars</p>
</Col>
</Grid>
</div>
)
}
}
|
e2ef0930f0398f0fbb26f425d2a8ebb594a58367
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
jenn2318/React-Bootstrap-Test-App
|
753c553a882c4dd435ba67b8e4f8eba3a7648638
|
1beb51985537535f808c50a14e8495c2d6884a84
|
refs/heads/master
|
<file_sep># urchin
<div style="text-align:center"><img src ="https://github.com/keeganjk/urchin/blob/master/img/urchin.GIF?raw=true"></div>
Reverse shell that lets you connect to others computers through the shell when they run the client.
### Supported platforms:
> <h5>Windows</h5>
> <h5>MacOS</h5>
> <h5>Linux</h5>
## What is it?
Urchin is a reverse shell that is writen in `Python 2`. It uses `socket` to send commands over the Internet. Urchin is a reverse-shell, meaning that a server can host a server and get the client to run the client script. The client will connect the user to the server, which will grant the server shell access to the client's computer.
## How to use it
> ### 1. Download
> Firstly, on any OS, you would navigate to https://github.com/keeganjk/urchin. Once on this page, click the button that says "Clone or Download" and then "Download as ZIP".
> <br />
> 
> <br />
> If you are on Unix (Linux, macOS, or BSD), you can type <code>git clone https://github.com/keeganjk/urchin</code> into the terminal to
> clone this repository and then <code>mv</code> into the directory. If you do this, skip to step 3.
<hr>
> ### 2. Extract files
> Nextly, extract the ZIP file and then move into the `urchin` folder.
<hr>
> ### 3. Download and install `Python 2` if not already installed
> Navigate to [Python Downloads](https://www.python.org/downloads/release/python-2713) and download `Python 2` for your OS.
<hr>
> ### 4. Run `urchin.py`
> To run `urchin.py`, the process is different depending on your operating system.
> On Windows:
> 1. Click on `urchin.py` and Python will run it.
> On MacOS/Linux:
> 1. Open the terminal.
> 2. Navigate to `urchin.py`
> 3. Type `chmod +x *` to allow e`x`ecution of all files in the directory.
> 4. You will have to remove the `.py` extension or replace it with `.command`.
> 5. You can run `urchin` by any of the below methods:
> 1. Click on `urchin`
> 2. Run `./urchin`
> 3. Run `python urchin`
<hr>
> ### 6. Build client
> Edit `client.py`. Find the line that says `host = 127.0.0.1`. Replace `127.0.0.1` with the server's IP Address.
<hr>
> ### 7. Give the file to client.
> After building the client, you will need to give it to a client.
> The client will need to have `Python 2` installed, unless you use the methods below:<br/>
> If the client is using Windows:<br/>
> 1. Download and install [py2exe](https://sourceforge.net/projects/py2exe/ "py2exe"). <br/>
> 2. Open CMD and run this command: `python filename.py py2exe`<br/>
> 3. Send EXE to client, put it in a ZIP file if you can't send an EXE.<br/>
>
> If the client is using MacOS:<br/>
> 1. Open the terminal and type `chmod +x filename`<br/>
> 2. Put the file in a folder<br/>
> 3. Open Disk Utility.<br/>
> 4. From the top menu, select `File` > `New Image` > `Image from Folder...`<br/>
> 5. A DMG will be generated.<br/>
> 6. Send it to your client.<br/>
>
> If the client is on Linux, you're just about out of luck on compilations. They'll have to `chmod` and run by themself.
<hr>
> ### 8. Allow connections
> Run `urchin` before the client runs the file.
> Once the client has connected, you will be notified and you will have a command prompt of `$ `.
> From here, you can enter commands to run on the client.
> Type `quit` to close the connection.
<file_sep>#!/usr/bin/python
import socket, os, sys, platform
if 'Windows' in platform.system():
os.system('cls')
print " | | | ,---` ,---` | | ----- ,---`"
print " \ * / | | | | | | | | | |"
print " -*+*- | | |---, | |---| | | |"
print " / * \ | | | \ | | | | | |"
print " | `___, | \ `___, | | ----- | |"
print ""
print " Made by <NAME> (keeganjk)"
print " Version: 1.0"
else:
os.system("clear")
print " | | | ,---` ,---` | | ----- ,---`"
print " \ * / | | | | | | | | | |"
print " -*+*- | | |---, | |---| | | |"
print " / * \ | | | \ | | | | | |"
print " | `___, | \ `___, | | ----- | |"
print ""
print " Made by <NAME> (\033[1;31mkeeganjk\033[0;0m)"
print " Version: 1.0"
port = 31337
s = socket.socket()
s.bind(('', port))
print ""
print " Waiting for connection ..."
s.listen(1)
while True:
c, addr = s.accept()
print " Accepted connection from", addr, "!"
print ""
while True:
cmd = raw_input("$ ")
if cmd == "python":
while cmd != "exit()":
cmd = raw_input(">>> ")
if cmd == "exit":
print "Use exit() to exit"
cmd = "python -c '" + cmd + "'"
c.send(cmd)
print c.recv(1024)
elif cmd == "bash":
while True:
cmd = raw_input("bash$ ")
cmd = "bash -c '" + cmd + "'"
c.send(cmd)
print c.recv(1024)
elif cmd == "quit" or cmd == "exit":
c.send('quit')
s.close()
sys.exit(1)
else:
c.send(cmd)
print c.recv(1024)
<file_sep>#!/usr/bin/python
import socket, os, sys
s = socket.socket()
host = '127.0.0.1'
port = 31337
s.connect((host, port))
while True:
cmd = s.recv(1024)
if cmd[:2] == "cd":
os.chdir(str(cmd[3:]))
o = " "
s.send(o)
elif cmd == "quit":
s.close()
sys.exit(1)
else:
o = os.popen(cmd).read()
s.send(o)
|
09d94cd3a5669f5f382ee1cee880c9ba8ea34bf2
|
[
"Markdown",
"Python"
] | 3
|
Markdown
|
PentestinGxRoot/urchin
|
6dacf45a3397604f6298fccceae836834d973d54
|
3c91f4248e314a128329fe982229a9a3490b6863
|
refs/heads/master
|
<repo_name>Chocobo1/image_optimize_helpers<file_sep>/README.md
# image_optimize_helpers
## Notes for myself
Most of the time, I'll want:
```shell
python enumFiles.py | concurrent -
```
* `enumFiles.py`:
Enumerate files in a directory (and subdirectories).
* `recurisve = True`: list files in subdirectories.
* `ext = None`: list all files.
`ext = "png"`: list only PNG files.
* `transcode.py`
All the hard work of manipulating files safely & handling unicode filenames are done here.
* Choose 1 helper function from the below list:
| Helper | Notes |
| ------ | ----- |
| `runDeflopt()` | Optimize PNG files via [Deflopt](https://web.archive.org/web/20140209022101/http://www.walbeehm.com/download/) |
| `runOptipng()` | Optimize PNG files via [OptiPNG](http://optipng.sourceforge.net/). |
| `runPngout()` | Optimize PNG files via [PNGOUT](http://advsys.net/ken/utils.htm). |
| `optimizePNG()` | A sequence of actions (that I often use) to compress PNG files. |
| `runJpegoptim()` | Optimize JPG files via [jpegoptim](https://github.com/tjko/jpegoptim). |
| `runCwebp()` | Run [WebP](https://developers.google.com/speed/webp/). |
* [`concurrent`](https://github.com/Chocobo1/concurrent)
A tool to utilize multicore CPU.
<file_sep>/transcode.py
#!/bin/python3
def processFile(file, newExt, cmdLine, quiet = False):
"""
file: Input, the file to be processed
newExt: Input, the file extension after processing. If `None`, then it will be the same as file
cmdLine: Input, the command line to be invoked, will replace "%input%" & "%ouput%" fields
"""
# start
import os
import shutil
import subprocess
import sys
import tempfile
print("\n processing: %s \n" % file)
fsplit = file.rsplit(".", 1)
origFileName = fsplit[0]
origFileExt = fsplit[1]
if not newExt:
newExt = origFileExt
# copy file to a temp file, workaround unicode file name issues
tmpDir = os.getcwd()
subDir = origFileName.rsplit(os.sep, 1)
if len(subDir) > 1: # have subdirectories
tmpDir += os.sep + subDir[0]
tmpFile = tempfile.NamedTemporaryFile(dir = tmpDir, suffix = "." + origFileExt, delete = False)
tmpFile.close()
shutil.copyfile(file, tmpFile.name)
# process command
tmpInputName = tmpFile.name
tmpOutputName = tmpFile.name.rsplit(".", 1)[0] + "." + newExt
cmdLine2 = cmdLine.replace("%input%", '"' + tmpInputName + '"').replace("%output%", '"' + tmpOutputName + '"')
# without shell, linux cannot find bin in $PATH
shellArg = True
if sys.platform == "win32":
shellArg = False
# redirect stdout & stderr to /dev/null
quietArg = None
if quiet:
quietArg = open(os.devnull, 'w')
runProg = subprocess.Popen(cmdLine2, shell = shellArg, stdout = quietArg, stderr = subprocess.STDOUT)
runProg.wait()
if quiet:
quietArg.close()
# cleanup
shutil.move(tmpOutputName, origFileName + "." + newExt)
try:
os.remove(tmpInputName)
except OSError:
pass
def runDeflopt(file):
processFile(file, newExt = None, cmdLine = "deflopt %input%", quiet = True)
def runOptipng(file):
processFile(file, newExt = "png", cmdLine = "optipng -o7 %input%", quiet = True)
def runPngout(file):
processFile(file, newExt = "png", cmdLine = "pngout %input%", quiet = True)
def runZopflipng(file):
processFile(file, newExt = "png", cmdLine = "zopflipng -m -y %input% %output%", quiet = True)
def optimizePNG(file):
import os
newSize = os.stat(file).st_size
fileSize = newSize + 1
while newSize < fileSize:
fileSize = newSize
runPngout(file)
runOptipng(file)
newSize = os.stat(file).st_size
runDeflopt(file)
def runJpegoptim(file):
processFile(file, newExt = None, cmdLine = "jpegoptim -s %input%", quiet = True)
def runCwebp(file):
processFile(file, newExt = "webp", cmdLine = "cwebp.exe -v -lossless -q 100 -m 6 %input% -o %output%", quiet = True)
if __name__ == "__main__":
import sys
import win32_unicode_argv
arg1 = sys.argv[1]
runCwebp(arg1)
<file_sep>/enumFiles.py
#!/bin/python3
def enumFilesFilter(dir, ext = None, recurisve = False):
"""
dir: Input, the target directory
ext: Input, only files ends with this field will be listed. If `None`, then no filtering will be done
recursive: Input, whether go into subdirectories
return a list of names of files (could contain relative path)
"""
import os
ret = []
walker = os.walk(str(dir))
for path, _, filenames in walker:
relPath = path[(len(dir) + 1):]
if relPath:
fileFullPaths = [relPath + os.sep + x for x in filenames]
else:
fileFullPaths = filenames
ret += fileFullPaths
if not recurisve:
break
if ext:
ret = [f for f in ret if f.endswith(ext)]
return ret
def generateCmds(fileList, cmdLine):
"""
fileList, Input list, the list of files to be processed
cmdLine, Input, the command line string, the string "%listEntry%" will be replaced by entries in `fileList`
"""
ret = [cmdLine.replace("%listEntry%", f) for f in fileList]
return ret
def printList(cmdList):
for c in cmdList:
print(c)
if __name__ == "__main__":
import os
currentDir = os.getcwd()
filesList = enumFilesFilter(currentDir, ext = "png", recurisve = False)
if filesList:
cmdsList = ["### Threads: 3 ###"]
cmdsList += generateCmds(filesList, cmdLine = "python transcode.py \"%listEntry%\"")
printList(cmdsList)
|
411d74d5c3019d91b24bd4876135d30dcf090213
|
[
"Markdown",
"Python"
] | 3
|
Markdown
|
Chocobo1/image_optimize_helpers
|
ec615e3edf9bfa5b0fd89c394946ce79f2a35d73
|
12c15b5a00bece51e753f6cc253f915b5c38c89a
|
refs/heads/master
|
<file_sep>package e.tamen.newapp;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.method.BaseKeyListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.sql.Ref;
import java.util.Calendar;
import java.util.Date;
public class MainActivity extends AppCompatActivity {
public enum ENUM_Gamer
{
correct, attention, addict, none
}
private String m_mail = "";
private String m_name = "";
private String m_firstName = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Affichage du nom de l'application dans la console
Log.i("Log info : ", getResources().getString(R.string.app_name));
//Récupération de la date
Date currentDate = Calendar.getInstance().getTime();
//Affichage de la date
TextView txt_dateRef = (TextView)findViewById(R.id.TXT_DATE);
txt_dateRef.setText(currentDate.toString());
//Référencements des champs Nom, Prénom, et Mail
final TextView txt_nameRef = (TextView)findViewById(R.id.TXT_NAME),
txt_firstNameRef = (TextView)findViewById(R.id.TXT_FIRSTNAME),
txt_mailRef = (TextView)findViewById(R.id.TXT_MAIL);
//Opérations de création du mail
txt_nameRef.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_ENTER && txt_nameRef.getText().length() > 0)
{
m_name = txt_nameRef.getText().toString().toLowerCase();
}
return false;
}
});
//Après mise à jour du prénom, le mail s'actualise dans le champ txt_mailRef
txt_firstNameRef.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_ENTER && txt_firstNameRef.getText().length() > 0)
{
m_firstName = txt_firstNameRef.getText().toString().toLowerCase();
//Mise à jour du champ "Mail"
m_mail = m_firstName.toLowerCase().charAt(0) + "." + m_name + "@.<EMAIL>";
txt_mailRef.setText(m_mail);
}
return false;
}
});
//Référencement des checkbox
final CheckBox[] chkRefs = new CheckBox[] {
(CheckBox)findViewById(R.id.CHK_C),
(CheckBox)findViewById(R.id.CHK_CPP),
(CheckBox)findViewById(R.id.CHK_Csharp)
};
//Référencement des radios
final RadioGroup rad_genderRef = (RadioGroup)findViewById(R.id.RADGRP_GENDER);
//Affichage du toast en fonction du sexe de la personne
rad_genderRef.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
String welcomeTxt = (group.getCheckedRadioButtonId() == 0) ? "Bienvenue Madame" : "Bienvenue Monsieur";
Context currentContext = getApplicationContext();
Toast newToast = Toast.makeText(currentContext,welcomeTxt,Toast.LENGTH_SHORT);
newToast.show();
}
});
//Référencement du champ contenant le nombre d'heures par sem
final TextView nb_hoursRef = (TextView)findViewById(R.id.NB_HOURS);
nb_hoursRef.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_ENTER && nb_hoursRef.getText().length() > 0)
{
//Définit l'état (correct, attention, addict) d'un joueur en fonction de son nombre d'heures via les opérateurs ternaires
ENUM_Gamer gamerState = Integer.parseInt(nb_hoursRef.getText().toString()) > 48 ?
ENUM_Gamer.addict
: (Integer.parseInt(nb_hoursRef.getText().toString()) > 24) ?
ENUM_Gamer.attention
: (Integer.parseInt(nb_hoursRef.getText().toString()) > 0) ?
ENUM_Gamer.correct : ENUM_Gamer.correct;
String toastText = gamerState.toString();
Context currentContext = getApplicationContext();
Toast toast = Toast.makeText(currentContext, toastText, Toast.LENGTH_SHORT);
//Référencement du toast
TextView toastRef = (TextView) toast.getView().findViewById(android.R.id.message);
switch(gamerState)
{
case correct:
toastRef.setTextColor(Color.GREEN);
break;
case attention:
toastRef.setTextColor(getResources().getColor(R.color.orange));
break;
case addict:
toastRef.setTextColor(Color.RED);
toast.setDuration(Toast.LENGTH_LONG);
break;
default:
break;
}
toast.show();
}
return false;
}
});
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
//Bouton RAZ
Button resetRef = (Button)findViewById(R.id.BT_RESET);
resetRef.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
txt_nameRef.setText("");
txt_firstNameRef.setText("");
txt_mailRef.setText("");
for(int i = 0; i < chkRefs.length; i++)
{
chkRefs[i].setChecked(false);
}
//Les
nb_hoursRef.setText("");
Log.i("Log info : ", "RAZ");
}
});
//Bouton Validation
Button confirmRef = (Button)findViewById(R.id.BT_CONFIRM);
confirmRef.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String languages = "";
for(int i = 0 ; i < chkRefs.length; i++)
{
if(chkRefs[i].isChecked())
{
languages = languages.concat(chkRefs[i].getText().toString() + ", ");
}
}
if(languages == "")
languages = "none";
else
languages = languages.substring(0, languages.length()-2);
//Concaténation des informations
Log.i("Log info : ",
"Informations : Name : " + txt_nameRef.getText().toString() +
". First name : " + txt_firstNameRef.getText().toString() +
". Email : " + txt_mailRef.getText().toString() +
". Languages : " + languages +
". Gender : " + ((rad_genderRef.getCheckedRadioButtonId() == 0) ? "Female" : "Male") +
". Gaming hours per week : " + nb_hoursRef.getText().toString());
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
322db2a108d523b1c0e77e2a647846ac057b8b25
|
[
"Java"
] | 1
|
Java
|
AlvesAppMob/001.AppMobile
|
a4fe4efa4e53eede771073ac3a4455a699f6a8ac
|
9f95734642305742212e3778c8d8d68e198e8189
|
refs/heads/master
|
<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;cin>>t;
while(t--){
int g1,s1,b1,g2,s2,b2;
cin>>g1>>s1>>b1>>g2>>s2>>b2;
int sum1=g1+s1+b1;
int sum2=g2+s2+b2;
if(sum1>sum2)cout<<1<<endl;
else cout<<2<<endl;
}
return 0;
}
<file_sep>T = int(input())
for _ in range(T):
n, p, k = map(int, input().split())
ans = 0
a = p%k - 1
b = ((n-1)//k)*k
b = n - 1 - b
if (a>b):
ans += (b+1)*((n-1)//k + 1) +(a-b)*((n-1)//k)
else:
ans += ((n-1)//k + 1)*(a+1)
for i in range(a+1, n, k):
ans += 1
if (i==p):
print(ans)
break
<file_sep>#include <bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;cin>>t;
while(t--){
vector<int> v;
for(int i=0;i<4;i++){
int v1;
cin>>v1;
v.push_back(v1);
}
set<int> s;
for(int i=0;i<4;i++) s.insert(v[i]);
int k=s.size();
if(k==4)cout<<2;
if(k==3)cout<<2;
if(k==2){
sort(v.begin(),v.end());
int z=v[0],cnt=0;
for(int i=0;i<4;i++){
if(z==v[i])cnt++;
}
if(cnt==2)cout<<2;
else cout<<1;
}
if(k==1)cout<<0;
cout<<"\n";
}
return 0;
}
<file_sep># Aug_Long_Codechef_Soln
August Challenge 2021 Division 2 (Unrated)
|
f8901cfa5eed6bb1d8e5744741235d7e0c288c3b
|
[
"Markdown",
"Python",
"C++"
] | 4
|
C++
|
negiaditi/Aug_Long_Codechef_Soln
|
61fb57f388ff648861ef1a8b93f4dfecc7abe2e1
|
72380f620f29bfa2bb4c2a3ddd77dab2e07654d7
|
refs/heads/main
|
<file_sep>#ifndef WATER_QUALITY_H_
#define WATER_QUALITY_H_
#include "tuya_ble_common.h"
#include "tuya_ble_log.h"
#define GOOD 0
#define COMMON 1
#define POOR 2
void water_quality_fun(void);
int water_value_get(void);
#endif
<file_sep>#include "water_quality.h"
#define TIME_MS 1000
#define BUF_LEN ((sizeof(DP_buf)) / (sizeof(DP_buf[0])))
unsigned long sys_time = 0;
uint8_t DP_buf[4] = {0x65, 0x04, 0x01, 0x00}; //{DP_ID, DP_type, DP_len, DP_data}
int water_value_get(void)
{
uint16_t water_val;
water_val = adc_sample_and_get_result();
TUYA_APP_LOG_INFO("water_val:%d", water_val);
return water_val;
}
void water_quality_fun(void)
{
if(!clock_time_exceed(sys_time, 1000 * TIME_MS)){
return;
}
sys_time = clock_time();
lux_adc_init();
if (water_value_get() >= 0x00 && water_value_get() <= 0x1E) {
DP_buf[3] = GOOD;
TUYA_APP_LOG_INFO("good_quality");
} else if (water_value_get() > 0x1E && water_value_get() <= 0x64) {
DP_buf[3] = COMMON;
TUYA_APP_LOG_INFO("common_quality");
} else {
DP_buf[3] = POOR;
TUYA_APP_LOG_INFO("poor_quality");
}
tuya_ble_dp_data_report(DP_buf, BUF_LEN);
}
|
5708874594ea0dec048de32b2a53dd443001974c
|
[
"C"
] | 2
|
C
|
Tuya-Community/tuya-iotos-embeded-demo-ble-water-quality-inspection
|
15b651857039f7c435e02a6820a7a3939db53096
|
4e51d05bb270cf3323f08fced80b49a6cdf84d9d
|
refs/heads/master
|
<file_sep>package com.example.baidu.retrofit.Activity.wanAndroid;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.baidu.retrofit.Activity.Rx2Activity;
import com.example.baidu.retrofit.Bean.home.ArticalBean;
import com.example.baidu.retrofit.Bean.home.ArticleBean;
import com.example.baidu.retrofit.Bean.home.ResultBean;
import com.example.baidu.retrofit.Bean.home.UserBean;
import com.example.baidu.retrofit.R;
import com.example.baidu.retrofit.util.RetrofitUtil;
import java.util.Properties;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
public class LoginActivity extends Rx2Activity {
@BindView(R.id.logo)
ImageView logo;
@BindView(R.id.name_icon)
ImageView nameIcon;
@BindView(R.id.name)
EditText name;
@BindView(R.id.password_icon)
ImageView passwordIcon;
@BindView(R.id.password)
EditText password;
@BindView(R.id.login)
Button login;
@BindView(R.id.register)
TextView register;
private String names;
private String passwords;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login3);
ButterKnife.bind(this);
}
@Override
protected void nationalizationData(Properties prop) {
}
@Override
protected void init() {
super.init();
names = name.getText().toString().trim();
passwords = password.getText().toString().trim();
}
@OnClick({R.id.login, R.id.register})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.login:
login(names, passwords);
break;
case R.id.register:
break;
}
}
private void login(String name, String password) {
// if(TextUtils.isEmpty(name) && TextUtils.isEmpty(passwords)){
// Toast.makeText(mContext,"请检查账号名称和密码",Toast.LENGTH_LONG).show();
// return;
// }
// RetrofitUtil.getTestService().login("<EMAIL>", "<PASSWORD>").subscribeOn(Schedulers.io())
// .observeOn(AndroidSchedulers.mainThread())
// .subscribe(new Observer<ResultBean<UserBean>>() {
//
//
// @Override
// public void onSubscribe(Disposable d) {
//
// }
//
// @Override
// public void onNext(ResultBean<UserBean> userBeanResultBean) {
// Log.d("UserBean", userBeanResultBean.getData().getCollectids().size() + "");
// }
//
// @Override
// public void onError(Throwable e) {
//
// }
//
// @Override
// public void onComplete() {
//
// }
// });
}
}
<file_sep>package com.example.baidu.retrofit;
import android.app.Application;
import com.tool.cn.utils.CrashHandler;
import com.tool.cn.utils.LogUtils;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.im.android.api.JMessageClient;
public class MyApplication extends Application {
private static MyApplication instance;
public String registrationID;
@Override
public void onCreate() {
super.onCreate();
// MultiDex.install(this);
instance = this;
LogUtils.isDebug(true);
CrashHandler.getInstance().init(this);
JPushInterface.setDebugMode(true);
JPushInterface.init(this);
registrationID = JPushInterface.getRegistrationID(this);
// MobSDK.init(this, "2dc08f5fc143e", "5dd794d8c9662b965f8182f7d9b503c8");
JMessageClient.setDebugMode(true);
JMessageClient.init(this);
// if (LeakCanary.isInAnalyzerProcess(this)) {
// // This process is dedicated to LeakCanary for heap analysis.
// // You should not init your app in this process.
// return;
// }
// LeakCanary.install(this);
// //搜集本地tbs内核信息并上报服务器,服务器返回结果决定使用哪个内核。
//
// QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {
//
// @Override
// public void onViewInitFinished(boolean arg0) {
// // TODO Auto-generated method stub
// //x5內核初始化完成的回调,为true表示x5内核加载成功,否则表示x5内核加载失败,会自动切换到系统内核。
// Log.d("app", " onViewInitFinished is " + arg0);
// }
//
// @Override
// public void onCoreInitFinished() {
// // TODO Auto-generated method stub
// }
// };
// //x5内核初始化接口
// QbSdk.initX5Environment(getApplicationContext(), cb);
CrashHandler.getInstance().init(this);
}
public static MyApplication getInstance() {
return instance;
}
}
<file_sep>package com.eyes.see.java;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import javax.xml.soap.Node;
/**
* @author
* @date 2020/1/15.
* GitHub:
* email:
* description:
*/
public class arrayList {
/**
* ArrayList是非线程安全外
*
* @param args
*/
public static void main(String[] args) {
List<String> strings = Collections.synchronizedList(new ArrayList<String>());
List<String> string = new ArrayList<>();
LinkedList<Integer> linkedList = new LinkedList<>();
}
}
<file_sep>package com.example.baidu.retrofit.Study;
public class Event {
/*
关于事件传递的机制,这里给出一些结论,根据这些结论可以更好地理解整个传递机制,如下所示。
(1)同一个事件序列是指从手指接触屏幕的那一刻起,到手指离开屏幕的那一刻结束,在这个过程中所产生的一系列事件,
这个事件序列以down事件开始,中间含有数量不定的move事件,最终以up事件结束。
(2)正常情况下,一个事件序列只能被一个View拦截且消耗。这一条的原因可以参考(3),
因为一旦一个元素拦截了某此事件,那么同一个事件序列内的所有事件都会直接交给它处理,
因此同一个事件序列中的事件不能分别由两个View同时处理,但是通过特殊手段可以做到,比如一个View将本该自己处理的事件通过onTouchEvent强行传递给其他View处理。
(3)某个View一旦决定拦截,那么这一个事件序列都只能由它来处理(如果事件序列能够传递给它的话),并且它的onInterceptTouchEvent不会再被调用。
这条也很好理解,就是说当一个View决定拦截一个事件后,那么系统会把同一个事件序列内的其他方法都直接交给它来处理,因此就不用再调用这个View的onInterceptTouchEvent去询问它是否要拦截了。
(4)某个View一旦开始处理事件,如果它不消耗ACTION_DOWN事件(onTouchEvent返回了false),那么同一事件序列中的其他事件都不会再交给它来处理,
并且事件将重新交由它的父元素去处理,即父元素的onTouchEvent会被调用。意思就是事件一旦交给一个View处理,那么它就必须消耗掉,否则同一事件序列中剩下的事件就不再交给它来处理了,这就好比上级交给程序员一件事,如果这件事没有处理好,短期内上级就不敢再把事情交给这个程序员做了,二者是类似的道理。
(5)如果View不消耗除ACTION_DOWN以外的其他事件,那么这个点击事件会消失,此时父元素的onTouchEvent并不会被调用,并且当前View可以持续收到后续的事件,
最终这些消失的点击事件会传递给Activity处理。
(6)ViewGroup默认不拦截任何事件。Android源码中ViewGroup的onInterceptTouch-Event方法默认返回false。
(7)View没有onInterceptTouchEvent方法,一旦有点击事件传递给它,那么它的onTouchEvent方法就会被调用。
(8)View的onTouchEvent默认都会消耗事件(返回true),除非它是不可点击的(clickable 和longClickable同时为false)。View的longClickable属性默认都为false,
clickable属性要分情况,比如Button的clickable属性默认为true,而TextView的clickable属性默认为false。
(9)View的enable属性不影响onTouchEvent的默认返回值。哪怕一个View是disable状态的,只要它的clickable或者longClickable有一个为true,
那么它的onTouchEvent就返回true。
(10)onClick会发生的前提是当前View是可点击的,并且它收到了down和up的事件。
(11)事件传递过程是由外向内的,即事件总是先传递给父元素,然后再由父元素分发给子View,通过requestDisallowInterceptTouchEvent方法
可以在子元素中干预父元素的事件分发过程,但是ACTION_DOWN事件除外
*/
}
<file_sep>package com.example.baidu.retrofit.Adapter;
import android.graphics.Bitmap;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import androidx.annotation.Nullable;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.baidu.retrofit.Bean.GanhuoNews;
import com.example.baidu.retrofit.R;
import com.example.baidu.retrofit.util.bitmap.AsyncDrawable;
import com.example.baidu.retrofit.util.bitmap.ImageAsyncTask;
import com.example.baidu.retrofit.util.bitmap.LoadBigBitMap;
import com.tool.cn.utils.GlideImageManager;
import java.util.List;
import java.util.Random;
public class FirstAdapter extends BaseQuickAdapter<GanhuoNews, BaseViewHolder> {
public FirstAdapter(@Nullable List data) {
super(R.layout.item_first, data);
}
@Override
protected void convert(BaseViewHolder helper, GanhuoNews item) {
String[] urls = new String[]{
"http://ww1.sinaimg.cn/large/0065oQSqly1g2pquqlp0nj30n00yiq8u.jpg",
"https://ww1.sinaimg.cn/large/0065oQSqly1g2hekfwnd7j30sg0x4djy.jpg",
"https://ws1.sinaimg.cn/large/0065oQSqly1g0ajj4h6ndj30sg11xdmj.jpg",
"https://ws1.sinaimg.cn/large/0065oQSqly1fytdr77urlj30sg10najf.jpg",
"https://ws1.sinaimg.cn/large/0065oQSqly1fymj13tnjmj30r60zf79k.jpg",
"https://ws1.sinaimg.cn/large/0065oQSqgy1fy58bi1wlgj30sg10hguu.jpg",
"https://ws1.sinaimg.cn/large/0065oQSqgy1fxno2dvxusj30sf10nqcm.jpg",
"https://ws1.sinaimg.cn/large/0065oQSqgy1fxd7vcz86nj30qo0ybqc1.jpg",
"https://ws1.sinaimg.cn/large/0065oQSqgy1fwyf0wr8hhj30ie0nhq6p.jpg",
"https://ws1.sinaimg.cn/large/0065oQSqgy1fwgzx8n1syj30sg15h7ew.jpg"};
Random random = new Random();
int max = 9;
int min = 0;
int s = random.nextInt(max);
Glide.with(mContext).load(urls[s]).into((ImageView) helper.getView(R.id.iv_image));
}
}
<file_sep>package com.example.commonlibrary.adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.Collections;
import java.util.List;
/**
* 2017/3/15 11:21.
*
*
* @version 1.0.0
* @class CommonViewPagerAdapter
* @describe 公共的ViewPager适配器
*/
public class CommonViewPagerAdapter extends FragmentPagerAdapter {
protected String TAG = getClass().getSimpleName();
private String[] title;
private List<Fragment> fragmentList;
public CommonViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public CommonViewPagerAdapter(FragmentManager fm, List<Fragment> fragmentList,String[] titles) {
super(fm);
title = titles;
this.fragmentList =fragmentList;
}
public void addFragment(Fragment fragment) {
fragmentList.add(fragment);
}
public void addFragments(Fragment... fragment) {
Collections.addAll(fragmentList, fragment);
}
@Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
@Override
public int getCount() {
return fragmentList.size();
}
@Override
public CharSequence getPageTitle(int position) {
return title == null ? "" : title[position];
}
}
<file_sep>package com.example.baidu.retrofit.Study;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import static android.content.Context.MODE_PRIVATE;
public class ContentProviders extends ContentProvider {
public static void main(String[] args) {
String string = "abc";
String s = string = "123";
System.out.println(s + " " + string);
}
@Override
public boolean onCreate() {
return false;
}
@Nullable
@Override
public Cursor query(@NonNull Uri uri, @Nullable String[] projection, @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) {
return null;
}
@Nullable
@Override
public String getType(@NonNull Uri uri) {
return null;
}
@Nullable
@Override
public Uri insert(@NonNull Uri uri, @Nullable ContentValues values) {
return null;
}
@Override
public int delete(@NonNull Uri uri, @Nullable String selection, @Nullable String[] selectionArgs) {
return 0;
}
@Override
public int update(@NonNull Uri uri, @Nullable ContentValues values, @Nullable String selection, @Nullable String[] selectionArgs) {
return 0;
}
/**
* 数据库
*/
static class sqlData extends SQLiteOpenHelper {
/*
dbHelper.getWritableDatabase(); // 会创建一个新的数据库
*/
public sqlData(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// 更新数据库
}
}
private void insert() {
// SQLiteDatabase db = sqlData.getWritableDatabase();
// ContentValues values = new ContentValues();
// // 开始组装第一条数据
// values.put("name", "The Da Vinci Code");
// values.put("author", "<NAME>");
// values.put("pages", 454);
// values.put("price", 16.96);
// db.insert("Book", null, values); // 插入第一条数据
// db.delete("Book", "pages > ?", new String[] { "500" });
}
// ContentResolver
}
<file_sep>package com.example.baidu.retrofit.util;
import android.database.Observable;
public class SmsObserver<T> extends Observable<T> {
public static String SMS_URI;
public interface SmsListener {
void onResult();
}
}
<file_sep>apply plugin: 'java-library'
apply plugin: 'kotlin'
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation("com.google.guava:guava:29.0-jre")
implementation 'io.reactivex.rxjava3:rxandroid:3.0.0'
// Because RxAndroid releases are few and far between, it is recommended you also
// explicitly depend on RxJava's latest version for bug fixes and new features.
// (see https://github.com/ReactiveX/RxJava/releases for latest 3.x.x version)
implementation 'io.reactivex.rxjava3:rxjava:3.0.0'
}
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
sourceCompatibility = "1.8"
targetCompatibility = "1.8"
buildscript {
ext.kotlin_version = '1.3.72'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
repositories {
mavenCentral()
}
compileKotlin {
kotlinOptions {
jvmTarget = "1.8"
}
}
compileTestKotlin {
kotlinOptions {
jvmTarget = "1.8"
}
}
<file_sep>package com.example.baidu.retrofit.Activity.wanAndroid;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import com.example.baidu.retrofit.R;
import com.tool.cn.activity.BaseActivity;
import butterknife.BindView;
import butterknife.ButterKnife;
public class WebViewActivity extends BaseActivity {
@BindView(R.id.webView)
WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
setContentView(R.layout.activity_web_view);
ButterKnife.bind(this);
}
@Override
protected void init() {
Bundle bundle = getIntent().getExtras();
WebSettings settings = null;
if (webView != null) {
settings = webView.getSettings();
}
settings.setJavaScriptEnabled(true);
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
//自己处理所有的网络请求,而不是打开浏览器
WebViewClient client = new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
};
webView.setWebViewClient(client);
String url = bundle.getString("url");
webView.loadUrl(url);
//使webView监听返回键,能够进行网页的返回
webView.setOnKeyListener(
new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
webView.goBack();
return true;
}
return false;
}
}
);
// TextView title = (TextView) findViewById(R.id.title);
// title.setSelected(true);
}
@Override
protected void getHttp() {
}
}
<file_sep>package com.example.commonlibrary.activity;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.tool.cn.R;
import com.tool.cn.utils.AppManager;
import com.tool.cn.utils.KeyBoardUtils;
import com.tool.cn.utils.StatusBarUtils;
import butterknife.ButterKnife;
/**
* 2017/3/9 16:07.
*
*
* @version 1.0.0
* @class BaseActivity
* @describe 公共基类Activity
*/
public abstract class BaseActivity extends AppCompatActivity {
protected String TAG = this.getClass().getSimpleName();
//当前的Context对象,方便内部类使用
protected Context mContext;
//布局填充器
protected LayoutInflater mInflater;
//根布局
protected LinearLayout mLlRoot;
//标题栏
protected Toolbar mToolBar;
// 将被替换的内容布局
protected FrameLayout mFmContent;
// 标题返回局
protected ImageView mIvTitleBack;
//标题图片
protected ImageView mIvTitleName;
// 标题名
protected TextView mTvTitleName;
// 标题右边文字
protected TextView mTvTitleRight;
// 标题右图片
protected ImageView mIvTitleRight;
//标题第二张右图片
protected ImageView mIvTitleRightSecond;
//标题左文字
protected TextView mTvTitleLeft;
// 标题左图片
protected ImageView mIvTitleLeft;
//标题中间区域
protected LinearLayout mLlTitleCenter;
protected FrameLayout mFmTitleRight;
protected FrameLayout mFmBackLeft;
protected boolean isFront = false; //是否在前台显示
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StatusBarUtils.StatusBarDarkMode(this, 3);
mContext = this;
mInflater = getLayoutInflater();
AppManager.getInstance().addActivity(this);// 将activity添加到list中
}
@Override
protected void onDestroy() {
super.onDestroy();
//TODO 释放Context,降低内存泄漏
mContext = null;
AppManager.getInstance().finishActivity(this);
System.gc();
}
//返回事件
@Override
public void onBackPressed() {
super.onBackPressed();
KeyBoardUtils.closeKeyBoard(this);
}
@Override
public void setContentView(@LayoutRes int layoutResID) {
super.setContentView(layoutResID);
ButterKnife.bind(this);
init();
getHttp();
}
/**
* 初始化,由基类Activity调用
*/
protected abstract void init();
protected abstract void getHttp();
@Override
public void onResume() {
super.onResume();
isFront = true;
}
@Override
public void onPause() {
super.onPause();
isFront = false;
}
/**
* 使用默认标题栏
*
* @param contentResID 内容布局id
* @param titleStringRes 标题文字
*/
public void setContentViewWithDefaultTitle(@LayoutRes final int contentResID, @StringRes int titleStringRes) {
this.setContentViewWithDefaultTitle(contentResID, getResources().getString(titleStringRes));
}
/**
* 使用默认标题栏
*
* @param contentResID 内容布局id
* @param titleName 标题文字
*/
public void setContentViewWithDefaultTitle(@LayoutRes final int contentResID, @NonNull String titleName) {
super.setContentView(R.layout.activity_base);
mLlRoot = getViewById(R.id.ll_root);
mToolBar = getViewById(R.id.tb_base);
mFmContent = getViewById(R.id.fm_base_content);
mFmBackLeft = getViewById(R.id.fm_title_left);
mIvTitleLeft = getViewById(R.id.iv_title_left);
mTvTitleLeft = getViewById(R.id.tv_title_left);
mFmTitleRight = getViewById(R.id.fm_title_right);
mTvTitleRight = getViewById(R.id.tv_title_right);
mIvTitleRight = getViewById(R.id.iv_title_right);
mIvTitleRightSecond = getViewById(R.id.iv_title_right_second);
mIvTitleBack = getViewById(R.id.iv_title_back);
mIvTitleName = getViewById(R.id.iv_title);
mTvTitleName = getViewById(R.id.tv_title);
mLlTitleCenter = getViewById(R.id.ll_title_center);
setSupportActionBar(mToolBar);
if (contentResID > 0) {
mInflater.inflate(contentResID, mFmContent);
}
ButterKnife.bind(this);
mTvTitleName.setText(titleName);
setOnClickListeners(mOnClickListener, mFmBackLeft, mFmTitleRight);
init();
}
/**
* 使用默认标题栏
*
* @param contentResID 内容布局id
* @param titleStringRes 标题文字
*/
public void setContentViewWithLeftTitle(@LayoutRes final int contentResID, @StringRes int titleStringRes) {
this.setContentViewWithLeftTitle(contentResID, getResources().getString(titleStringRes));
}
/**
* 使用默认标题栏
*
* @param contentResID 内容布局id
* @param titleName 标题文字
*/
public void setContentViewWithLeftTitle(@LayoutRes final int contentResID, @NonNull String titleName) {
super.setContentView(R.layout.activity_base);
mLlRoot = getViewById(R.id.ll_root);
mToolBar = getViewById(R.id.tb_base);
mFmContent = getViewById(R.id.fm_base_content);
mFmBackLeft = getViewById(R.id.fm_title_left);
mIvTitleLeft = getViewById(R.id.iv_title_left);
mTvTitleLeft = getViewById(R.id.tv_title_left);
mFmTitleRight = getViewById(R.id.fm_title_right);
mTvTitleRight = getViewById(R.id.tv_title_right);
mIvTitleRight = getViewById(R.id.iv_title_right);
mIvTitleRightSecond = getViewById(R.id.iv_title_right_second);
mIvTitleBack = getViewById(R.id.iv_title_back);
mTvTitleName = getViewById(R.id.tv_title);
mLlTitleCenter = getViewById(R.id.ll_title_center);
setSupportActionBar(mToolBar);
if (contentResID > 0) {
mInflater.inflate(contentResID, mFmContent);
}
mTvTitleLeft.setVisibility(View.VISIBLE);
mTvTitleName.setText(titleName);
setOnClickListeners(mOnClickListener, mFmBackLeft, mFmTitleRight);
init();
}
/**
* 设置标题中间区域的View
*
* @param view 标题中间区域的View
*/
protected void setTittleCenterView(View view) {
mLlTitleCenter.removeAllViews();
mLlTitleCenter.addView(view);
}
/**
* 查找View,不用强制转型
*
* @param id 控件的id
* @param <VT> View类型
* @return 对应的View
*/
@SuppressWarnings("unchecked")
protected <VT extends View> VT getViewById(@IdRes int id) {
return (VT) findViewById(id);
}
/**
* 不需要为返回键设置监听,默认为finish当前activity
*/
private View.OnClickListener mOnClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (v.getId() == R.id.fm_title_left) {// 返回
onBackPressed();
} else if (v.getId() == R.id.fm_title_right) {
rightClickEnvent();
}
}
};
/**
* 标题栏右键点击事件
*/
protected void rightClickEnvent() {
}
/**
* 为多个View 添加点击事件
*
* @param listener View.OnClickListener
* @param views View
*/
@Deprecated
protected void setOnClickListeners(View.OnClickListener listener, View... views) {
if (listener != null) {
for (View view : views) {
view.setOnClickListener(listener);
}
}
}
/**
* 解决系统改变字体大小的时候导致的界面布局混乱的问题(不使用系统资源)
*
* @return Resources
*/
@Override
public Resources getResources() {
if (isNeedUseSystemResConfig()) {
return super.getResources();
} else {
Resources res = super.getResources();
Configuration configuration = new Configuration();
configuration.setToDefaults();
res.updateConfiguration(configuration, res.getDisplayMetrics());
return res;
}
}
// 默认返回true,使用系统资源,如果个别界面不需要,
// 在这些activity中Override this method ,then return false;
protected boolean isNeedUseSystemResConfig() {
return true;
}
/**
* 设置Activity进出动画
*
* @param enterAnim 进入动画
* @param exitAnim 消失动画
*/
@Override
public void overridePendingTransition(int enterAnim, int exitAnim) {
super.overridePendingTransition(enterAnim, exitAnim);
}
}
<file_sep>package com.tool.cn.utils;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
/**
* 2017/2/21 15:04.
*
*
* @version 1.0.0
* @class DisplayUtils
* @describe 获取屏幕大小等工具类
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class DisplayUtils {
/**
* Andorid.util 包下的DisplayMetrics 类提供了一种关于显示的通用信息,如显示大小,分辨率和字体。
*
* @param context 上下文对象
* @return DisplayMetrics对象
*/
public static DisplayMetrics getMetrics(Context context) {
DisplayMetrics metrics = new DisplayMetrics();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
return metrics;
}
/**
* dp转pixel
*
* @param context 上下文对象
* @param dp dp
* @return pixel
*/
public static int dp2px(Context context, float dp) {
DisplayMetrics metrics = getMetrics(context);
return (int) (dp * (metrics.densityDpi / 160f));
}
/**
* pixel转dp
*
* @param context 上下文对象
* @param px pixel
* @return dp
*/
public static float px2dp(Context context, float px) {
DisplayMetrics metrics = getMetrics(context);
return px / (metrics.densityDpi / 160f);
}
/**
* 获取屏幕宽度(单位:像素pixel)
*
* @param context 上下文对象
* @return 屏幕宽度
*/
public static int getScreenWidth(Context context) {
DisplayMetrics dm = getMetrics(context);
return dm.widthPixels;
}
/**
* 获取屏幕高度(单位:像素pixel)
*
* @param context 上下文对象
* @return 屏幕宽度
*/
public static int getScreenHeight(Context context) {
DisplayMetrics dm = getMetrics(context);
return dm.heightPixels;
}
/**
* 获取状态栏高度
* (通过反射来实现状态栏高度的获取)
* 注:该方法在任何时候都能正常获取状态栏高度
*
* @param context 上下文对象
* @return 状态栏高度
*/
public static int getStatusBarHeight(Context context) {
int statusHeight = -1;
try {
Class<?> clazz = Class.forName("com.android.internal.R$dimen");
Object obj = clazz.newInstance();
int height = Integer.parseInt(clazz.getField("status_bar_height").get(obj).toString());
statusHeight = context.getResources().getDimensionPixelSize(height);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return statusHeight;
}
/**
* 获取状态栏高度
* (在源码程序中获取状态栏高度)
*
* @param context 上下文对象
* @return 状态栏高度
*/
@Deprecated
public static int getStatusBarHeight2(Context context) {
int statusHeight = 0;
//statusHeight = context.getResources().getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height);
return statusHeight;
}
/**
* 获取状态栏高度(状态栏相对Window的位置)
* 注:在onCreate()方法中无效(返回0)
*
* @param activity Activity
* @return 状态栏高度
*/
public static int getStatusBarHeight(Activity activity) {
Rect frame = new Rect();
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
return frame.top;
}
/**
* 获取标题栏高度
* 注:在onCreate()方法中无效(返回0)
*
* @param activity Activity
* @return 标题栏高度
*/
public static int getTitleBarHeight(Activity activity) {
//获取程序不包括标题栏的部分
View view = activity.getWindow().findViewById(Window.ID_ANDROID_CONTENT);
int contentTop = view.getTop();
int statusBarHeight = getStatusBarHeight(activity);
return contentTop - statusBarHeight;
}
/**
* 获取当前屏幕截图,包含状态栏
*
* @param activity Activity
* @return 当前屏幕截图,包含状态栏
*/
public static Bitmap screenshotWithStatusBar(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap screenBitmap;
screenBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height);
view.destroyDrawingCache();
return screenBitmap;
}
/**
* 获取当前屏幕截图,不包含状态栏
*
* @param activity Activity
* @return 当前屏幕截图,不包含状态栏
*/
public static Bitmap screenshotWithoutStatusBar(Activity activity) {
View view = activity.getWindow().getDecorView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap bitmap = view.getDrawingCache();
int statusBarHeight = getStatusBarHeight(activity);
int width = getScreenWidth(activity);
int height = getScreenHeight(activity);
Bitmap screenBitmap;
screenBitmap = Bitmap.createBitmap(bitmap, 0, statusBarHeight, width, height - statusBarHeight);
view.destroyDrawingCache();
return screenBitmap;
}
/**
* 设置透明状态栏
* 最好用代码设置,style有时有的机型不起作用.
*
* @param activity activity
*/
public static void setTransparentBar(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Window window = activity.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.TRANSPARENT);
}
}
}
<file_sep>package com.example.commonlibrary.utils;
import android.content.Context;
import android.content.res.Resources;
import android.os.Build;
import android.view.ViewConfiguration;
import java.lang.reflect.Method;
/**
* 2017/6/15 16:05.
*
*
* @version 1.0.0
* @class NavigationBarUtils
* @describe 虚拟键相关操作工具类
*/
public class NavigationBarUtils {
/**
* 获取虚拟按键的高度
*
* @param context 上下文对象
* @return 虚拟按键的高度
*/
public static int getNavigationBarHeight(Context context) {
int result = 0;
if (hasNavigationBar(context)) {
Resources resources = context.getResources();
int resourcesId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourcesId > 0) {
result = resources.getDimensionPixelSize(resourcesId);
}
}
return result;
}
/**
* 检查是否存在虚拟按键栏
*
* @param context 上下文对象
* @return 是否存在虚拟按键栏
*/
public static boolean hasNavigationBar(Context context) {
Resources res = context.getResources();
int resourcesId = res.getIdentifier("config_showNavigationBar", "bool", "android");
if (0 != resourcesId) {
boolean hasNav = res.getBoolean(resourcesId);
String isOverrideNavBar = getNavigationBarOverride();
if ("1".equals(isOverrideNavBar)) {
hasNav = false;
} else if ("0".equals(isOverrideNavBar)) {
hasNav = true;
}
return hasNav;
} else {
return !ViewConfiguration.get(context).hasPermanentMenuKey();
}
}
/**
* 判断虚拟案件栏是否被重写
*
* @return 虚拟案件栏是否被重写
*/
public static String getNavigationBarOverride() {
String sNavBarOverride = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
try {
Class c = Class.forName("android.os.SystemProperties");
Method method = c.getDeclaredMethod("get", String.class);
method.setAccessible(true);
sNavBarOverride = (String) method.invoke(null, "qemu.hw.mainkeys");
} catch (Exception e) {
//e.printStackTrace();
sNavBarOverride = "1";
}
}
return sNavBarOverride;
}
}
<file_sep>package com.example.baidu.retrofit.Study;
/**
* 记录android 版本特点
*
*/
public class Version {
/**
*
*
Version 5.0:
1.material design
2.支持多种设备
Android系统的身影早已出现在多种设备中,比如:智能手机、平板电脑、笔记本电脑、智能电视、汽车、智能手表甚至是各种家用电子产品等。
3.全新的通知中心设计
谷歌在Android 5.0中加入了全新风格的通知系统。改进后的通知系统会优先显示对用户来说比较重要的信息,而将不太紧急的内容隐藏起来。用户只需要向下滑动就可以查看全部的通知内容,如图1-2所示。
4.支持 64 位 ART虚拟机
Android 5.0内部的性能上也提升了不少,它放弃了之前一直使用的Dalvik虚拟机,改用了ART虚拟机,实现了真正的跨平台编译,在ARM、X86、MIPS 等无处不在。
5.Overview
多任务视窗现在有了一
6.设备识别解锁
现在个人识别解锁已经被普遍使用,比如当特定的智能手表出现在Android设备的附近时,就会直接绕过锁屏界面进行操作。而Android 5.0也增加了这种针对特定设备识别解锁的模式。换句话说,当设备没有检测到附近有可用的信任设备时,就会启动安全模式以防止未授权访问。
7.Ok Google语音指令
当手机处于待机状态时,对你的手机轻轻说声“Ok Google”,手机即刻被唤醒,只需说出简单的语言指令,如播放音乐、查询地点、拨打电话和设定闹钟等,一切只需“说说”而已。
8.Face unlock面部解锁
在Android 5.0中,Google花费大力气优化了面部解锁功能。当用户拿起手机处理锁屏界面上的消息通知时,面部解锁功能便自动被激活。随意浏览几条消息之后,手机已经默默地完成了面部识别。
Version 6.0:
1.应用权限管理
在Android 6.0中,应用许可提示可以自定义了。它允许对应用的权限进行高度管理,比如应用能否使用位置、相机、网络和通信录等,这些都开放给开发者和用户。此前的 Android 系统的应用权限管理只能靠第三方应用来实现,在Android 6.0中应用权限管理成为系统级的功能。
2.Android Pay
Android Pay是Android支付统一标准。Android 6.0系统中集成了Android Pay,其特性在于简洁、安全和可选性。它是一个开放性平台,用户可以选择谷歌的服务或者使用银行的App来使用它。Android Pay支持Android 4.4以后的系统设备并且可以使用指纹来进行支付。
3.指纹支持
虽然很多厂商的 Android 手机实现了指纹的支持,但是这些手机都使用了非谷歌认证的技术。这一次谷歌提供的指纹识别支持,旨在统一指纹识别的技术方案。
4.Doze电量管理
Android 6.0自带Doze电量管理功能。手机静止不动一段时间后,会进入Doze电量管理模式。谷歌表示,当屏幕处于关闭状态时,平均续航时间可提高30%。
5.App Links
Android 6.0加强了软件间的关联,允许开发者将App和他们的Web域名关联。谷歌大会展示了App Links的应用场景,比如你的手机邮箱里收到一封邮件,内文里有一个Twitter链接,点击该链接可以直接跳转到Twitter应用,而不再是网页。
6.Now on Tap
在桌面或App的任意界面,长按Home键即可激活Now on Tap,它会识别当前屏幕上的内容并创建Now卡片。比如,你和某人聊天时提到一起去一家餐馆吃饭,这时你长按Home键,Now on Tap就会创建Now卡片提供这家餐馆的地址和评价等相关信息。如屏幕中出现电话号码,它就会提供一个拨号的标志,你可以直接拨打;而无须先复制,然后再粘贴到拨号界面。它还可以识别日历、地址、音乐、地标等信息。Now on Tap能够快速便捷地帮助用户,完成用户需求,这在很大程度上解放了用户的嘴和双手。这可以说是自Google Now发布以来最为重大的一次升级。
Version 7.0:
Version 9.0: Pie
1.室内WiFi定位 RTT
支持IEEE 802.11mc WiFi协议,通过该协议可以实现基于WiFi的室内定位,
2.异形屏支持
就是俗称的刘海屏支持,根据DisplayCutout可以获得刘海屏的缺口数量、位置和大小等相关信息。方便开发者进行适配。
3.多摄像头支持
在9.0上,你可以同时获取多个视频流。
4.ImageDecoder
9.0引入了新的图像类ImageDecoder,提供了更加现代化的方法来解码图片。用于替代老的BitmapFactory 和 BitmapFactory.Options APIs。
5.Animation
引入AnimatedImageDrawable类用于绘制和显示GIF。
Oreo 8.0:
1.画中画模式
允许Activity启动picture-in-picture (PIP) mode。
2. Notification
引入channel的概念,必须设置。
3. 自动填充框架
没有仔细看,应该需要Google Service配合,国内不用考虑了。
4.可下载字体
8.0以后支持应用后期下载字体文件而不是打包在APK里面。这样可以有效减少APK体积。
5.XML中声明字体
8.0以后支持将字体文件保存在resource资源文件夹中,同时生成对应的R文件,这样就不必再放在asset文件夹中了。并且支持在对应xml中编写字体库。
6.自适应大小的TextView
官方支持TextView根据控件尺寸来决定其内部文字的大小。(我之前还自己写过一个类似的,很多坑,现在终于有官方的了,喜大普奔)
7.新的WebView API
Version API
Google SafeBrowsing API
Termination Handle API
Renderer Importance API
8.快捷菜单
就是常见的桌面在长按某个应用图标,可以弹出一些子菜单,方便用户直接实现某步操作,
Nougat 7.0
1.多窗口支持(分屏显示)
官方详细文档
2.手机和平板设备上,用户可以同时运行两个应用在同一屏幕上。
TV上,应用可以将自己设置为画中画模式,允许用户在浏览别的应用时继续显示。
3.Notification增强
其实每代新版本发布,或多或少都会Notification进行一定的优化和调整,介于这次调增相对大些,就大致介绍下。
4.自定义消息风格
5.打包通知
6.直接回复
7.自定义view
8.JIT/AOT 交叉编译
9.在5.0引入ART模式,以AOT编译模式替代了JIT模式,在7.0后,Google又在ART模式中新加入了JIT模式的编译器,让JIT帮助AOT进行混合编译,提高应用的运行性能,节省磁盘空间占用。提高应用和系统更新速度。
10.SurfaceView加强
7.0后使用SurfaceView将会比TextureView更加省电。
11.Vulkan支持
12.新Emoji
13.OpenGL ES 3.2
14.VR支持
*
*/
}
<file_sep>package com.eyes.see.java;
import java.util.HashMap;
/**
* @author
* @date 2020/1/15.
* GitHub:
* email:
* description:
*/
public class Hashmaps {
private static HashMap<String, String> mHashMap = new HashMap<>();
public static void main(String[] args) {
mHashMap.put("1", "2");
String value = mHashMap.put("1", "3");
System.out.println(value);
System.out.println("100".hashCode());
System.out.println(mHashMap.get("1"));
mHashMap.put("", "23");
mHashMap.put("", "");
System.out.println(mHashMap.get("") + "34343242");
//
//
// System.out.println(Integer.highestOneBit(10));
//
// System.out.println(1 << 30);
}
/**
* 取最高位的值(不管后面位置数据)
* example-->10
* 0000 1010
* <p>
* 0000 1111
* -0000 0111
* ----------
* 0000 1000
*
* @param i
* @return
*/
public static int highestOneBit(int i) {
// HD, Figure 3-1
i |= (i >> 1);
i |= (i >> 2);
i |= (i >> 4);
i |= (i >> 8);
i |= (i >> 16);
return i - (i >>> 1);
}
}
<file_sep>apply plugin: 'com.android.library'
android {
compileSdkVersion 28
defaultConfig {
minSdkVersion 15
targetSdkVersion 28
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:28.0.0'
//noinspection GradleCompatible
//butterknife注解框架,https://github.com/JakeWharton/butterknife
implementation 'com.jakewharton:butterknife:10.0.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.0.0'
//一个为glide提供图片转换的Android类库,内部已依赖Glide,https://github.com/wasabeef/glide-transformations
//https://github.com/bumptech/glide
//compile 'jp.wasabeef:glide-transformations:2.0.1'
implementation 'jp.wasabeef:glide-transformations:4.0.1'
implementation 'com.readystatesoftware.systembartint:systembartint:1.0.3'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.github.bumptech.glide:glide:4.8.0'
// annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
}
<file_sep>package com.example.baidu.retrofit.util;
import android.content.Context;
import com.allenliu.versionchecklib.callback.APKDownloadListener;
import com.allenliu.versionchecklib.core.http.HttpHeaders;
import com.allenliu.versionchecklib.core.http.HttpParams;
import com.allenliu.versionchecklib.core.http.HttpRequestMethod;
import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.RequestVersionListener;
import com.example.baidu.retrofit.Api;
import java.io.File;
import io.reactivex.annotations.Nullable;
/**
* 版本检测
*/
public class Versionchecklib {
public static void checkVersion(Context context) {
AllenVersionChecker.getInstance()
.downloadOnly(crateUIData())
.setApkDownloadListener(new APKDownloadListener() {
@Override
public void onDownloading(int progress) {
}
@Override
public void onDownloadSuccess(File file) {
}
@Override
public void onDownloadFail() {
}
})
.setShowNotification(false)
.setForceRedownload(true)
.executeMission(context);
}
/**
* @return
* @important 使用请求版本功能,可以在这里设置downloadUrl
* 这里可以构造UI需要显示的数据
* UIData 内部是一个Bundle
*/
private static UIData crateUIData() {
UIData uiData = UIData.create();
uiData.setTitle("itle");
uiData.setDownloadUrl("http://test-1251233192.coscd.myqcloud.com/1_1.apk");
uiData.setContent("32");
return uiData;
}
}
<file_sep>interface Study {
fun readBooks()
fun doWork()
}<file_sep>package com.example.commonlibrary.dialog;
import android.content.Context;
import com.tool.cn.R;
/**
* 2017/8/8 11:28.
*
*
* @version 1.0.0
* @class LoadingDialog
* @describe LoadingView
*/
public class LoadingDialog extends BaseDialog {
private static LoadingDialog loadingDialog;
public LoadingDialog(Context context) {
super(context, R.layout.dialog_loading, R.style.Theme_Dialog);
}
@Override
protected void initView() {
}
/**
* 显示等待框
*/
public static void showLoadding(Context context) {
if (null == loadingDialog) {
loadingDialog = new LoadingDialog(context);
}
loadingDialog.show();
}
/**
* 隐藏等待框
*/
public static void dismissLoadding() {
if (null != loadingDialog && loadingDialog.isShowing()) {
loadingDialog.dismiss();
loadingDialog = null;
}
}
@Override
public void onBackPressed() {
dismissLoadding();
}
}
<file_sep>package com.example.commonlibrary.utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
/**
* 2017/4/24 17:04.
*
*
* @version 1.0.0
* @class DeviceInfoUtils
* @describe 设备信息帮助类
*/
public class DeviceInfoUtils {
/**
* 获取手机IMEI
*
* @param context
* @return
*/
public static final String getIMEI(Context context) {
try {
//实例化TelephonyManager对象
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//获取IMEI号
@SuppressLint("MissingPermission") String imei = telephonyManager.getDeviceId();
//再次做个验证,也不是什么时候都能获取到的啊
if (imei == null) {
imei = "";
}
return imei;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* 获取手机IMSI
*/
public static String getIMSI(Context context) {
try {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//获取IMSI号
@SuppressLint("MissingPermission") String imsi = telephonyManager.getSubscriberId();
if (null == imsi) {
imsi = "";
}
return imsi;
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* 获取app当前的渠道号或application中指定的meta-data
*
* @return 如果没有获取成功(没有对应值,或者异常),则返回值为空
*/
public static String getAppMetaData(Context context, String key) {
if (context == null || TextUtils.isEmpty(key)) {
return null;
}
String channelNumber = null;
try {
PackageManager packageManager = context.getPackageManager();
if (packageManager != null) {
ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
if (applicationInfo != null) {
if (applicationInfo.metaData != null) {
channelNumber = applicationInfo.metaData.getString(key);
}
}
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
return channelNumber;
}
/**
* 获取显示屏参数
*
* @return 显示屏参数
*/
public static String getDisplay() {
return Build.DISPLAY;
}
/**
* 获取手机制造商
*
* @return 手机制造商
*/
public static String getProduct() {
return Build.PRODUCT;
}
/**
* 获取版本
*
* @return 版本
*/
public static String getModel() {
return Build.MODEL;
}
/**
* 获取CPU指令集
*
* @return CPU指令集
*/
public static String getCPU_ABI() {
return Build.CPU_ABI;
}
/**
* 获取设备参数
*
* @return 设备参数
*/
public static String getDevice() {
return Build.DEVICE;
}
/**
* 获取硬件名称
*
* @return 硬件名称
*/
public static String getFingerprint() {
return Build.FINGERPRINT;
}
/**
* 获取Android系统定制商
*
* @return Android系统定制商
*/
public static String getBrand() {
return Build.BRAND;//http://dev.xiaomi.com/doc/p=9494/index.html
}
}
<file_sep>package com.example.baidu.retrofit.service;
import cn.jpush.android.service.JCommonService;
/**
* @author
* @date 2020/1/8.
* GitHub:
* email:
* description:
*/
public class PushService extends JCommonService {
}
<file_sep>package com.example.baidu.retrofit.Adapter;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.baidu.retrofit.R;
import java.util.ArrayList;
import java.util.List;
/**
* @author
* @date 2020/1/17.
* GitHub:
* email:
* description:
*/
public class TestRecycleViewAdapter extends RecyclerView.Adapter<TestRecycleViewAdapter.ViewHolder> {
private Context mContext;
private List<String> mList;
private List<Integer> heights;
public TestRecycleViewAdapter(Context context, List<String> list) {
this.mContext = context;
this.mList = list;
randomHeight();
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_recycleview_test, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override
public int getItemCount() {
return mList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView mTextView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
mTextView = (TextView) itemView.findViewById(R.id.textview);
}
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
// holder 存在复用问题 ,需要防止混乱
ViewGroup.LayoutParams lp = holder.mTextView.getLayoutParams();
lp.height = heights.get(position);
holder.mTextView.setLayoutParams(lp);
holder.mTextView.setText(mList.get(position));
}
private List randomHeight() {
heights = new ArrayList<>();
for (int i = 0; i < mList.size(); i++) {
heights.add((int) ((int) 100 + Math.random() * 300));
}
return heights;
}
}
<file_sep>apply plugin: 'com.android.application'
//apply plugin: 'kotlin-android-extensions'
//apply plugin: 'kotlin-android'
apply plugin: 'com.github.dcendents.android-maven'
apply plugin: 'com.jakewharton.butterknife'
//apply from: 'mob.gradle'
android {
//
compileSdkVersion 28
defaultConfig {
applicationId "com.example.baidu.retrofit"
minSdkVersion 15
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
packagingOptions { exclude 'META-INF/rxjava.properties' }
ndk {
abiFilters "armeabi", "armeabi-v7a", "x86", "mips"
}
manifestPlaceholders = [
JPUSH_PKGNAME: "com.example.baidu.retrofit",
JPUSH_APPKEY : "ced138d5d31d0ce52f5860c2", //JPush 上注册的包名对应的 Appkey.
JPUSH_CHANNEL: "developer-default", //暂时填写默认值即可.
]
packagingOptions {
doNotStrip '*/mips/*.so'
doNotStrip '*/mips64/*.so'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
multiDexEnabled true
}
sourceSets {
main {
jniLibs.srcDirs = ['libs']
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
// 内存泄漏
// debugApi'com.squareup.leakcanary:leakcanary-android:1.6.2'
// releaseApi'com.squareup.leakcanary:leakcanary-android-no-op:1.6.2'
// Okhttp库
implementation 'com.squareup.okhttp3:okhttp:3.1.2'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
// 日志拦截器
implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
//如果需要集成json解析,还需要添加库:
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
//如果还需要集成rxjava,还需要添加库:
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
//引入rxJava适配器,方便rxJava与retrofit的结合
implementation 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'
//引入J神的rxrelay2,出现异常仍然可以处理
implementation 'com.jakewharton.rxrelay2:rxrelay:2.0.0'
// implementation 'com.hwangjr.rxbus:rxbus:1.0.6'
//butterknife
implementation 'com.jakewharton:butterknife:10.2.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.1'
implementation 'com.github.bumptech.glide:glide:4.8.0'
implementation 'com.allenliu.versionchecklib:library:2.2.1'
// tencent X5 webview
implementation 'com.just.agentwebX5:agentwebX5:2.0.0'
implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.50'
implementation project(path: ':common')
implementation project(path: ':rxbus')
implementation 'com.android.support:design:28.0.0'
implementation 'cn.jiguang.sdk:jpush:3.5.4' // 此处以JPush 3.5.4 版本为例。
implementation 'cn.jiguang.sdk:jcore:2.2.6' // 此处以JCore 2.2.6 版本为例。
implementation 'cn.jiguang.sdk:jmessage:2.9.0' // 此处以JMessage 2.9.0 版本为例。
implementation 'com.android.support:multidex:1.0.3'
implementation 'com.google.android:flexbox:2.0.1'
implementation 'androidx.cardview:cardview:1.0.0'
implementation "com.google.android.material:material:1.0.0"
// compile "androidx.core:core-ktx:+"
// implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
repositories {
mavenCentral()
}
<file_sep>class Student(name :String ,age :Int) : Person(name, age), Study {
override fun readBooks() {
// TODO("Not yet implemented")
println(name + " " + age + " " + "readBooks")
}
override fun doWork() {
// TODO("Not yet implemented")
}
}
fun main() {
var s = Student("hah",12)
s.readBooks()
var s1= Singletons()
s1.tests()
}
<file_sep>package com.example.baidu.retrofit.Bean.home;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
/**
* @author
* @date 2020/4/3.
* GitHub:
* email:
* description:
*/
public class GongZhongHao implements Parcelable {
private List<String> children = new ArrayList<>();
private int courseid;
private int id;
private String name;
private int order;
private int parentchapterid;
private boolean usercontrolsettop;
private int visible;
public void setChildren(List<String> children) {
this.children = children;
}
public List<String> getChildren() {
return children;
}
public void setCourseid(int courseid) {
this.courseid = courseid;
}
public int getCourseid() {
return courseid;
}
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setOrder(int order) {
this.order = order;
}
public int getOrder() {
return order;
}
public void setParentchapterid(int parentchapterid) {
this.parentchapterid = parentchapterid;
}
public int getParentchapterid() {
return parentchapterid;
}
public void setUsercontrolsettop(boolean usercontrolsettop) {
this.usercontrolsettop = usercontrolsettop;
}
public boolean getUsercontrolsettop() {
return usercontrolsettop;
}
public void setVisible(int visible) {
this.visible = visible;
}
public int getVisible() {
return visible;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringList(this.children);
dest.writeInt(this.courseid);
dest.writeInt(this.id);
dest.writeString(this.name);
dest.writeInt(this.order);
dest.writeInt(this.parentchapterid);
dest.writeByte(this.usercontrolsettop ? (byte) 1 : (byte) 0);
dest.writeInt(this.visible);
}
public GongZhongHao() {
}
protected GongZhongHao(Parcel in) {
this.children = in.createStringArrayList();
this.courseid = in.readInt();
this.id = in.readInt();
this.name = in.readString();
this.order = in.readInt();
this.parentchapterid = in.readInt();
this.usercontrolsettop = in.readByte() != 0;
this.visible = in.readInt();
}
public static final Parcelable.Creator<GongZhongHao> CREATOR = new Parcelable.Creator<GongZhongHao>() {
@Override
public GongZhongHao createFromParcel(Parcel source) {
return new GongZhongHao(source);
}
@Override
public GongZhongHao[] newArray(int size) {
return new GongZhongHao[size];
}
};
}
<file_sep>package com.eyes.see.java.utils;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/**
* @author
* @date 2020/3/11.
* GitHub:
* email:
* description:
*/
public class Callable {
/**
* 实现callable 接口
* 线程池执行
* future 回调
*/
public static class TestCallable implements java.util.concurrent.Callable {
@Override
public String call() throws Exception {
return "hellow orld";
}
}
public static void main(String[] args) {
TestCallable testCallable = new TestCallable();
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future mFuture = executorService.submit(testCallable);
try {
System.out.print(mFuture.get().toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>package com.example.baidu.retrofit.util.bitmap;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.widget.ImageView;
import java.lang.ref.WeakReference;
/**
* @author
* @date 2019/12/24.
* GitHub:
* email:
* description: 异步加载图片
*/
public class ImageAsyncTask extends AsyncTask<Integer, Integer, Bitmap> {
private WeakReference imageViewReference;
public int data = 0;
private Context context;
public ImageAsyncTask(ImageView imageView, Context context) {
this.context = context;
// Use a WeakReference to ensure the ImageView can be garbage collected
imageViewReference = new WeakReference(imageView);
}
@Override
protected Bitmap doInBackground(Integer... integers) {
data = integers[0];
return LoadBigBitMap.decodeSampledBitmapFromResource(context.getResources(), data, 100, 100);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (isCancelled()) {
bitmap = null;
}
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = (ImageView) imageViewReference.get();
final ImageAsyncTask bitmapWorkerTask =
AsyncDrawable.getBitmapWorkerTask(imageView);
if (this == bitmapWorkerTask && imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
}
<file_sep>package com.tool.cn.utils;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import java.util.Stack;
/**
* 2017/3/9 15:23.
*
*
* @version 1.0.0
* @class AppManager
* @describe 基类应用程序Activity管理类:管理Activity和应用程序
*/
public class AppManager {
protected static Stack<Activity> mActivityStack;
private static AppManager mInstance;
protected AppManager() {
if (mActivityStack == null) {
mActivityStack = new Stack<Activity>();
}
}
/**
* 获取单例
*/
public static AppManager getInstance() {
if (null == mInstance) {
synchronized (AppManager.class) {
if (null == mInstance) {
mInstance = new AppManager();
}
}
}
return mInstance;
}
/**
* 添加Activity到栈
*/
public void addActivity(Activity activity) {
if (mActivityStack == null) {
mActivityStack = new Stack<Activity>();
}
mActivityStack.add(activity);
}
/**
* @return activity
*/
public Stack<Activity> getActivities() {
return mActivityStack;
}
/**
* 获取顶层Activity
*/
public Activity currentActivity() {
Activity activity = mActivityStack.lastElement();
return activity;
}
/**
* 结束当前Activity(堆栈中后一个压入的Activity)
*/
public void finishActivity() {
Activity activity = mActivityStack.lastElement();
if (activity != null) {
activity.finish();
removeActivity(activity);
}
}
/**
* 结束指定的Activity
*/
public void finishActivity(Activity... activitys) {
for (Activity activity : activitys) {
if (activity != null) {
activity.finish();
removeActivity(activity);
}
}
}
public void removeActivity(Activity activity) {
if (activity != null) {
mActivityStack.remove(activity);
}
}
public void removeActivity(Class<?> cls) {
Activity activity = getActivity(cls);
if (activity != null) {
mActivityStack.remove(activity);
}
}
/**
* 获取指定的Activity对象
*/
public Activity getActivity(Class<?> cls) {
for (int i = 0; i < mActivityStack.size(); i++) {
if (mActivityStack.get(i).getClass().equals(cls)) {
return mActivityStack.get(i);
}
}
return null;
}
/**
* 结束除开指定Activity的其他Activity
*/
public void finishOtherActivity(Class<?> cls) {
for (int i = 0; i < mActivityStack.size(); i++) {
if (!mActivityStack.get(i).getClass().equals(cls)) {
this.finishActivity(mActivityStack.get(i));
//如果不加这一行,remove之后当前元素的下标跟变化之后的size完全不对应,可能会跳过几个元素没有检查或者下标会大于size造成数组越界
i = -1;
}
}
}
/**
* 结束指定类名的Activity
*/
public void finishActivity(Class<?> cls) {
for (Activity activity : mActivityStack) {
if (activity.getClass().equals(cls)) {
this.finishActivity(activity);
return;
}
}
}
/**
* 结束所有Activity
*/
public void finishAllActivity() {
int size = mActivityStack.size();
for (int i = 0; i < size; i++) {
if (null != mActivityStack.get(i)) {
mActivityStack.get(i).finish();
}
}
//移出Stack中所有的元素
mActivityStack.clear();
}
/**
* 退出应用程序
*/
public void AppExit(Context context) {
try {
this.finishAllActivity();
//MobclickAgent.onKillProcess(context);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* delayMillis时间后关闭应用
*/
public void killApplication(final Context context, int delayMillis) {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
AppExit(context);
}
}, delayMillis);
}
}
<file_sep>package com.example.baidu.retrofit.Study;
/**
* 系统垃圾回收
*
*/
public class GC {
}
<file_sep>package com.example.baidu.retrofit.Study;
public class Bundle {
/*
*/
}
<file_sep>package com.example.baidu.retrofit.Study;
public class AndroidOptimization {
/**
*
* android 优化
*
1 布局方面
减少绘制层数
include
viewstub
2 绘制优化
绘制优化是指View的onDraw方法要避免执行大量的操作,这主要体现在两个方面。
首先,onDraw中不要创建新的局部对象,这是因为onDraw方法可能会被频繁调用,这样就会在一瞬间产生大量的临时对象,这不仅占用了过多的内存而且还会导致系统更加频繁gc,
降低了程序的执行效率。
另外一方面,onDraw方法中不要做耗时的任务,也不能执行成千上万次的循环操作,尽管每次循环都很轻量级,但是大量的循环仍然十分抢占CPU的时间片,
这会造成View的绘制过程不流畅。按照Google官方给出的性能优化典范中的标准,View的绘制帧率保证60fps是最佳的,这就要求每帧的绘制时间不超过16ms(16ms = 1000 / 60),
虽然程序很难保证16ms这个时间,但是尽量降低onDraw方法的复杂度总是切实有效的
3. 内存泄露优化:
分析原因:
内存泄漏产生的原因在Android中大致分为以下几种:
1.static变量引起的内存泄漏
因为static变量的生命周期是在类加载时开始 类卸载时结束,也就是说static变量是在程序进程死亡时才释放,如果在static变量中 引用了Activity 那么 这个Activity由于被引用,便会随static变量的生命周期一样,一直无法被释放,造成内存泄漏。
解决办法:
在Activity被静态变量引用时,使用 getApplicationContext 因为Application生命周期从程序开始到结束,和static变量的一样。
2.线程造成的内存泄漏
类似于上述例子中的情况,线程执行时间很长,及时Activity跳出还会执行,因为线程或者Runnable是Acticvity内部类,因此握有Activity的实例(因为创建内部类必须依靠外部类),因此造成Activity无法释放。
AsyncTask 有线程池,问题更严重
解决办法:
1.合理安排线程执行的时间,控制线程在Activity结束前结束。
2.将内部类改为静态内部类,并使用弱引用WeakReference来保存Activity实例 因为弱引用 只要GC发现了 就会回收它 ,因此可尽快回收
3.BitMap占用过多内存
bitmap的解析需要占用内存,但是内存只提供8M的空间给BitMap,如果图片过多,并且没有及时 recycle bitmap 那么就会造成内存溢出。
解决办法:
及时recycle 压缩图片之后加载图片
4.资源未被及时关闭造成的内存泄漏
比如一些Cursor 没有及时close 会保存有Activity的引用,导致内存泄漏
解决办法:
在onDestory方法中及时 close即可
5.Handler的使用造成的内存泄漏
由于在Handler的使用中,handler会发送message对象到 MessageQueue中 然后 Looper会轮询MessageQueue 然后取出Message执行,但是如果一个Message长时间没被取出执行,那么由于 Message中有 Handler的引用,而 Handler 一般来说也是内部类对象,Message引用 Handler ,Handler引用 Activity 这样 使得 Activity无法回收。
解决办法:
依旧使用 静态内部类+弱引用的方式 可解决
6.带参数的单例
https://images2015.cnblogs.com/blog/690927/201606/690927-20160620172701897-2109008457.png
如果我们在在调用Singleton的getInstance()方法时传入了Activity。那么当instance没有释放时,这个Activity会一直存在。因此造成内存泄露。
解决方法:
可以将new Singleton(context)改为new Singleton(context.getApplicationContext())即可,这样便和传入的Activity没关系了。
7. 属性动画导致的内存泄露
果在Activity中播放此类动画且没有在onDestroy中去停止动画,那么动画会一直播放下去,尽管已经无法在界面上看到动画效果了,并且这个时候Activity的View会被动画持有,
而View又持有了Activity,最终Activity无法释放。下面的动画是无限动画,
会泄露当前Activity,解决方法是在Activity的onDestroy中调用animator.cancel()来停止动画。
响应速度,ANR
ListView和Bitmap优化
要分为三个方面:
首先要采用ViewHolder并避免在getView中执行耗时操作;
View view = null;//getView方法要返回的View
if(convertView == null){//如果当前没有可以复用的View
view = LayoutInflater.from(context).inflate(resourceId,null);//那么就从XML文件生成一个View
}else{//否则
view = convertView;//就使用可以复用的View
}
其次要根据列表的滑动状态来控制任务的执行频率,比如当列表快速滑动时显然是不太适合开启大量的异步任务的;
最后可以尝试开启硬件加速来使Listview的滑动更加流畅。注意Listview的优化策略完全适用于GridView。
Bitmap:
(1)将BitmapFactory.Option的inJustDecodeBounds参数设为true并加载图片
(2)从BitmapFactory.Option中取出图片的原始宽高,它们对应于outWidth和outHeight参数
(3) 根据采样率的规则并结合目标View的所需大小计算出采样率inSampleSize。
(4)将BitmapFactory.Option的inJustDecodeBounds参数设为false,然后重新加载图片。
public static Bitmap decodeSampleFromResources(Resource res, int resId, int reqWidth, int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
options.inJustDecodeBoundles = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateSampleSize
{
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > resHeight || width > resWidth) {
final int halfHeight = height / 2;
final int halfwidth = width / 2;
while ((halfHeight / inSampleSize) >= reqHeigh && (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
线程优化
线程优化的思想是采用线程池,避免程序中存在大量的Thread。线程池可以重用内部的线程,从而避免了线程的创建和销毁所带来的性能开销,
同时线程池还能有效地控制线程池的最大并发数,避免大量的线程因互相抢占系统资源从而导致阻塞现象的发生。因此在实际开发中,我们要尽量采用线程池,
而不是每次都要创建一个Thread对象,关于线程池的详细介绍请参考第11章的内容。
本节介绍的是一些性能优化的小建议,通过它们可以在一定程度上提高性能。
1.避免创建过多的对象;
2.不要过多使用枚举,枚举占用的内存空间要比整型大;
3.常量请使用static final来修饰;
4.使用一些Android特有的数据结构,比如SparseArray和Pair等,它们都具有更好的性能;
5.适当使用软引用和软引用;
6.采用内存缓存和磁盘缓存;
7.尽量采用静态内部类,这样可以避免潜在的由于内部类而导致的内存泄露。
*
*/
}
<file_sep>package com.example.baidu.retrofit.Adapter;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.example.baidu.retrofit.R;
public class StaggeredHomeAdapter extends RecyclerView.Adapter{
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return null;
}
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
}
@Override
public int getItemCount() {
return 0;
}
}<file_sep>package com.example.baidu.retrofit;
import java.util.Properties;
public class Constants {
public static String IS_LOGIN;
public static String API_KEY;
public static String TICKET;
public static String retryAfterTips;
public static String FILE_PATH;
public static String APP_LAN;
public static String DOWNLOAD_PATH;
public static String IS_FIRST_LOAD;
public static String noNetwork;
public static int getCaptcha;
public static String surl = "https://www.wanandroid.com/";
public static void nationalizationData(Properties prop) {
}
}
<file_sep>package com.example.commonlibrary.listener;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
/**
* 2017/4/13 11:18.
*
*
* @version 1.0.0
* @class ElasticTouchListener
* @describe 弹性UI实现。
* eg:View.setOnTouchListener(new ElasticTouchListener());
*/
public class ElasticTouchListener implements View.OnTouchListener {
private View mRootView;
private View[] mChildren;
private float mY;
private Rect mNormal = new Rect();
private boolean isAnimationFinish = true;
private int[] mTops;
private int[] mBottoms;
@Override
public boolean onTouch(View v, MotionEvent event) {
if (null == mRootView && null == mChildren) {
if (v instanceof ViewGroup) {
ViewGroup group = (ViewGroup) v;
int count = group.getChildCount();
if (count > 0) {
mChildren = new View[count];
mTops = new int[count];
mBottoms = new int[count];
for (int i = 0; i < count; i++) {
mChildren[i] = group.getChildAt(i);
mTops[i] = mChildren[i].getTop();
mBottoms[i] = mChildren[i].getBottom();
}
}
}
mRootView = v;
}
if (isAnimationFinish && (null != mRootView || null != mChildren)) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
mY = event.getY();
break;
case MotionEvent.ACTION_UP:
mY = 0;
if (isNeedAnimation()) {
animation();
}
mRootView.invalidate();
break;
case MotionEvent.ACTION_MOVE:
float preY = mY == 0 ? event.getY() : mY;
float nowY = event.getY();
int deltaY = (int) (preY - nowY);
mY = nowY;
//当滚动到最上或最下时就不会再滚动,这时移动布局
if (isNeedMove()) {
if (mNormal.isEmpty()) {
mNormal.set(mRootView.getLeft(), mRootView.getTop(), mRootView.getRight(), mRootView.getBottom());
}
if (null != mChildren) {
for (View aMChildren : mChildren) {
aMChildren.layout(aMChildren.getLeft(), aMChildren.getTop() - deltaY / 2, aMChildren.getRight(), aMChildren.getBottom() - deltaY / 2);
}
} else {
mRootView.layout(mRootView.getLeft(), mRootView.getTop() - deltaY / 2, mRootView.getRight(), mRootView.getBottom() - deltaY / 2);
}
}
mRootView.invalidate();
break;
}
} else {
return false;
}
return true;
}
private void animation() {
if (null == mChildren) {
//开启移动动画
TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, 0, mNormal.top - mRootView.getTop());
translateAnimation.setDuration(200);
translateAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
isAnimationFinish = false;
}
@Override
public void onAnimationEnd(Animation animation) {
mRootView.clearAnimation();
//设置回到正常的布局位置
mRootView.layout(mNormal.left, mNormal.top, mNormal.right, mNormal.bottom);
mNormal.setEmpty();
isAnimationFinish = true;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
mRootView.startAnimation(translateAnimation);
} else {
for (int i = 0; i < mChildren.length; i++) {
final View view = mChildren[i];
if (View.VISIBLE == view.getVisibility()) {
final int index = i;
//开启移动动画
TranslateAnimation translateAnimation = new TranslateAnimation(0, 0, 0, mTops[i] - view.getTop());
translateAnimation.setDuration(200);
translateAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
isAnimationFinish = false;
}
@Override
public void onAnimationEnd(Animation animation) {
view.clearAnimation();
//设置回到正常的布局位置
view.layout(view.getLeft(), mTops[index], view.getRight(), mBottoms[index]);
mNormal.setEmpty();
isAnimationFinish = true;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
});
view.startAnimation(translateAnimation);
}
}
}
}
/**
* 是否需要开启动画
*
* @return true需要,false不需要
*/
private boolean isNeedAnimation() {
return !mNormal.isEmpty();
}
/**
* 是否需要移动布局
*
* @return true需要,false不需要
*/
private boolean isNeedMove() {
return true;
}
}
<file_sep>class Singletons {
fun tests() {
println("test")
}
}
object Singleton {
fun singleton() {
println("as a singleton is here")
}
}
fun main() {
Thread(object : Runnable {
override fun run() {
// TODO("Not yet implemented")
var s = Singleton;
s.singleton()
System.out.println("Thread as a singleton is here")
}
}).start()
}<file_sep>package com.example.commonlibrary;
import android.app.Application;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.StrictMode;
import com.tool.cn.utils.DisplayUtils;
import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* 2017/3/15 18:18.
*
*
* @version 1.0.0
* @class BaseApplication
* @describe 公共的Application
*/
public abstract class BaseApplication extends Application {
protected final String TAG = getClass().getSimpleName();
public static int mHeightPixels;//屏幕高度
public static int mWidthPixels;//屏幕宽度
private static Context context;
@Override
public void onCreate() {
super.onCreate();
mHeightPixels = DisplayUtils.getScreenHeight(this);
mWidthPixels = DisplayUtils.getScreenWidth(this);
context = getApplicationContext();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//兼容android7.0 使用共享文件的形式
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
}
closeAndroidPDialog();
}
public static Context getContext() {
return context;
}
/**
* 在子类的onCreate方法中调用创建Project Folder.
*
* @param rootPath eg:"/Common"
*/
@SuppressWarnings("ResultOfMethodCallIgnored")
protected final void createFile(String rootPath) {
//SDCard路径
final String sdCardPath = Environment.getExternalStorageDirectory().getAbsolutePath();
//项目文件夹
final String basePath = sdCardPath + rootPath;
//image文件夹
BaseConstants.IMAGE_PATH = basePath + "/Image/";
//video文件夹
BaseConstants.VIDEO_PATH = basePath + "/video/";
//dowmload文件夹
BaseConstants.DOWNLOAD_PATH = basePath + "/Download/";
//crash异常信息收集文件夹
BaseConstants.CRASH_PATH = basePath + "/Crash/";
File file;
file = new File(basePath);
if (!file.exists()) {
file.mkdirs();
}
file = new File(BaseConstants.IMAGE_PATH);
if (!file.exists()) {
file.mkdirs();
}
file = new File(BaseConstants.DOWNLOAD_PATH);
if (!file.exists()) {
file.mkdirs();
}
file = new File(BaseConstants.CRASH_PATH);
if (!file.exists()) {
file.mkdirs();
}
}
/**
* Android P 后谷歌限制了开发者调用非官方公开API 方法或接口,干掉每次启动都会弹出的提醒窗口
*/
private void closeAndroidPDialog() {
try {
Class aClass = Class.forName("android.content.pm.PackageParser$Package");
Constructor declaredConstructor = aClass.getDeclaredConstructor(String.class);
declaredConstructor.setAccessible(true);
} catch (Exception e) {
e.printStackTrace();
}
try {
Class cls = Class.forName("android.app.ActivityThread");
Method declaredMethod = cls.getDeclaredMethod("currentActivityThread");
declaredMethod.setAccessible(true);
Object activityThread = declaredMethod.invoke(null);
Field mHiddenApiWarningShown = cls.getDeclaredField("mHiddenApiWarningShown");
mHiddenApiWarningShown.setAccessible(true);
mHiddenApiWarningShown.setBoolean(activityThread, true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>package com.example.baidu.retrofit.presenter;
public interface Login2Presenter {
void onSuccess();//登陆成功
void onfail(String msg);//登陆失败
}
<file_sep>package com.example.commonlibrary.utils;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.webkit.MimeTypeMap;
import com.tool.cn.BaseConstants;
import java.io.File;
/**
* 2017/2/21 12:12.
*
*
* @version 1.0.0
* @class IntentUtils
* @describe Activity跳转、获取Intent意图工具类
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class IntentUtils {
public static final String BUNDLE = "BUNDLE";
/**
* 通过类名启动Activity
*
* @param context 上下文对象
* @param cls 要跳转的Activity
*/
public static void openActivity(@NonNull Context context, Class<?> cls) {
openActivity(context, cls, null);
}
/**
* 通过类名启动Activity
*
* @param context 上下文对象
* @param cls 要跳转的Activity
*/
public static void startActivityForResult(@NonNull Context context, Class<?> cls, int requestCode) {
startActivityForResult(context, cls, null, requestCode);
}
/**
* 通过类名启动Activity
*
* @param context 上下文对象
* @param cls 要跳转的Activity
* @param bundle 需要传递的参数,通过IntentUtils.BUNDLE获取参数
*/
public static void openActivity(@NonNull Context context, Class<?> cls, Bundle bundle) {
Intent intent = new Intent(context, cls);
if (null != bundle) {
intent.putExtras(bundle);
}
context.startActivity(intent);
}
/**
* 通过类名启动Activity
*
* @param context 上下文对象
* @param cls 要跳转的Activity
* @param bundle 需要传递的参数,通过IntentUtils.BUNDLE获取参数
*/
public static void startActivityForResult(@NonNull Context context, Class<?> cls, Bundle bundle, int requestCode) {
if (context instanceof Activity) {
Intent intent = new Intent(context, cls);
if (null != bundle) {
intent.putExtras(bundle);
}
((Activity) context).startActivityForResult(intent, requestCode);
}
}
/**
* 开启相机
*/
public static void openCamera(@NonNull Activity context, String photoPath) {
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // 先验证手机是否有sd卡
try {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
Uri uri = Uri.fromFile(new File(photoPath));
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
context.startActivityForResult(intent, BaseConstants.CAMERE_REQUEST_CODE);
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 开启相册
*/
public static void openPhoto(@NonNull Activity context) {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
context.startActivityForResult(intent, BaseConstants.PHOTO_REQUEST_CODE);
}
/**
* 打电话,跳到拨号界面
*
* @param context 上下文对象
* @param mobile 电话号码
*/
public static void callMobile(@NonNull Context context, String mobile) {
if (!TextUtils.isEmpty(mobile)) {
Uri uri = Uri.parse("tel:" + mobile);
context.startActivity(new Intent(Intent.ACTION_DIAL, uri));
} else {
ToastUtils.showToastOnce(context, "号码为空");
}
}
/**
* 获取拨打电话意图
* 需添加权限 {@code <uses-permission android:name="android.permission.CALL_PHONE"/>}
*
* @param context 上下文对象
* @param phoneNumber 电话号码
* @return 拨打电话意图
*/
public static Intent getCallIntent(@NonNull Context context, String phoneNumber) {
if (!TextUtils.isEmpty(phoneNumber)) {
Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + phoneNumber));
return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
} else {
ToastUtils.showToastOnce(context, "号码为空");
return null;
}
}
/**
* 调用系统浏览器打开uri
*
* @param context 上下文
* @param uriRes 需要打开的链接
*/
public static void openSystemBrowser(@NonNull Context context, @StringRes int uriRes) {
openSystemBrowser(context, context.getResources().getString(uriRes));
}
/**
* 调用系统浏览器打开uri
*
* @param context 上下文
* @param uri 需要打开的链接
*/
public static void openSystemBrowser(@NonNull Context context, String uri) {
openSystemBrowser(context, Uri.parse(uri));
}
/**
* 调用系统浏览器打开uri
*
* @param context 上下文
* @param uri Uri链接
*/
public static void openSystemBrowser(@NonNull Context context, Uri uri) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(uri);
context.startActivity(intent);
}
/**
* 获取安装App(支持6.0)的意图
*
* @param filePath 文件路径
* @return intent
*/
public static Intent getInstallAppIntent(@NonNull Context context, @NonNull String filePath) {
File file = FileUtils.getFileByPath(filePath);
return null == file ? null : getInstallAppIntent(context, file);
}
/**
* 获取安装App(支持6.0)的意图
*
* @param file 文件
* @return intent
*/
@SuppressWarnings("ConstantConditions")
public static Intent getInstallAppIntent(@NonNull Context context, @NonNull File file) {
if (file == null) return null;
Intent intent = new Intent(Intent.ACTION_VIEW);
String type;
if (Build.VERSION.SDK_INT < 23) {
type = "application/vnd.android.package-archive";
} else {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(FileUtils.getFileExtension(file));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri contentUri = FileProvider.getUriForFile(context, "com.your.package.fileProvider", file);
intent.setDataAndType(contentUri, type);
}
intent.setDataAndType(Uri.fromFile(file), type);
return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
/**
* 获取卸载App的意图
*
* @param packageName 包名
* @return intent
*/
public static Intent getUninstallAppIntent(@NonNull String packageName) {
Intent intent = new Intent(Intent.ACTION_DELETE);
intent.setData(Uri.parse("package:" + packageName));
return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
/**
* 获取打开App的意图
*
* @param context 上下文对象
* @param packageName 包名
* @return 打开App的意图
*/
public static Intent getLaunchAppIntent(@NonNull Context context, @NonNull String packageName) {
return context.getPackageManager().getLaunchIntentForPackage(packageName);
}
/**
* 获取App具体设置的意图
*
* @param packageName 包名
* @return intent
*/
public static Intent getAppDetailsSettingsIntent(@NonNull String packageName) {
Intent intent = new Intent("android.settings.APPLICATION_DETAILS_SETTINGS");
intent.setData(Uri.parse("package:" + packageName));
return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
/**
* 获取分享文本的意图
*
* @param content 分享文本
* @return intent
*/
public static Intent getShareTextIntent(String content) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, content);
return intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
/**
* 获取分享图片的意图
*
* @param content 文本
* @param imagePath 图片文件路径
* @return intent
*/
public static Intent getShareImageIntent(String content, String imagePath) {
return getShareImageIntent(content, FileUtils.getFileByPath(imagePath));
}
/**
* 获取分享图片的意图
*
* @param content 文本
* @param image 图片文件
* @return intent
*/
public static Intent getShareImageIntent(String content, File image) {
if (!FileUtils.isFileExists(image)) return null;
return getShareImageIntent(content, Uri.fromFile(image));
}
/**
* 获取分享图片的意图
*
* @param content 分享文本
* @param uri 图片uri
* @return intent
*/
public static Intent getShareImageIntent(String content, Uri uri) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, content);
intent.putExtra(Intent.EXTRA_STREAM, uri);
intent.setType("image/*");
return intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
/**
* 获取其他应用组件的意图
*
* @param packageName 包名
* @param className 全类名
* @return intent
*/
public static Intent getComponentIntent(@NonNull String packageName, @NonNull String className) {
return getComponentIntent(packageName, className, null);
}
/**
* 获取其他应用组件的意图
*
* @param packageName 包名
* @param className 全类名
* @param bundle bundle
* @return intent
*/
public static Intent getComponentIntent(@NonNull String packageName, @NonNull String className, Bundle bundle) {
Intent intent = new Intent(Intent.ACTION_VIEW);
if (bundle != null) intent.putExtras(bundle);
ComponentName cn = new ComponentName(packageName, className);
intent.setComponent(cn);
return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
/**
* 获取关机的意图
* 需添加权限 {@code <uses-permission android:name="android.permission.SHUTDOWN"/>}
*
* @return intent
*/
public static Intent getShutdownIntent() {
Intent intent = new Intent(Intent.ACTION_SHUTDOWN);
return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
/**
* 获取跳至拨号界面意图
*
* @param phoneNumber 电话号码
*/
public static Intent getDialIntent(@NonNull String phoneNumber) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phoneNumber));
return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
/**
* 获取跳至发送短信界面的意图
*
* @param phoneNumber 接收号码
* @param content 短信内容
*/
public static Intent getSendSmsIntent(@NonNull String phoneNumber, String content) {
Uri uri = Uri.parse("smsto:" + phoneNumber);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.putExtra("sms_body", content);
return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
/**
* 获取拍照的意图
*
* @param outUri 输出的uri
* @return 拍照的意图
*/
public static Intent getCaptureIntent(@NonNull Uri outUri) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, outUri);
return intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK);
}
private static final String MINETYPE = "application/vnd.android.package-archive";
/**
* 安装Apk文件
*
* @param context 上下文对象
* @param data Uri
*/
public static void installApk(Context context, Uri data) {
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setDataAndType(data, MINETYPE);
// FLAG_ACTIVITY_NEW_TASK 可以保证安装成功时可以正常打开 app
promptInstall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(promptInstall);
}
}
<file_sep>package com.tool.cn.utils;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import androidx.annotation.NonNull;
import java.util.Timer;
import java.util.TimerTask;
import static android.content.Context.INPUT_METHOD_SERVICE;
/**
* 2016/11/9 14:05.
*
*
* @version 1.0.0
* @class KeyBoardUtils
* @describe 软键盘相关工具类
*/
public class KeyBoardUtils{
/**
* 打开软键盘
*
* @param context 上下文对象
* @param editText 输入框
*/
@SuppressWarnings("unused")
public static void openKeyBoard(@NonNull Context context, @NonNull EditText editText) {
InputMethodManager imm = (InputMethodManager) context
.getSystemService(INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.RESULT_SHOWN);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,
InputMethodManager.HIDE_IMPLICIT_ONLY);
}
/**
* 关闭软键盘
*
*/
@SuppressWarnings("unused")
public static void closeKeyBoard(@NonNull Activity activity) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(INPUT_METHOD_SERVICE);
View v = activity.getWindow().peekDecorView();
if (null != v) { //收起软键盘
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
/**
* 打开软键盘(兼容华为手机)
* @param editText
*/
public static void showKeyBoard(final EditText editText) {
if (editText != null) {
editText.setFocusable(true);
editText.setFocusableInTouchMode(true);
editText.requestFocus();
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
try {
InputMethodManager inputManager =
(InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(editText, 0);
} catch (Exception e) {
e.printStackTrace();
}
}
}, 300);
}
}
}<file_sep>package com.example.baidu.retrofit.Adapter.home;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.baidu.retrofit.Activity.wanAndroid.ArticalHistoryActivity;
import com.example.baidu.retrofit.Bean.home.GongZhongHao;
import com.example.baidu.retrofit.R;
import java.util.List;
/**
* @author
* @date 2020/1/3.
* GitHub:
* email:
* description:
*/
public class FirstAdapter extends BaseQuickAdapter<GongZhongHao, BaseViewHolder> implements BaseQuickAdapter.OnItemClickListener {
public FirstAdapter(@Nullable List<GongZhongHao> data) {
super(R.layout.item_android, data);
setOnItemClickListener(this);
}
@Override
protected void convert(@NonNull BaseViewHolder baseViewHolder, GongZhongHao gongZhongHao) {
baseViewHolder.setText(R.id.title, gongZhongHao.getName());
}
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
GongZhongHao gongZhongHao = (GongZhongHao) adapter.getData().get(position);
Bundle bundle = new Bundle();
bundle.putParcelable("item", gongZhongHao);
Intent intent = new Intent(mContext, ArticalHistoryActivity.class);
intent.putExtra("Bundle", bundle);
mContext.startActivity(intent);
}
}
<file_sep>package com.eyes.see.java.thread;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* @author
* @date 2020/4/30.
* GitHub:
* email:
* description:
*/
public class CreateSingleThreadPool {
private static ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
.setNameFormat("demo-pool-%d").build();
private static ExecutorService pool = new ThreadPoolExecutor(5, 200,
0L, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(1024), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
public static void main(String[] args) {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
pool.execute(new Thread(new Runnable() {
@Override
public void run() {
System.out.println("asdasd" + Thread.currentThread().getName());
}
}));
}
}
private static void rightCreate2() {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
pool.execute(new Thread());
}
}
private static void rightCreate() {
ExecutorService executorService = new ThreadPoolExecutor(
5, 10, 10, TimeUnit.SECONDS,
new ArrayBlockingQueue<Runnable>(5));
for (int i = 0; i < 20; i++) {
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println("开始线程池中的任务");
}
});
}
}
private static void test() throws InterruptedException {
ExecutorService executorService = Executors.newSingleThreadExecutor();
for (int i = 0; i < 10; i++) {
final int taskId = i;
Future future = executorService.submit(new Runnable() {
@Override
public void run() {
System.out.println("线程 " + Thread.currentThread().getName() + " 正在执行" + taskId);
}
});
try {
if (future.get() == null) {//如果Future's get返回null,任务完成
System.out.println("任务完成");
} else {
}
} catch (ExecutionException | InterruptedException e) {
e.printStackTrace();
System.out.println("任务失败 " + e.getCause().getMessage());
}
Thread.sleep(2000);
}
}
}
<file_sep>package com.example.baidu.retrofit.util;
/**
* @author
* @date 2020/1/9.
* GitHub:
* email:
* description:
*/
import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.view.View;
import java.io.IOException;
import java.io.InputStream;
public class RealPathFromUriUtils {
private int MAX_SIZE = 1024;
/**
* 根据Uri获取图片的绝对路径
*
* @param context 上下文对象
* @param uri 图片的Uri
* @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
*/
public static String getRealPathFromUri(Context context, Uri uri) {
int sdkVersion = Build.VERSION.SDK_INT;
if (sdkVersion >= 19) { // api >= 19
return getRealPathFromUriAboveApi19(context, uri);
} else { // api < 19
return getRealPathFromUriBelowAPI19(context, uri);
}
}
/**
* 适配api19以下(不包括api19),根据uri获取图片的绝对路径
*
* @param context 上下文对象
* @param uri 图片的Uri
* @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
*/
private static String getRealPathFromUriBelowAPI19(Context context, Uri uri) {
return getDataColumn(context, uri, null, null);
}
/**
* 适配api19及以上,根据uri获取图片的绝对路径
*
* @param context 上下文对象
* @param uri 图片的Uri
* @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
*/
@SuppressLint("NewApi")
private static String getRealPathFromUriAboveApi19(Context context, Uri uri) {
String filePath = null;
if (DocumentsContract.isDocumentUri(context, uri)) {
// 如果是document类型的 uri, 则通过document id来进行处理
String documentId = DocumentsContract.getDocumentId(uri);
if (isMediaDocument(uri)) { // MediaProvider
// 使用':'分割
String id = documentId.split(":")[1];
String selection = MediaStore.Images.Media._ID + "=?";
String[] selectionArgs = {id};
filePath = getDataColumn(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);
} else if (isDownloadsDocument(uri)) { // DownloadsProvider
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
filePath = getDataColumn(context, contentUri, null, null);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
// 如果是 content 类型的 Uri
filePath = getDataColumn(context, uri, null, null);
} else if ("file".equals(uri.getScheme())) {
// 如果是 file 类型的 Uri,直接获取图片对应的路径
filePath = uri.getPath();
}
return filePath;
}
/**
* 获取数据库表中的 _data 列,即返回Uri对应的文件路径
*
* @return
*/
private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
String path = null;
String[] projection = new String[]{MediaStore.Images.Media.DATA};
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (cursor != null && cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
path = cursor.getString(columnIndex);
}
} catch (Exception e) {
if (cursor != null) {
cursor.close();
}
}
return path;
}
/**
* @param uri the Uri to check
* @return Whether the Uri authority is MediaProvider
*/
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
/**
* @param uri the Uri to check
* @return Whether the Uri authority is DownloadsProvider
*/
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
private void setImageView(Uri uri, View mAutographView, Context context) {
String path = RealPathFromUriUtils.getRealPathFromUri(context, uri);
if (path == null) {
path = uri.getPath();
}
int angle = DiyCommonUtil.readPictureDegree(path);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = false;
try {
InputStream inputStream = context.getContentResolver().openInputStream(uri);
BitmapFactory.decodeStream(inputStream, null, options);
inputStream.close();
int height = options.outHeight;
int width = options.outWidth;
int sampleSize = 1;
int max = Math.max(height, width);
if (max > MAX_SIZE) {
int nw = width / 2;
int nh = height / 2;
while ((nw / sampleSize) > MAX_SIZE || (nh / sampleSize) > MAX_SIZE) {
sampleSize *= 2;
}
}
options.inSampleSize = sampleSize;
options.inJustDecodeBounds = false;
Bitmap selectdBitmap = BitmapFactory.decodeStream(context.getContentResolver().openInputStream(uri), null, options);
selectdBitmap = DiyCommonUtil.rotaingImageView(angle, selectdBitmap);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mAutographView.setBackground(BitmapUtil.btimapToDrawable(selectdBitmap, context));
}
} catch (IOException ioe) {
}
}
}
<file_sep>include ':app', ':common', ':rxbus', ':Java1'
project(':Java1').projectDir = new File('Java')<file_sep>package com.example.commonlibrary.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.DrawableRes;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.tool.cn.R;
/**
* 2017/4/12 13:54.
*
*
* @version 1.0.0
* @class BottomNavigationLayout
* @describe 底部导航栏
*/
public class BottomNavigationLayout extends LinearLayout implements View.OnClickListener {
private SparseArray<Tab> mTabs;
private OnTabItemClickListener mOnTabItemClickListener;
private int mLastSelectedPosition;//记录上一次点击的位置
private int mTabSelectedTextColor;
private int mTabUnselectedTextColor;
private int specialPosition = -1; //特殊的view项
public BottomNavigationLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
initAttrs(attrs);
}
private void initAttrs(@Nullable AttributeSet attrs) {
TypedArray typedArray = getResources().obtainAttributes(attrs, R.styleable.BottomNavigationLayout);
mTabSelectedTextColor = typedArray.getColor(R.styleable.BottomNavigationLayout_tab_selected_textColor, getResources().getColor(R.color.colorPrimary));
mTabUnselectedTextColor = typedArray.getColor(R.styleable.BottomNavigationLayout_tab_unselected_textColor, getResources().getColor(R.color.text_gray_color));
typedArray.recycle();
}
/**
* 初始化Tab
*/
private void initTabs() {
mTabs = new SparseArray<>();
Tab tab;
for (int i = 0; i < getChildCount(); i++) {
tab = new Tab();
tab.vTabView = getChildAt(i);
tab.vTabView.setOnClickListener(this);
tab.vTabView.setTag(i);
if (specialPosition != i) {
tab.ivTabSelectedIcon = tab.vTabView.findViewById(R.id.iv_tab_selected_icon);
tab.ivTabUnselectedIcon = tab.vTabView.findViewById(R.id.iv_tab_unselected_icon);
tab.badgeView = tab.vTabView.findViewById(R.id.badgeView);
tab.tvTabName = tab.vTabView.findViewById(R.id.tv_tab_name);
}
mTabs.put(i, tab);
}
//默认选择第一个
mLastSelectedPosition = 0;
refreshSelectedTab();
}
/**
* 添加Tab
*
* @param position Tab的位置
* @param tabSelectedIcon Tab的选中状态的icon
* @param tabUnselectedIcon Tab的未选中状态的icon
* @param tabName Tab的名字
*/
public final void addTab(int position, @DrawableRes int tabSelectedIcon, @DrawableRes int tabUnselectedIcon, String tabName) {
if (null == mTabs) {
initTabs();
}
Tab tab = mTabs.get(position);
tab.ivTabSelectedIcon.setImageResource(tabSelectedIcon);
tab.ivTabUnselectedIcon.setImageResource(tabUnselectedIcon);
tab.tvTabName.setTextColor(mTabUnselectedTextColor);
tab.tvTabName.setText(tabName);
}
@Override
public void onClick(View v) {
boolean isCanChange = true;//是否可以切换,true可以,false不可以。默认可以切换。
int position = (int) v.getTag();
if (mLastSelectedPosition == position && specialPosition != position) return;
if (null != mOnTabItemClickListener) {
isCanChange = mOnTabItemClickListener.onTabItemClick(position);
}
if (isCanChange) {
mLastSelectedPosition = position;
refreshSelectedTab();
}
}
/**
* 获取Tab名字
*
* @param position 要获取名字的Tab位置
* @return Tab名字
*/
public String getTabName(int position) {
return mTabs.get(position).tvTabName.getText().toString().trim();
}
/**
* 设置mark角标数量
*
* @param markPosition 要设置mark的Tab位置。
* @param badgeCount mark 数量。
*/
public void setTabMarkCount(int markPosition, int badgeCount) {
Tab tab = mTabs.get(markPosition);
if (badgeCount > 0) { //数字
tab.badgeView.refresh(badgeCount);
} else if (badgeCount == 0) { //小圆点
tab.badgeView.setVisibility(VISIBLE);
tab.badgeView.invalidate();
} else {
tab.badgeView.setVisibility(GONE);
tab.badgeView.invalidate();
}
}
public void setSelectedTab(int selectedTabIndex) {
mLastSelectedPosition = selectedTabIndex;
refreshSelectedTab();
if (null != mOnTabItemClickListener) {
mOnTabItemClickListener.onTabItemClick(selectedTabIndex);
}
}
/**
* 刷新选择的Tab
*
* @param selectedTabPosition 选中的Tab的角标
*/
public void refreshSelectedTab(int selectedTabPosition) {
mLastSelectedPosition = selectedTabPosition;
refreshSelectedTab();
}
/**
* 刷新选择的Tab
*/
private void refreshSelectedTab() {
for (int i = 0; i < mTabs.size(); i++) {
if (specialPosition != i) {
Tab tab = mTabs.get(i);
if (mLastSelectedPosition == i) {
tab.ivTabSelectedIcon.setVisibility(View.VISIBLE);
tab.ivTabUnselectedIcon.setVisibility(View.GONE);
tab.tvTabName.setTextColor(mTabSelectedTextColor);
} else {
tab.ivTabSelectedIcon.setVisibility(View.GONE);
tab.ivTabUnselectedIcon.setVisibility(View.VISIBLE);
tab.tvTabName.setTextColor(mTabUnselectedTextColor);
}
}
}
}
private class Tab {
private View vTabView;
private ImageView ivTabSelectedIcon;
private ImageView ivTabUnselectedIcon;
private TextView tvTabName;
private BadgeView badgeView;
}
/**
* BottomNavigation子条目点击事件监听器。
*/
public interface OnTabItemClickListener {
/**
* BottomNavigation子条目点击事件回调。
*
* @param clickPosition 点击的子条目的position
* @return true切换成功,false切换失败(不允许切换)。
*/
boolean onTabItemClick(int clickPosition);
}
/**
* 设置BottomNavigation子条目点击事件监听器
*
* @param onTabItemClickListener BottomNavigation子条目点击事件监听器
*/
public void setOnTabItemClickListener(OnTabItemClickListener onTabItemClickListener) {
this.mOnTabItemClickListener = onTabItemClickListener;
}
public int getSpecialPosition() {
return specialPosition;
}
public void setSpecialPosition(int specialPosition) {
this.specialPosition = specialPosition;
}
}
<file_sep>package com.example.baidu.retrofit.Activity.other;
import android.os.Bundle;
import com.example.baidu.retrofit.Activity.Rx2Activity;
import com.example.baidu.retrofit.R;
import java.util.Properties;
public class CustomViewActivity extends Rx2Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_view);
}
@Override
protected void init() {
super.init();
}
@Override
protected void getHttp() {
}
@Override
protected void nationalizationData(Properties prop) {
}
}
<file_sep>package com.example.baidu.retrofit.Activity.other;
import androidx.appcompat.app.AppCompatActivity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import com.example.baidu.retrofit.R;
public class DataBindingActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data_binding);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
init();
}
private void init() {
// ActivityDataBindingBinding viewDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_main);
////
// User userBean = new User();
// userBean.setUser("姜涛");
//
// // setUser这个方法根据Variable标签的name属性自动生成
// // viewDataBinding.setIsLogin(true);
// if (viewDataBinding.getIsLogin()) {
// viewDataBinding.setUser(userBean);
// } else {
// userBean.setUser("hahha");
// viewDataBinding.setUser(userBean);
// }
}
}
<file_sep>package com.example.commonlibrary.utils;
import android.app.Activity;
import android.graphics.Rect;
import android.os.Build;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
/**
* 2017/6/7 15:33.
*
*
* @version 1.0.0
* @class AndroidBugWorkaround
* @describe 解决软键盘弹起时遮挡输入框的终极办法
* <p>
* 注:在全屏模式、使用沉浸式状态栏、h5等情况下设置adjestPan和adjestResize无效,
* 这是Android自1.x到现在的一个Bug(https://code.google.com/p/android/issues/detail?id=5497),
* 此时可使用该方法解决。
* <p>
* 使用方法:在需要的Activity的onCreateff中添加 new AndroidBugWorkaround(this); 即可
*/
public class AndroidBugWorkaround {
private View mChildOfContent;
private int usableHeightPrevious;
private FrameLayout.LayoutParams frameLayoutParams;
private boolean isFullScreen;//true全屏,false非全屏
private Activity mActivity;
public AndroidBugWorkaround(Activity activity) {
isFullScreen = true;
init(activity);
}
public AndroidBugWorkaround(Activity activity, boolean isFullScreen) {
this.isFullScreen = isFullScreen;
init(activity);
}
private void init(Activity activity) {
mActivity = activity;
FrameLayout content = activity.findViewById(android.R.id.content);
mChildOfContent = content.getChildAt(0);
mChildOfContent.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
possiblyResizeChildOfContent();
}
});
frameLayoutParams = (FrameLayout.LayoutParams) mChildOfContent.getLayoutParams();
}
private void possiblyResizeChildOfContent() {
int usableHeightNow = computeUsableHeight();
if (usableHeightNow != usableHeightPrevious) {
int usableHeightSansKeyboard = mChildOfContent.getRootView().getHeight();
int heightDifference = usableHeightSansKeyboard - usableHeightNow;
if (heightDifference > (usableHeightSansKeyboard / 4)) {//软键盘可能可见
frameLayoutParams.height = usableHeightSansKeyboard - heightDifference;
} else {//软键盘可能不可见
//这样设置在有虚拟键开启的手机上如果输入框在底部,会导致虚拟键遮挡输入框
// frameLayoutParams.height = usableHeightSansKeyboard;
frameLayoutParams.height = -1;
}
mChildOfContent.requestLayout();
usableHeightPrevious = usableHeightNow;
}
}
private int computeUsableHeight() {
Rect rect = new Rect();
mChildOfContent.getWindowVisibleDisplayFrame(rect);
if (isFullScreen) {// 全屏模式下: return r.bottom
//此处这样是为了减掉透明状态栏的高度,此处是25dp,具体项目具体调整
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return rect.bottom - DisplayUtils.dp2px(mActivity, 25);
}
return rect.bottom;
} else {//非全屏时减去状态栏高度
return rect.bottom - rect.top;
}
}
}
<file_sep>package com.example.baidu.retrofit.dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;
import com.tool.cn.BaseApplication;
import com.tool.cn.dialog.BaseDialog;
import com.tool.cn.utils.DisplayUtils;
public class CustomDialog extends BaseDialog {
public CustomDialog(Context context, int layoutId, int theme) {
super(context, layoutId, theme);
}
@Override
protected void initView() {
Window window = getWindow();
window.setGravity(Gravity.CENTER);
WindowManager.LayoutParams windowLp = window.getAttributes(); // 获取对话框当前的参数值
windowLp.width = BaseApplication.mWidthPixels - DisplayUtils.dp2px(mContext, 100);
window.setAttributes(windowLp);
setCanceledOnTouchOutside(false); // 设置点击屏幕Dialog不消失
}
}
<file_sep>package com.example.baidu.retrofit.util;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* @author
* @date 2020/3/4.
* GitHub:
* email:
* description:
*/
public class BitmapUtils {
public static Bitmap photoTuya;
private static BitmapUtils btimapUtils;
private Context context;
private BitmapUtils(Context context) {
this.context = context;
}
public static BitmapUtils getBtimapUtil(Context context) {
if (btimapUtils == null) {
synchronized (BitmapUtil.class) {
btimapUtils = new BitmapUtils(context);
}
}
return btimapUtils;
}
/**
* 文件转Bitmap
*/
public Bitmap fileToBitmap(String filePath) {
File file = new File(filePath);
BitmapFactory.Options options = new BitmapFactory.Options();
/**
*压缩长宽各为一半避免图片过大装载不了
*/
options.inPurgeable = true;
options.inSampleSize = 2;
return BitmapFactory.decodeFile(filePath, options);
}
/**
* Bitmap转文件
*/
public File bitmapToFile(Bitmap bitmap, String saveFilePath) {
File file = new File(saveFilePath);//将要保存图片的路径
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
return file;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
/**
* 数组转Bitmap
*/
public Bitmap btyesToBtimap(byte[] bytes) {
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
/**
* Btimap转数组
*/
public byte[] btimapToBtyes(Bitmap bitmap) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
return baos.toByteArray();
}
/**
* Bitmap转Drawable
*/
public static Drawable btimapToDrawable(Bitmap bitmap, Context context) {
return new BitmapDrawable(context.getResources(), bitmap);
}
/**
* Drawable转Bitmap
*/
// public Bitmap drawableToBitmap(Drawable drawable) {
// int w = drawable.getIntrinsicWidth();
// int h = drawable.getIntrinsicHeight();
// // 取 drawable 的颜色格式
// Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
// Bitmap bitmap = Bitmap.createBitmap(w, h, config);
// //建立对应 bitmap 的画布
// Canvas canvas = new Canvas(bitmap);
// drawable.setBounds(0, 0, w, h);
// // 把 drawable 内容画到画布中
// drawable.draw(canvas);
// return bitmap;
// }
/**
* 带圆角的绘制转Bitmap
*/
public Bitmap creatRoundedBitmap(Bitmap bitmap, float roundPx) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Bitmap output = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, w, h);
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
/**
* 带倒影的绘制Bitmap
*/
public Bitmap createReflectionBitmap(Bitmap bitmap) {
final int reflectionGap = 4;
int w = bitmap.getWidth();
int h = bitmap.getHeight();
/**
* 获取矩阵变换
* */
Matrix matrix = new Matrix();
matrix.preScale(1, -1);
Bitmap reflectionImage = Bitmap.createBitmap(bitmap, 0, h / 2, w, h / 2, matrix, false);
Bitmap bitmapWithReflection = Bitmap.createBitmap(w, (h + h / 2), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(bitmapWithReflection);
canvas.drawBitmap(bitmap, 0, 0, null);
Paint deafalutPaint = new Paint();
canvas.drawRect(0, h, w, h + reflectionGap, deafalutPaint);
canvas.drawBitmap(reflectionImage, 0, h + reflectionGap, null);
Paint paint = new Paint();
LinearGradient shader = new LinearGradient(0, bitmap.getHeight(),
0, bitmapWithReflection.getHeight() + reflectionGap,
0x70ffffff, 0x00ffffff, Shader.TileMode.CLAMP);
paint.setShader(shader);
// Set the Transfer mode to be porter duff and destination in
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
// Draw a rectangle using the paint with our linear gradient
canvas.drawRect(0, h, w, bitmapWithReflection.getHeight() + reflectionGap, paint);
return bitmapWithReflection;
}
public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 andkeeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static boolean saveImageToGallery(Context context, Bitmap bmp) {
String storePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "dearxy";
File appDir = new File(storePath);
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
boolean isSuccess = bmp.compress(Bitmap.CompressFormat.JPEG, 60, fos);
fos.flush();
fos.close();
MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getAbsolutePath(), fileName, null);
Uri uri = Uri.fromFile(file);
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
if (isSuccess) {
return true;
} else {
return false;
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public static Drawable BitmapToDrawable(Bitmap bitmap, Context context) {
BitmapDrawable drawbale = new BitmapDrawable(context.getResources(),
bitmap);
return drawbale;
}
public static final Bitmap drawableToBitmap(Drawable drawable) {
Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
drawable.draw(canvas);
return bitmap;
}
public static Bitmap big(Bitmap bitmap, float scale) {
Matrix matrix = new Matrix();
matrix.postScale(scale, scale); //长和宽放大缩小的比例
Bitmap resizeBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
return resizeBmp;
}
public Bitmap getNewBitmap(Bitmap bitmap, int newWidth, int newHeight) {
// 获得图片的宽高.
int width = bitmap.getWidth();
int height = bitmap.getHeight();
// 计算缩放比例.
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 取得想要缩放的matrix参数.
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
// 得到新的图片.
Bitmap newBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
return newBitmap;
}
}
<file_sep>package com.example.commonlibrary.activity;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.tool.cn.utils.StatusBarUtils;
import java.util.ArrayList;
/**
* 2016/5/16 9:56
*
*
* @version 1.0.0
* @class ImageDisplayActivity
* @describe 查看大图
*/
public class ImageDisplayActivity extends BaseActivity implements ViewPager.OnPageChangeListener {
public static final String pickers = "pickers"; //图片数组
public static final String picker = "picker"; //单张图片
public static final String position = "position"; //初始化位置
private ViewPager vp;
private LinearLayout ll_point;
private int mOriginalPosition;
private int length;
private ArrayList<ImageView> imageList = new ArrayList<>();
private ArrayList<View> points = new ArrayList<>();
private ArrayList<String> uriList;
private String pickerPach;
private Bundle bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StatusBarUtils.setTransparent(this);
setContentView(com.tool.cn.R.layout.activity_image_display);
}
@Override
protected void getHttp() {
}
@Override
protected void init() {
StatusBarUtils.StatusBarDarkMode(this, 3);
vp = (ViewPager) findViewById(com.tool.cn.R.id.vp_imageDisplayAty);
ll_point = (LinearLayout) findViewById(com.tool.cn.R.id.ll_imageDisplayAty_points);
bundle = getIntent().getExtras();
uriList = bundle.getStringArrayList(pickers);
pickerPach = bundle.getString(picker);
bundle.clear();
if (pickerPach != null) {
uriList = new ArrayList<>();
uriList.add(pickerPach);
}
if (uriList != null && uriList.size() > 0) {
length = uriList.size();
}
mOriginalPosition = getIntent().getExtras().getInt(position, -1);
initImageSource();// 加载图片
initPoints();// 加载小圆点
vp.setAdapter(new MyPagerAdapter());
if (length == 1) {
vp.setCurrentItem(0);
} else {
vp.setCurrentItem(mOriginalPosition);
}
vp.setOnPageChangeListener(this);
}
public void initImageSource() {
if (length == 1) {
if (uriList.get(0).startsWith("http://")) {
setTouchImageViewWithDrawable(Uri.parse(uriList.get(0)).toString());
} else {
setTouchImageViewWithDrawable(uriList.get(0));
}
ll_point.setVisibility(View.GONE);
vp.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View arg0, MotionEvent arg1) {
return true;
}
});
} else {
for (int i = 0; i < length; i++) {
if (uriList.get(i).startsWith("http://")) {
setTouchImageViewWithDrawable(Uri.parse(uriList.get(i)).toString());
} else {
// setTouchImageViewWithDrawable(Uri.parse(ServerURL.SERVER_CBL_API_URL + uriList.get(i)));
}
}
}
}
public void initPoints() {
for (int i = 0; i < length; i++) {
View v = new View(this);
v.setBackgroundResource(com.tool.cn.R.drawable.icon_zhishiqi_gray);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(15, 15);
params.setMargins(5, 0, 5, 0);
v.setLayoutParams(params);
ll_point.addView(v);
points.add(v);
}
if (mOriginalPosition > -1) {
points.get(mOriginalPosition).setBackgroundResource(com.tool.cn.R.drawable.icon_zhishiqi_white_solid);
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
for (int i = 0; i < length; i++) {
points.get(i).setBackgroundResource(com.tool.cn.R.drawable.icon_zhishiqi_gray);
}
points.get(position).setBackgroundResource(com.tool.cn.R.drawable.icon_zhishiqi_white_solid);
mOriginalPosition = position;
}
@Override
public void onPageScrollStateChanged(int state) {
}
/**
* viewPager适配器
*/
private class MyPagerAdapter extends PagerAdapter {
@Override
public int getCount() {
return imageList.size();
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
try {
container.addView(imageList.get(position), 0);
} catch (Exception e) {
//handler something
}
return imageList.get(position);
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView(imageList.get(position));
}
}
/**
* 给TouchImageView添加Drawable图片
*
* @param pickerPath
*/
private void setTouchImageViewWithDrawable(String pickerPath) {
ImageView iv = new ImageView(this);
RequestOptions options = new RequestOptions()
.override(800)
.circleCrop()
.dontAnimate();
//设置图片
Glide.with(mContext).load(pickerPath)
.apply(options)
.into(iv);
imageList.add(iv);
}
}
<file_sep>package com.example.baidu.retrofit.Activity.wanAndroid;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;
import com.example.baidu.retrofit.Activity.Rx2Activity;
import com.example.baidu.retrofit.Adapter.home.BannerAdapter;
import com.example.baidu.retrofit.Adapter.home.FragmentAdapter;
import com.example.baidu.retrofit.Bean.home.BannerBean;
import com.example.baidu.retrofit.R;
import com.example.baidu.retrofit.fragment.home.ArticalFragment;
import com.example.baidu.retrofit.util.BaseObserver;
import com.example.baidu.retrofit.util.RetrofitUtil;
import com.tool.cn.utils.GlideImageManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
public class HomePageActivity extends Rx2Activity {
@BindView(R.id.viewpager_1)
ViewPager viewpager1;
@BindView(R.id.news)
Button news;
@BindView(R.id.projects)
Button projects;
@BindView(R.id.fragment)
FrameLayout fragment;
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
int index = (viewpager1.getCurrentItem() + 1) % views.size();
viewpager1.setCurrentItem(index);
break;
}
}
};
private List<Fragment> fragments = new ArrayList<>();
private List<String> titles = new ArrayList<>();
private FragmentAdapter mAdapter;
private BannerAdapter mAdapter1;
private List<View> views = new ArrayList<>();
private ArticalFragment mArticalFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_page);
ButterKnife.bind(this);
// startActivity(new Intent(this, LoginActivity.class));
}
@Override
protected void init() {
super.init();
timer();
initFragment();
}
private void initFragment() {
mArticalFragment = new ArticalFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.fragment, mArticalFragment);
transaction.commit();
transaction.show(mArticalFragment);
}
private void timer() {
Runnable r = new Runnable() {
@Override
public void run() {
//do something
//每隔1s循环执行run方法
if (views.size() > 0) {
mHandler.sendEmptyMessageDelayed(0, 10000);
}
mHandler.postDelayed(this, 4000);
}
};
//主线程中调用:
mHandler.postDelayed(r, 4000);//延时100毫秒
}
@Override
protected void getHttp() {
getBanner();
}
@Override
protected void nationalizationData(Properties prop) {
}
private void getBanner() {
RetrofitUtil.getTestService().getBanner().subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new BaseObserver<List<BannerBean>>((Rx2Activity) mContext, false, "getBanner") {
@Override
public void onSuccess(List<BannerBean> bannerBeans) {
for (int i = 0; i < bannerBeans.size(); i++) {
//通过系统提供的实例获得一个LayoutInflater对象
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//第一个参数为xml文件中view的id,第二个参数为此view的父组件,可以为null,android会自动寻找它是否拥有父组件
View view = inflater.inflate(R.layout.home_banner, null);
views.add(view);
ImageView banner = views.get(i).findViewById(R.id.banner);
if (!TextUtils.isEmpty(bannerBeans.get(i).getImagepath())) {
Log.d("TAGPATH", bannerBeans.get(i).getImagepath());
} else {
Log.d("TAGPATH", bannerBeans.get(i).getTitle());
}
GlideImageManager.loadImage(mContext, bannerBeans.get(i).getImagepath(), banner);
}
mAdapter1 = new BannerAdapter(views, mContext);
viewpager1.setAdapter(mAdapter1);
mAdapter1.notifyDataSetChanged();
}
});
}
private void hideAllFragment(FragmentManager fm) {
FragmentTransaction ft = fm.beginTransaction();
// if (!homeFragment.isHidden())
// ft.hide(homeFragment);
// ft.commitAllowingStateLoss();
}
private void oldPage() {
// fragments.add(new FirstFragment());
//
// titles.add("公众号");
//
//
// mAdapter = new FragmentAdapter(getSupportFragmentManager(), fragments, titles, mContext);
//
// viewpager.setAdapter(mAdapter);
// viewpager.clearAnimation();
// viewpager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
// @Override
// public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//
// }
//
// @Override
// public void onPageSelected(int position) {
// }
//
// @Override
// public void onPageScrollStateChanged(int state) {
//
// }
// });
// viewpager.setCurrentItem(0);
}
@OnClick({R.id.news, R.id.projects})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.news:
break;
case R.id.projects:
break;
}
}
}
<file_sep>package com.tool.cn.widget.image;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import androidx.appcompat.widget.AppCompatImageView;
/**
* 2016/6/12 12:08
*
*
* @version 1.0.0
* @class SelfAdaptionImageView
* 描述:宽度match_parent,高度自适应的ImageView
*/
public class SelfAdaptionImageView extends AppCompatImageView {
public SelfAdaptionImageView(Context context) {
super(context);
}
public SelfAdaptionImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SelfAdaptionImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable d = getDrawable();
//父容器传过来的宽度方向上的模式
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
//父容器传过来的高度方向上的模式
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
//父容器传过来的宽度的值
int width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
//父容器传过来的高度的值
int height = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
if (d != null) {
height = (int) Math.ceil((float) width * (float) d.getIntrinsicHeight() / (float) d.getIntrinsicWidth());
height = height + getPaddingTop() + getPaddingBottom();
setMeasuredDimension(width, height);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
<file_sep>package com.example.baidu.retrofit.receiver;
import android.app.ListActivity;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.NotificationMessage;
import cn.jpush.android.helper.Logger;
import cn.jpush.android.service.JPushMessageReceiver;
/**
* @author
* @date 2020/1/8.
* GitHub:
* email:
* description:
*/
public class JpushReceiver extends JPushMessageReceiver {
private static final String TAG = "JIGUANG-Example";
@Override
public Notification getNotification(Context context, NotificationMessage notificationMessage) {
return super.getNotification(context, notificationMessage);
}
@Override
public void onRegister(Context context, String s) {
super.onRegister(context, s);
Log.d(TAG, s);
}
@Override
public void onNotifyMessageArrived(Context context, NotificationMessage notificationMessage) {
Log.d(TAG, notificationMessage.notificationContent);
}
}
<file_sep>package com.example.commonlibrary.utils;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import com.tool.cn.BaseConstants;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 2017/6/19 16:27.
*
*
* @version 1.0.0
* @class PhotoUtils
* @describe 照片处理工具类
* 注:压缩可参考 https://github.com/Curzibn/Luban
*/
public class PhotoUtils {
//-------------------------------------------以下为图片压缩相关内容-------------------------------------------//
/**
* 压缩图片
*
* @param originalPhotoPath 原始图片文件路径
* @param compressFile 压缩后输出的文件
* @return 压缩后的文件
* @throws IOException IOException
*/
public static File compress(String originalPhotoPath, File compressFile) throws IOException {
return compress(originalPhotoPath, compressFile, 50);
}
/**
* 压缩图片
*
* @param originalPhotoPath 原始图片文件路径
* @param compressFile 压缩后输出的文件
* @param compressionValue 压缩比
* @return 压缩后的文件
* @throws IOException IOException
*/
public static File compress(String originalPhotoPath, File compressFile, int compressionValue) throws IOException {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inSampleSize = 1;
BitmapFactory.decodeFile(originalPhotoPath, options);
options.inSampleSize = computeSize(options.outWidth, options.outHeight);
options.inJustDecodeBounds = false;
Bitmap compressBitmap = BitmapFactory.decodeFile(originalPhotoPath, options);
if (null != compressBitmap) {
compressBitmap = rotatingPhoto(originalPhotoPath, compressBitmap);
}
return saveBitmapFile(compressBitmap, compressFile, compressionValue);
}
/**
* Bitmap对象保存为图片文件
*
* @param compressBitmap 原文件bitmap
* @param compressFile 压缩后输出的文件
* @param compressionValue 压缩比
* @return
* @throws IOException
*/
public static File saveBitmapFile(Bitmap compressBitmap, File compressFile, int compressionValue) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (null != compressBitmap) {
compressBitmap.compress(Bitmap.CompressFormat.JPEG, compressionValue, baos);
compressBitmap.recycle();
}
FileOutputStream fos = null;
fos = new FileOutputStream(compressFile);
fos.write(baos.toByteArray());
fos.flush();
fos.close();
baos.close();
return compressFile;
}
/**
* 压缩图片
*
* @param originalFile 原始图片文件
* @param compressFile 压缩后输出的文件
* @return 压缩后的文件
* @throws IOException IOException
*/
public static File compress(File originalFile, File compressFile) throws IOException {
return compress(originalFile.getAbsolutePath(), compressFile);
}
/**
* 旋转图片
*
* @param filePath 图片路径
* @param bitmap 图片生成的bitmap
* @return 旋转后的bitmap
* @throws IOException IOException
*/
private static Bitmap rotatingPhoto(String filePath, Bitmap bitmap) throws IOException {
ExifInterface exifInterface = null;
if (isJpeg(filePath)) {
exifInterface = new ExifInterface(filePath);
}
if (null == exifInterface) return bitmap;
Matrix matrix = new Matrix();
int angle = 0;
int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_90:
angle = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
angle = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
angle = 270;
break;
}
matrix.postRotate(angle);
return null == bitmap ? null : Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
}
private static boolean isJpeg(String photoPath) {
return photoPath.endsWith(".jpeg") || photoPath.endsWith("jpg");
}
/**
* 计算压缩比
*
* @param originalWidth 图片宽度
* @param originalHeight 图片高度
* @return 压缩比
*/
public static int computeSize(int originalWidth, int originalHeight) {
int mSampleSize;
originalWidth = originalWidth % 2 == 1 ? originalWidth + 1 : originalWidth;
originalHeight = originalHeight % 2 == 1 ? originalHeight + 1 : originalHeight;
originalWidth = originalWidth > originalHeight ? originalHeight : originalWidth;
originalHeight = originalWidth > originalHeight ? originalWidth : originalHeight;
double scale = ((double) originalWidth / originalHeight);
if (scale <= 1 && scale > 0.5625) {
if (originalHeight < 1664) {
mSampleSize = 1;
} else if (originalHeight >= 1664 && originalHeight < 4990) {
mSampleSize = 2;
} else if (originalHeight >= 4990 && originalHeight < 10240) {
mSampleSize = 4;
} else {
mSampleSize = originalHeight / 1280 == 0 ? 1 : originalHeight / 1280;
}
} else if (scale <= 0.5625 && scale > 0.5) {
mSampleSize = originalHeight / 1280 == 0 ? 1 : originalHeight / 1280;
} else {
mSampleSize = (int) Math.ceil(originalHeight / (1280.0 / scale));
}
return mSampleSize;
}
//-------------------------------------------以下为裁剪相关内容-------------------------------------------//
//裁剪参数
private static final boolean DEFAULT_RETURN_DATA = false;//是否返回数据
private static final boolean DEFAULT_SCALE = true;//是否缩放
private static final boolean DEFAULT_FACE_DETECTION = false;//是否面部检测
private static final boolean DEFAULT_CIRCLE_CROP = false;//圆形裁剪
private static final int DEFAULT_OUTPUT_X = 900;//默认裁剪输出宽度
private static final int DEFAULT_OUTPUT_Y = 600;//默认裁剪输出高度
private static final int DEFAULT_ASPECT_X = 3;//默认裁剪宽度比例
private static final int DEFAULT_ASPECT_Y = 2;//默认裁剪高度比例
/**
* 裁剪照片
*
* @param uri 原始路径
* @param outUri 裁剪输出路径
* @return 裁剪意图
*/
/**
* 裁剪照片
*
* @param imgPath 原始路径
* @param targetPath 裁剪输出路径
* @return 裁剪意图
*/
public static Intent crop(Activity mContext, String imgPath, String targetPath) {
return crop(mContext, imgPath, targetPath, DEFAULT_ASPECT_X, DEFAULT_ASPECT_Y, DEFAULT_OUTPUT_X, DEFAULT_OUTPUT_Y, DEFAULT_SCALE, DEFAULT_RETURN_DATA, DEFAULT_FACE_DETECTION, DEFAULT_CIRCLE_CROP);
}
public static Intent crop(Activity mContext, String imgPath, String targetPath,int aspectX, int aspectY, int outputX, int outputY) {
return crop(mContext, imgPath, targetPath, aspectX, aspectY, outputX, outputY, DEFAULT_SCALE, DEFAULT_RETURN_DATA, DEFAULT_FACE_DETECTION, DEFAULT_CIRCLE_CROP);
}
private static Intent crop(Activity mContext, String imgPath, String targetPath,
int aspectX, int aspectY, int outputX, int outputY,
boolean scale, boolean returnData, boolean faceDetection, boolean circleCrop) {
Intent intent = new Intent("com.android.camera.action.CROP");
File file = new File(imgPath);
file.deleteOnExit();
Uri imgUri = Uri.fromFile(file);
Uri targertUri = Uri.fromFile(new File(targetPath));
intent.setDataAndType(imgUri, "image/*");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.putExtra("crop", "true");
// aspectX aspectY 是宽高的比例
intent.putExtra("aspectX", aspectX);
intent.putExtra("aspectY", aspectY);
// outputX outputY 是裁剪图片宽高
intent.putExtra("outputX", outputX);
intent.putExtra("outputY", outputY);
intent.putExtra("scale", scale);
intent.putExtra("return-data", returnData);
intent.putExtra(MediaStore.EXTRA_OUTPUT, targertUri);
intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
intent.putExtra("noFaceDetection", !faceDetection);
intent.putExtra("circleCrop", circleCrop);
mContext.startActivityForResult(intent, BaseConstants.PCROP_REQUEST_CODE);
return intent;
}
//-------------------------------------------以下为根据Uri获取路径相关内容-------------------------------------------//
/**
* 通用的根据Uri获取路径的方法,兼容shceme是content和file的情况
*
* @param context 上下文对象
* @param uri Uri
* @return 路径
*/
public static String getPathFromUri(Context context, Uri uri) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, uri)) {//DocumentProvider
if (isExternalStorageDocument(uri)) {//ExternalStorageProvider
String docId = DocumentsContract.getDocumentId(uri);
String[] split = docId.split(":");
String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
} else if (isDownloadsDocument(uri)) {//DownloadsProvider
String docId = DocumentsContract.getDocumentId(uri);
Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
return getDataColumn(context, contentUri, null, null);
} else if (isMediaDocument(uri)) {//MediaProvider
String docId = DocumentsContract.getDocumentId(uri);
String[] split = docId.split(":");
String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
String selection = "_id=?";
String[] selectedArgs = new String[]{split[1]};
return getDataColumn(context, contentUri, selection, selectedArgs);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {//MediaStore (and general)
if (isGooglePhotosDocument(uri)) {//Return the remote address
return uri.getLastPathSegment();
}
return getDataColumn(context, uri, null, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {//File
return uri.getPath();
}
return "";
}
private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
Cursor cursor = null;
String column = "_data";
String[] projection = new String[]{column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
if (null != cursor && cursor.moveToFirst()) {
int index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(index);
}
} finally {
if (null != cursor) {
cursor.close();
}
}
return "";
}
private static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private static boolean isGooglePhotosDocument(Uri uri) {
return "com.google.android.apps.photos.content".equals(uri.getAuthority());
}
}
<file_sep>package com.example.baidu.retrofit.Activity.jpush;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.RecyclerView;
import com.example.baidu.retrofit.Activity.Rx2Activity;
import com.example.baidu.retrofit.R;
import com.tool.cn.utils.GlideImageManager;
import java.util.Properties;
import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.model.UserInfo;
public class ChatUIActivity extends Rx2Activity {
@BindView(R.id.recycleView)
RecyclerView recycleView;
@BindView(R.id.user_image)
ImageView userImage;
@BindView(R.id.user_name)
TextView userName;
@BindView(R.id.menu)
TextView menu;
@BindView(R.id.drawlayout)
DrawerLayout drawlayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat_ui);
ButterKnife.bind(this);
}
@Override
protected void init() {
super.init();
setUserInfo();
}
private void setUserInfo() {
UserInfo userInfo = JMessageClient.getMyInfo();
GlideImageManager.loadCircleImage(mContext, userInfo.getAvatar(), userImage);
userName.setText(userInfo.getUserName());
}
@Override
protected void getHttp() {
}
@Override
protected void nationalizationData(Properties prop) {
}
}
<file_sep>package com.tool.cn.widget.image;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import androidx.appcompat.widget.AppCompatImageView;
/**
* 2017/4/12 16:58.
*
*
* @version 1.0.0
* @class SquareImageView
* @describe 正方形的ImageView
*/
public class SquareImageView extends AppCompatImageView {
public SquareImageView(Context context) {
super(context);
}
public SquareImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SquareImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable d = getDrawable();
//父容器传过来的宽度方向上的模式
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
//父容器传过来的高度方向上的模式
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
//父容器传过来的宽度的值
int width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
//父容器传过来的高度的值
int height = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
if (d != null) {
height = width;
height = height + getPaddingTop() + getPaddingBottom();
setMeasuredDimension(width, height);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
<file_sep>package com.example.baidu.retrofit.Bean;
public class UploadAvatarResponseBean {
}
<file_sep>package com.example.baidu.retrofit.Bean;
/**
* @author
* @date 2020/4/3.
* GitHub:
* email:
* description:
*/
public class Tags {
private String name;
private String url;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setUrl(String url) {
this.url = url;
}
public String getUrl() {
return url;
}
}
<file_sep>package com.example.baidu.retrofit.View;
import android.content.Context;
import android.graphics.Camera;
import android.graphics.Matrix;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.BounceInterpolator;
import android.view.animation.Transformation;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;
import java.util.List;
/**
* 自动垂直滚动的ImageView
*/
public class AutoVerticalScrollImageView extends ImageSwitcher implements ViewSwitcher.ViewFactory {
//mInUp,mOutUp分别构成向下翻页的进出动画
private Rotate3dAnimation mInUp;
private Rotate3dAnimation mOutUp;
public AutoVerticalScrollImageView(Context context) {
this(context, null);
}
public AutoVerticalScrollImageView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
setFactory(this);
mInUp = createAnim(true, true);
mOutUp = createAnim(false, true);
setInAnimation(mInUp);//当View显示时动画资源ID
setOutAnimation(mOutUp);//当View隐藏是动画资源ID。
}
private Rotate3dAnimation createAnim(boolean turnIn, boolean turnUp) {
Rotate3dAnimation rotation = new Rotate3dAnimation(turnIn, turnUp);
rotation.setDuration(animTime);//执行动画的时间
rotation.setFillAfter(false);//是否保持动画完毕之后的状态
rotation.setInterpolator(new AccelerateInterpolator());//设置加速模式
return rotation;
}
private boolean isRunning = true;
private int number = 0;
private List<Integer> list;
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 199) {
next();
number++; // 切换现实的index
if (list.size() > 0) {
setImageResource(list.get(number % list.size()));
}
}
}
};
public void setList(List<Integer> list) {
this.list = list;
}
public void startAutoScroll() {
number = 0;
isRunning = true;
new Thread() {
@Override
public void run() {
while (isRunning) {
handler.sendEmptyMessage(199);
SystemClock.sleep(imageStillTime);
}
}
}.start();
}
public void stopAutoScroll() {
isRunning = false;
}
private int imageStillTime = 3000;//停留时长间隔
private int animTime = 300;//执行动画的时间
/**
* 设置停留时长间隔
*/
public void setImageStillTime(int textStillTime) {
this.imageStillTime = textStillTime;
}
/**
* 设置进入和退出的时间间隔
*/
public void setAnimTime(int animTime) {
this.animTime = animTime;
}
//这里返回的ImageView,就是我们看到的View,可以设置自己想要的效果
public View makeView() {
ImageView imageView = new ImageView(getContext().getApplicationContext());
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
/* TextView textView = new TextView(mContext);
textView.setGravity(Gravity.LEFT);
textView.setTextSize(15);
textView.setSingleLine(true);
textView.setGravity(Gravity.CENTER_VERTICAL);
textView.setEllipsize(TextUtils.TruncateAt.END);
textView.setTextColor(getResources().getColor(R.color.player_black));*/
return imageView;
}
//定义动作,向上滚动翻页
public void next() {
//显示动画
if (getInAnimation() != mInUp) {
setInAnimation(mInUp);
}
//隐藏动画
if (getOutAnimation() != mOutUp) {
setOutAnimation(mOutUp);
}
}
class Rotate3dAnimation extends Animation {
private float mCenterX;
private float mCenterY;
private final boolean mTurnIn;
private final boolean mTurnUp;
private Camera mCamera;
public Rotate3dAnimation(boolean turnIn, boolean turnUp) {
mTurnIn = turnIn;
mTurnUp = turnUp;
}
@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
mCamera = new Camera();
mCenterY = getHeight();
mCenterX = getWidth();
}
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final float centerX = mCenterX;
final float centerY = mCenterY;
final Camera camera = mCamera;
final int derection = mTurnUp ? 1 : -1;
final Matrix matrix = t.getMatrix();
camera.save();
if (mTurnIn) {
camera.translate(0.0f, derection * mCenterY * (interpolatedTime - 1.0f), 0.0f);
} else {
camera.translate(0.0f, derection * mCenterY * (interpolatedTime), 0.0f);
}
camera.getMatrix(matrix);
camera.restore();
matrix.preTranslate(-centerX, -centerY);
matrix.postTranslate(centerX, centerY);
}
}
}
<file_sep>package com.example.commonlibrary.widget.scroll;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ScrollView;
/**
* 2017/4/13 11:59.
*
*
* @version 1.0.0
* @class ElasticScrollView
* @describe 弹性ScrollView
*/
public class ElasticScrollView extends ScrollView {
private View mRootView;
private float mY;
private Rect mNormal = new Rect();
private boolean isAnimationFinish = true;
public ElasticScrollView(Context context) {
this(context, null);
}
public ElasticScrollView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public ElasticScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
if (getChildCount() > 0) {
mRootView = getChildAt(0);
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (null == mRootView) {
return super.onTouchEvent(ev);
} else {
commOnTouchEvent(ev);
}
return super.onTouchEvent(ev);
}
public void commOnTouchEvent(MotionEvent ev) {
if (isAnimationFinish) {
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
mY = ev.getY();
super.onTouchEvent(ev);
break;
case MotionEvent.ACTION_UP:
mY = 0;
if (isNeedAnimation()) {
animation();
}
super.onTouchEvent(ev);
break;
case MotionEvent.ACTION_MOVE:
final float preY = mY == 0 ? ev.getY() : mY;
float nowY = ev.getY();
int deltaY = (int) (preY - nowY);
mY = nowY;
// 当滚动到最上或者最下时就不会再滚动,这时移动布局
if (isNeedMove()) {
if (mNormal.isEmpty()) {
// 保存正常的布局位置
mNormal.set(mRootView.getLeft(), mRootView.getTop(), mRootView.getRight(), mRootView.getBottom());
}
// 移动布局
mRootView.layout(mRootView.getLeft(), mRootView.getTop() - deltaY / 2, mRootView.getRight(), mRootView.getBottom() - deltaY / 2);
} else {
super.onTouchEvent(ev);
}
break;
default:
break;
}
}
}
/**
* 开启动画移动
*/
public void animation() {
// 开启移动动画
TranslateAnimation ta = new TranslateAnimation(0, 0, 0, mNormal.top - mRootView.getTop());
ta.setDuration(200);
ta.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
isAnimationFinish = false;
}
@Override
public void onAnimationRepeat(Animation animation) {
}
@Override
public void onAnimationEnd(Animation animation) {
mRootView.clearAnimation();
// 设置回到正常的布局位置
mRootView.layout(mNormal.left, mNormal.top, mNormal.right, mNormal.bottom);
mNormal.setEmpty();
isAnimationFinish = true;
}
});
mRootView.startAnimation(ta);
}
/**
* 是否需要开启动画
*
* @return true需要,false不需要
*/
public boolean isNeedAnimation() {
return !mNormal.isEmpty();
}
/**
* 是否需要移动布局
*
* @return true需要,false不需要
*/
public boolean isNeedMove() {
int offset = mRootView.getMeasuredHeight() - getHeight();
int scrollY = getScrollY();
return scrollY == 0 || scrollY == offset;
}
}
<file_sep>package com.tool.cn.utils;
/**
* 2017/2/22 11:28.
*
* @version 1.0.0
* @class LogUtils
* @describe 日志工具类
*/
public class LogUtils {
private static final String TAG = "LogUtils";
/**
* 是否是调试模式,true是,false不是.
*/
private static boolean isDebug = false;
/**
* 初始化状态
*
* @param debug 是否是调试模式,true是,false不是.
*/
public static void isDebug(boolean debug) {
isDebug = debug;
}
public static void v(String msg) {
LogUtils.v(TAG, msg);
}
public static void v(String tag, String msg) {
if (isDebug)
try {
android.util.Log.v(tag, msg);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void v(String tag, String msg, Throwable t) {
if (isDebug)
try {
android.util.Log.v(tag, msg, t);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void d(String msg) {
LogUtils.d(TAG, msg);
}
public static void d(String tag, String msg) {
if (isDebug)
android.util.Log.d(tag, msg);
}
public static void d(String tag, String msg, Throwable t) {
if (isDebug)
try {
android.util.Log.d(tag, msg, t);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void i(String msg) {
LogUtils.i(TAG, msg);
}
public static void i(String tag, String msg) {
if (isDebug)
try {
android.util.Log.i(tag, msg);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void i(String tag, String msg, Throwable t) {
if (isDebug)
try {
android.util.Log.i(tag, msg, t);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void w(String msg) {
LogUtils.w(TAG, msg);
}
public static void w(String tag, String msg) {
if (isDebug)
try {
android.util.Log.w(tag, msg);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void w(String tag, String msg, Throwable t) {
if (isDebug)
try {
android.util.Log.w(tag, msg, t);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void e(String msg) {
LogUtils.e(TAG, msg);
}
public static void e(String tag, String msg) {
if (isDebug)
try {
android.util.Log.e(tag, msg);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void e(String tag, String msg, Throwable t) {
if (isDebug)
try {
android.util.Log.e(tag, msg, t);
} catch (Exception e) {
e.printStackTrace();
}
}
}
<file_sep>package com.example.baidu.retrofit.util.bitmap;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.widget.ImageView;
import com.example.baidu.retrofit.util.DiskLruCache;
import java.lang.ref.WeakReference;
/**
* @author
* @date 2019/12/24.
* GitHub:
* email:
* description:
*/
public class AsyncDrawable extends BitmapDrawable {
private static WeakReference bitmapWorkerTaskReference;
public AsyncDrawable(Resources res, Bitmap bitmap,
ImageAsyncTask bitmapWorkerTask) {
super(res, bitmap);
bitmapWorkerTaskReference =
new WeakReference(bitmapWorkerTask);
}
public static ImageAsyncTask getBitmapWorkerTask() {
return (ImageAsyncTask) bitmapWorkerTaskReference.get();
}
public static ImageAsyncTask getBitmapWorkerTask(ImageView imageView) {
if (imageView != null) {
final Drawable drawable = imageView.getDrawable();
if (drawable instanceof AsyncDrawable) {
final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable;
return asyncDrawable.getBitmapWorkerTask();
}
}
return null;
}
}<file_sep>package com.tool.cn.utils;
import java.util.regex.Pattern;
/**
* 2016/11/10 17:08
*
*
* @version 1.0.0
* @class VerificationUtils
* @describe 常用验证工具类
*/
@SuppressWarnings("unused")
public class VerificationUtils {
/******************** 正则相关常量 stat********************/
/**
* 正则:手机号(简单)
*/
public static final String REGEX_MOBILE_SIMPLE = "^[1]\\d{10}$";
/**
* 正则:手机号(精确)
* 移动:134(0-8)、135、136、137、138、139、147、150、151、152、157、158、159、178、182、183、184、187、188
* 联通:130、131、132、145、155、156、175、176、185、186
* 电信:133、153、173、177、180、181、189
* 全球星:1349
* 虚拟运营商:170
*/
public static final String REGEX_MOBILE_EXACT = "^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|(147))\\d{8}$";
/**
* 正则:电话号码
*/
public static final String REGEX_TEL = "^0\\d{2,3}[- ]?\\d{7,8}";
/**
* 正则:身份证号码15位
*/
public static final String REGEX_ID_CARD15 = "^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$";
/**
* 正则:身份证号码18位
*/
public static final String REGEX_ID_CARD18 = "^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9Xx])$";
/**
* 正则:邮箱
*/
public static final String REGEX_EMAIL = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
/**
* 正则:URL
*/
public static final String REGEX_URL = "[a-zA-z]+://[^\\s]*";
/**
* 正则:汉字
*/
public static final String REGEX_ZH = "^[\\u4e00-\\u9fa5]+$";
/**
* 正则:用户名,取值范围为a-z,A-Z,0-9,"_",汉字,不能以"_"结尾,用户名必须是6-20位
*/
public static final String REGEX_USERNAME = "^[\\w\\u4e00-\\u9fa5]{6,20}(?<!_)$";
/**
* 正则:yyyy-MM-dd格式的日期校验,已考虑平闰年
*/
public static final String REGEX_DATE = "^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$";
/**
* 正则:IP地址
*/
public static final String REGEX_IP = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)";
//----------------------以下摘自http://tool.oschina.net/regex ----------------------/
/**
* 正则:双字节字符(包括汉字在内)
*/
public static final String REGEX_DOUBLE_BYTE_CHAR = "[^\\x00-\\xff]";
/**
* 正则:空白行
*/
public static final String REGEX_BLANK_LINE = "\\n\\s*\\r";
/**
* 正则:QQ号
*/
public static final String REGEX_TENCENT_NUM = "[1-9][0-9]{4,}";
/**
* 正则:中国邮政编码
*/
public static final String REGEX_ZIP_CODE = "[1-9]\\d{5}(?!\\d)";
/**
* 正则:正整数
*/
public static final String REGEX_POSITIVE_INTEGER = "^[1-9]\\d*$";
/**
* 正则:负整数
*/
public static final String REGEX_NEGATIVE_INTEGER = "^-[1-9]\\d*$";
/**
* 正则:整数
*/
public static final String REGEX_INTEGER = "^-?[1-9]\\d*$";
/**
* 正则:非负整数(正整数 + 0)
*/
public static final String REGEX_NOT_NEGATIVE_INTEGER = "^[1-9]\\d*|0$";
/**
* 正则:非正整数(负整数 + 0)
*/
public static final String REGEX_NOT_POSITIVE_INTEGER = "^-[1-9]\\d*|0$";
/**
* 正则:正浮点数
*/
public static final String REGEX_POSITIVE_FLOAT = "^[1-9]\\d*\\.\\d*|0\\.\\d*[1-9]\\d*$";
/**
* 正则:负浮点数
*/
public static final String REGEX_NEGATIVE_FLOAT = "^-[1-9]\\d*\\.\\d*|-0\\.\\d*[1-9]\\d*$";
/**
* 密码8-20位至少包含1个大写字母1个小写字母1个数字
*/
public static final String LOGIN_PWD_PATTERN = "^(.*(?=.{8,})(?=.*\\d)(?=.*[A-Z])(?=.*[a-z]).*)$";
/**
* 特殊符号
*/
public static String SPECHAT="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
//----------------------------正则相关常量 end----------------------------/
/**
* 验证Email
*
* @param email email地址,格式:<EMAIL>,<EMAIL>,xxx代表邮件服务商
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkEmail(String email) {
String regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?";
return Pattern.matches(regex, email);
}
/**
* 验证手机号码(支持国际格式,+86135xxxx...(中国内地),+00852137xxxx...(中国香港))
*
* @param mobile 移动、联通、电信运营商的号码段
* <p>
* 移动的号段:134(0-8)、135、136、137、138、139、147(预计用于TD上网卡)
* 、150、151、152、157(TD专用)、158、159、187(未启用)、188(TD专用)
* </p>
* <p>
* 联通的号段:130、131、132、155、156(世界风专用)、185(未启用)、186(3g)
* </p>
* <p>
* 电信的号段:133、153、180(未启用)、189
* </p>
* <p>
* 4G号段:17*
* </p>
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkMobile1(String mobile) {
String regex = "(\\+\\d+)?1[012345789]\\d{9}$";
return Pattern.matches(regex, mobile);
}
/**
* 验证身份证号码
*
* @param idCard 18位,最后一位可能是数字或字母
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkIdCard(String idCard) {
String regex = "(\\d{14}[0-9a-zA-Z])|(\\d{17}[0-9a-zA-Z])";
return Pattern.matches(regex, idCard);
}
/**
* 验证手机号码(支持国际格式,+86135xxxx...(中国内地),+00852137xxxx...(中国香港))
*
* @param mobile 移动、联通、电信运营商的号码段
* <p>
* 移动的号段:134(0-8)、135、136、137、138、139、147(预计用于TD上网卡)
* 、150、151、152、157(TD专用)、158、159、187(未启用)、188(TD专用)
* </p>
* <p>
* 联通的号段:130、131、132、155、156(世界风专用)、185(未启用)、186(3g)
* </p>
* <p>
* 电信的号段:133、153、180(未启用)、189
* </p>
* <p>
* 4G号段:17*
* </p>
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkMobile(String mobile) {
String regex = "(\\+\\d+)?1[34578]\\d{9}$";
return Pattern.matches(regex, mobile);
}
/**
* 验证固定电话号码
*
* @param phone 电话号码,格式:国家(地区)电话代码 + 区号(城市代码) + 电话号码,如:+8602085588447
* <p>
* <b>国家(地区) 代码 :</b>标识电话号码的国家(地区)的标准国家(地区)代码。它包含从 0 到 9
* 的一位或多位数字, 数字之后是空格分隔的国家(地区)代码。
* </p>
* <p>
* <b>区号(城市代码):</b>这可能包含一个或多个从 0 到 9 的数字,地区或城市代码放在圆括号——
* 对不使用地区或城市代码的国家(地区),则省略该组件。
* </p>
* <p>
* <b>电话号码:</b>这包含从 0 到 9 的一个或多个数字
* </p>
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkPhone(String phone) {
String regex = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$";
return Pattern.matches(regex, phone);
}
/**
* 验证整数(正整数和负整数)
*
* @param digit 一位或多位0-9之间的整数
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkDigit(String digit) {
String regex = "\\-?[1-9]\\d+";
return Pattern.matches(regex, digit);
}
/**
* 验证整数和浮点数(正负整数和正负浮点数)
*
* @param decimals 一位或多位0-9之间的浮点数,如:1.23,233.30
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkDecimals(String decimals) {
String regex = "\\-?[1-9]\\d+(\\.\\d+)?";
return Pattern.matches(regex, decimals);
}
/**
* 验证整数 0-99的正整数
*
* @param decimals nums
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkNums(String decimals) {
String regex = "^[1-9][0-9]?$";
return Pattern.matches(regex, decimals);
}
/**
* 验证空白字符
*
* @param blankSpace 空白字符,包括:空格、\t、\n、\r、\f、\x0B
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkBlankSpace(String blankSpace) {
String regex = "\\s+";
return Pattern.matches(regex, blankSpace);
}
/**
* 验证中文
*
* @param chinese 中文字符
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkChinese(String chinese) {
String regex = "^[\u4E00-\u9FA5]+$";
return Pattern.matches(regex, chinese);
}
/**
* 验证日期(年月日)
*
* @param birthday 日期,格式:1992-09-03,或1992.09.03
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkBirthday(String birthday) {
String regex = "[1-9]{4}([-./])\\d{1,2}\\1\\d{1,2}";
return Pattern.matches(regex, birthday);
}
/**
* 验证URL地址
*
* @param url 格式:http://blog.csdn.net:80/xyang81/article/details/7705960? 或
* http://www.csdn.net:80
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkURL(String url) {
String regex = "(https?://(w{3}\\.)?)?\\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5})?(/\\w*)*(\\??(.+=.*)?(&.+=.*)?)?";
return Pattern.matches(regex, url);
}
/**
* 匹配中国邮政编码
*
* @param postcode 邮政编码
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkPostcode(String postcode) {
String regex = "[1-9]\\d{5}";
return Pattern.matches(regex, postcode);
}
/**
* 匹配IP地址(简单匹配,格式,如:192.168.1.1,127.0.0.1,没有匹配IP段的大小)
*
* @param ipAddress IPv4标准地址
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkIpAddress(String ipAddress) {
String regex = "[1-9](\\d{1,2})?\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))";
return Pattern.matches(regex, ipAddress);
}
/**
* 匹配车牌号
*
* @param carNummber 车牌号
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkCarNummber(String carNummber) {
String regex = "[\\u4e00-\\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}";
return Pattern.matches(regex, carNummber);
}
/**
* 小数点后不超过两位
*
* @param carNummber
* @return 验证成功返回true,验证失败返回false
*/
public static boolean checkDoublePoint(String carNummber) {
String regex = "^\\d+(\\.\\d{1,2})?$";
return Pattern.matches(regex, carNummber);
}
}
<file_sep>package com.example.baidu.retrofit.Adapter.home;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
/**
* @author
* @date 2020/4/3.
* GitHub:
* email:
* description:
*/
public class FragmentAdapter extends FragmentPagerAdapter {
private List<Fragment> mFragmentList;
private Context mContext;
private List<String> titles = new ArrayList<>();
public FragmentAdapter(FragmentManager fm, List<Fragment> fragments, @Nullable List<String> titles, Context luteActivity) {
super(fm);
this.mFragmentList = fragments;
this.mContext = luteActivity;
this.titles = titles;
}
@NonNull
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position % mFragmentList.size());
}
@Override
public int getCount() {
return mFragmentList.size();
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
if (titles.size() == 0) {
return "";
}
return titles.get(position);
}
}
<file_sep>package com.example.baidu.retrofit.View;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.LinearInterpolator;
import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.baidu.retrofit.R;
/**
* @author
* @date 2020/3/26.
* GitHub:
* email:
* description:
*/
public class HwLoadingView extends View {
private static final int CIRCLE_COUNT = 12;
private static final int DEGREE_PER_CIRCLE = 360 / CIRCLE_COUNT;
private float[] mWholeCircleRadius = new float[CIRCLE_COUNT];
private int[] mWholeCircleColors = new int[CIRCLE_COUNT];
private float mMaxCircleRadius;
private int mSize;
private int mColor;
private Paint mPaint;
private ValueAnimator mAnimator;
private int mAnimateValue = 0;
private long mDuration;
public HwLoadingView(Context context) {
this(context, null);
}
public HwLoadingView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public HwLoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initAttrs(context, attrs);
initPaint();
initValue();
}
private void initAttrs(Context context, AttributeSet attrs) {
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.HwLoadingView);
mSize = (int) ta.getDimension(R.styleable.HwLoadingView_size, dp2px(context, 50));
setSize(mSize);
mColor = ta.getColor(R.styleable.HwLoadingView_color, Color.parseColor("#CCCCCC"));
setColor(mColor);
mDuration = ta.getInt(R.styleable.HwLoadingView_duration, 1500);
ta.recycle();
}
public void setConfig(int size) {
this.mSize = size;
}
private void initPaint() {
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setStyle(Paint.Style.FILL);
mPaint.setColor(mColor);
}
private void initValue() {
float minCircleRadius = mSize / 24;
for (int i = 0; i < CIRCLE_COUNT; i++) {
switch (i) {
case 7:
mWholeCircleRadius[i] = minCircleRadius * 1.25f;
mWholeCircleColors[i] = (int) (255 * 0.7f);
break;
case 8:
mWholeCircleRadius[i] = minCircleRadius * 1.5f;
mWholeCircleColors[i] = (int) (255 * 0.8f);
break;
case 9:
case 11:
mWholeCircleRadius[i] = minCircleRadius * 1.75f;
mWholeCircleColors[i] = (int) (255 * 0.9f);
break;
case 10:
mWholeCircleRadius[i] = minCircleRadius * 2f;
mWholeCircleColors[i] = 255;
break;
default:
mWholeCircleRadius[i] = minCircleRadius;
mWholeCircleColors[i] = (int) (255 * 0.5f);
break;
}
}
mMaxCircleRadius = minCircleRadius * 2;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(mSize, mSize);
}
@Override
protected void onDraw(Canvas canvas) {
if (mSize > 0) {
canvas.rotate(DEGREE_PER_CIRCLE * mAnimateValue, mSize / 2, mSize / 2);
for (int i = 0; i < CIRCLE_COUNT; i++) {
mPaint.setAlpha(mWholeCircleColors[i]);
canvas.drawCircle(mSize / 2, mMaxCircleRadius, mWholeCircleRadius[i], mPaint);
canvas.rotate(DEGREE_PER_CIRCLE, mSize / 2, mSize / 2);
}
}
}
public void setSize(int size) {
mSize = size;
invalidate();
}
public void setColor(@ColorInt int color) {
mColor = color;
invalidate();
}
private ValueAnimator.AnimatorUpdateListener mUpdateListener = new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mAnimateValue = (int) animation.getAnimatedValue();
invalidate();
}
};
public void start() {
if (mAnimator == null) {
mAnimator = ValueAnimator.ofInt(0, CIRCLE_COUNT - 1);
mAnimator.addUpdateListener(mUpdateListener);
mAnimator.setDuration(mDuration);
mAnimator.setRepeatMode(ValueAnimator.RESTART);
mAnimator.setRepeatCount(ValueAnimator.INFINITE);
mAnimator.setInterpolator(new LinearInterpolator());
mAnimator.start();
} else if (!mAnimator.isStarted()) {
mAnimator.start();
}
}
public void stop() {
if (mAnimator != null) {
mAnimator.removeUpdateListener(mUpdateListener);
mAnimator.removeAllUpdateListeners();
mAnimator.cancel();
mAnimator = null;
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
start();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
stop();
}
@Override
protected void onVisibilityChanged(@NonNull View changedView, int visibility) {
super.onVisibilityChanged(changedView, visibility);
if (visibility == VISIBLE) {
start();
} else {
stop();
}
}
private int dp2px(Context context, float dp) {
float density = context.getResources().getDisplayMetrics().density;
return (int) (density * dp + 0.5f);
}
}<file_sep>package com.tool.cn.widget.image;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import androidx.appcompat.widget.AppCompatImageView;
import com.tool.cn.R;
/**
* 2017/1/16 14:51
*
*
* @version 1.0.0
* @class PercentImageView
* @describe 百分比的ImageView
* 注:1.注:宽高权重都设置时权重设置百分比方法才有效;
* 2.宽高权重和百分比都设置时使用百分比方法.
*/
public class PercentImageView extends AppCompatImageView {
/**
* 宽高比
*/
private float mWidthHeightPercent;
/**
* 宽权重
*/
private int mWidthWeight = -1;
/**
* 高权重
*/
private int mHeightWeight = -1;
public PercentImageView(Context context) {
this(context, null);
}
public PercentImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public PercentImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initImageView(context, attrs, defStyleAttr);
}
private void initImageView(Context context, AttributeSet attrs, int defStyleAttr) {
TypedArray typrdArray = getResources().obtainAttributes(attrs, R.styleable.PercentView);
mWidthHeightPercent = typrdArray.getFloat(R.styleable.PercentView_width_height_percent, -1);
mWidthWeight = typrdArray.getInteger(R.styleable.PercentView_width_weight, mWidthWeight);
mHeightWeight = typrdArray.getInteger(R.styleable.PercentView_height_weight, mHeightWeight);
typrdArray.recycle();
}
/**
* 设置宽高比
*
* @param widthHeightPercent 宽高比
*/
public void setWidthHeightPercent(float widthHeightPercent) {
this.mWidthHeightPercent = widthHeightPercent;
}
/**
* 设置宽权重
*
* @param widthWeight 宽权重
*/
public void setWidthWeight(int widthWeight) {
this.mWidthWeight = widthWeight;
}
/**
* 设置高权重
*
* @param heightWeight 高权重
*/
public void setHeightWeight(int heightWeight) {
this.mHeightWeight = heightWeight;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
Drawable d = getDrawable();
//父容器传过来的宽度方向上的模式
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
//父容器传过来的高度方向上的模式
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
//父容器传过来的宽度的值
int width = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
//父容器传过来的高度的值
int height = MeasureSpec.getSize(widthMeasureSpec) - getPaddingLeft() - getPaddingRight();
switch (widthMode) {
case MeasureSpec.EXACTLY://精确尺寸eg:andorid:layout_width="50dp"或者andorid:layout_width="match_parent"
break;
case MeasureSpec.UNSPECIFIED://未指定尺寸eg:WRAP_CONTENT,控件大小一般随着控件的子空间或内容进行变化,此时控件尺寸只要不超过父控件允许的最大尺寸即可.
break;
case MeasureSpec.AT_MOST://最大尺寸,这种情况不多,一般都是父控件是AdapterView,通过measure方法传入的模式
break;
}
switch (heightMode) {
case MeasureSpec.EXACTLY://精确尺寸eg:andorid:layout_width="50dp"或者andorid:layout_width="match_parent"
break;
case MeasureSpec.UNSPECIFIED://未指定尺寸eg:WRAP_CONTENT,控件大小一般随着控件的子空间或内容进行变化,此时控件尺寸只要不超过父控件允许的最大尺寸即可.
if (-1 != mWidthHeightPercent) {
height = (int) ((float) width / mWidthHeightPercent);
} else if (-1 != mWidthWeight && -1 != mHeightWeight) {
height = (int) ((float) width * mHeightWeight / (float) mWidthWeight);
}
height += +getPaddingTop() + getPaddingBottom();
break;
case MeasureSpec.AT_MOST://最大尺寸,这种情况不多,一般都是父控件是AdapterView,通过measure方法传入的模式
break;
}
if (d != null && (-1 != mWidthHeightPercent || (-1 != mWidthWeight && -1 != mHeightWeight))) {
setMeasuredDimension(width, height);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
<file_sep>package com.example.baidu.retrofit.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.baidu.retrofit.Adapter.ListActivityAdapter;
import com.example.baidu.retrofit.Api;
import com.example.baidu.retrofit.Bean.StudyBean;
import com.example.baidu.retrofit.R;
import com.example.baidu.retrofit.util.DividerGridItemDecoration;
import com.tool.cn.utils.GlideImageManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import butterknife.BindView;
public class MainActivity extends Rx2Activity {
@BindView(R.id.recycleView)
RecyclerView recycleView;
@BindView(R.id.header_image)
ImageView headerImage;
@BindView(R.id.name)
TextView name;
@BindView(R.id.ll_menu)
LinearLayout llMenu;
@BindView(R.id.drawlayout)
DrawerLayout drawlayout;
private Api apis;
private String TAG = "Mainactivity";
private ListActivityAdapter activityAdapter;
private List<StudyBean> listString;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void nationalizationData(Properties prop) {
}
@Override
protected void init() {
super.init();
listString = new ArrayList<>();
activityAdapter = new ListActivityAdapter(getApplicationContext(), null);
recycleView.setLayoutManager(new LinearLayoutManager(mContext));
//设置分隔线
recycleView.addItemDecoration(new DividerGridItemDecoration(this));
//设置增加或删除条目的动画
recycleView.setItemAnimator(new DefaultItemAnimator());
//设置Adapter
recycleView.setAdapter(activityAdapter);
initData();
String url = "https://c-ssl.duitang.com/uploads/item/201511/20/20151120185405_8dJPm.thumb.700_0.jpeg";
GlideImageManager.loadCircleImage(mContext, url, headerImage);
}
private void initData() {
listString.add(new StudyBean("GanHuo", "", "url"));
activityAdapter.setNewData(listString);
activityAdapter.notifyDataSetChanged();
}
@Override
protected void getHttp() {
}
/**
* 开启获取网速定时器
*/
public void startSpeedTimer() {
}
}
<file_sep>package com.eyes.see.java;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
/**
* @author
* @date 2020/5/7.
* GitHub:
* email:
* description:
*/
public class DateTransUtils {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
public static final long DAY_IN_MILLIS = 24 * 60 * 60 * 1000;
/*
* 将时间戳转换为时间
*/
public static String stampToDate(String stamp) {
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
long lt = new Long(stamp);
Date date = new Date(lt);
res = simpleDateFormat.format(date);
return res;
}
public static String stampToDate(long stamp) {
String res;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
Date date = new Date(stamp);
res = simpleDateFormat.format(date);
return res;
}
//获取今日某时间的时间戳
public static long getTodayStartStamp(int hour, int minute, int second) {
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, second);
long todayStamp = cal.getTimeInMillis();
// Log.i("Wingbu", " DateTransUtils-getTodayStartStamp() 获取当日" + hour + ":" + minute + ":" + second + "的时间戳 :" + todayStamp);
return todayStamp;
}
//获取当日00:00:00的时间戳,东八区则为早上八点
public static long getZeroClockTimestamp(long time) {
long currentStamp = time;
currentStamp -= currentStamp % DAY_IN_MILLIS;
// Log.i("Wingbu", " DateTransUtils-getZeroClockTimestamp() 获取当日00:00:00的时间戳,东八区则为早上八点 :" + currentStamp);
return currentStamp;
}
//获取最近7天的日期,用于查询这7天的系统数据
public static ArrayList<String> getSearchDays() {
ArrayList<String> dayList = new ArrayList<>();
for (int i = 0; i < 7; i++) {
dayList.add(getDateString(i));
}
return dayList;
}
//获取dayNumber天前,当天的日期字符串
public static String getDateString(int dayNumber) {
long time = System.currentTimeMillis() - dayNumber * DAY_IN_MILLIS;
// Log.i("getDateString", " DateTransUtils-getDateString() 获取查询的日期 :" + dateFormat.format(time));
return dateFormat.format(time);
}
public static String getDayDate(long time) {
return dateFormat.format(time);
}
public static String formatDuring(long mss) {
long timer = mss / 1000; //seconds
String sTime = String.format("%02d:%02d:%02d", timer / 3600, timer % 3600 / 60, timer % 60);//转为标准格式
return sTime;
}
public static String getAMorPMFormatTime(String time, String format) {
SimpleDateFormat formatTime = new SimpleDateFormat(format + " aa", Locale.ENGLISH);
try {
return formatTime.format(new SimpleDateFormat(format).parse(time));
} catch (ParseException e) {
e.printStackTrace();
}
return "";
}
public static String getTimeByAMorPMFormat(long time) {
if (time == 0) {
return "00:00:00";
}
SimpleDateFormat formatTime1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss aa", Locale.ENGLISH);
SimpleDateFormat formatTime = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
String str = "";
try {
Date date = new Date(time);
str = formatTime.format(date);
} catch (Exception e) {
System.out.println("传入日期错误");
}
return str;
}
public static String getTimeByAMorPM(long time) {
if (time == 0) {
return "AM";
}
SimpleDateFormat formatTime = new SimpleDateFormat("aa", Locale.ENGLISH);
String str = "";
try {
Date date = new Date(time);
str = formatTime.format(date);
} catch (Exception e) {
System.out.println("传入日期错误");
}
return str;
}
}<file_sep>apply plugin: 'com.mob.sdk'
MobSDK {
appKey "2dc08f5fc143e"
appSecret "<KEY>"
ShareSDK {
loopShare true
devInfo {
SinaWeibo {
appKey "568898243"
appSecret "<KEY>"
callbackUri "http://www.sharesdk.cn"
}
Wechat {
appId "wx4868b35061f87885"
appSecret "64020361b8ec4c99936c0e3999a9f249"
userName "gh_afb25ac019c9"
path "pages/index/index.html?id=1"
withShareTicket true
miniprogramType 2
}
QQ {
appId "100371282"
appKey "aed9b0303e3ed1e27bae87c33761161d"
}
Facebook {
appKey "1412473428822331"
appSecret "a42f4f3f867dc947b9ed6020c2e93558"
callbackUri "https://mob.com"
}
Twitter {
appKey "<KEY>"
appSecret "<KEY>"
callbackUri "http://mob.com"
}
ShortMessage {}
LinkedIn {
appKey "<KEY>"
appSecret "<KEY>"
callbackUri "http://www.sharesdk.cn"
}
Douyin {
appKey "<KEY>"
appSecret "<KEY>"
}
FacebookMessenger {
appId "107704292745179"
}
WhatsApp {}
WechatMoments {
appId "wx4868b35061f87885"
appSecret "64020361b8ec4c99936c0e3999a9f249"
}
WechatFavorite {
appId "wx4868b35061f87885"
appSecret "64020361b8ec4c99936c0e3999a9f249"
}
}
}
}<file_sep>package com.example.commonlibrary.widget;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.widget.AbsListView;
/**
* 2017/6/2 11:34.
*
*
* @version 1.0.0
* @class LoadMore
* @describe 上拉加载框架
*/
public class LoadMore extends RecyclerView.OnScrollListener implements AbsListView.OnScrollListener {
private OnLoadMoreListener loadMoreListener;
private boolean isLastPage;
private boolean isGrid;
public LoadMore(RecyclerView recyclerView) {
//noinspection deprecation
recyclerView.setOnScrollListener(this);
}
/**
* 设置LayoutManager为StaggeredGridLayoutManager、GridLayoutManager等模式时使用该构造方法
*
* @param recyclerView
* @param isGrid 是网格是为true
*/
public LoadMore(RecyclerView recyclerView, boolean isGrid) {
this.isGrid = isGrid;
recyclerView.setOnScrollListener(this);
}
public LoadMore(AbsListView absListView) {
absListView.setOnScrollListener(this);
}
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (isLastPage) {
return;
}
if (newState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
int lastVisiblePosition;
if (isGrid) {
StaggeredGridLayoutManager staggeredGridLayoutManager = (StaggeredGridLayoutManager) recyclerView.getLayoutManager();
int[] lastVisible = staggeredGridLayoutManager.findLastVisibleItemPositions(new int[staggeredGridLayoutManager.getSpanCount()]);
lastVisiblePosition = lastVisible[lastVisible.length - 1];
} else {
lastVisiblePosition = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();
}
if (lastVisiblePosition == recyclerView.getAdapter().getItemCount() - 1) {
if (loadMoreListener != null) {
loadMoreListener.onLoadMore();
}
}
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (isLastPage) {
return;
}
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
int lastVisiblePosition = view.getLastVisiblePosition();
if (lastVisiblePosition == view.getCount() - 1) {
if (loadMoreListener != null) {
loadMoreListener.onLoadMore();
}
}
}
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
public interface OnLoadMoreListener {
void onLoadMore();
}
public void setOnLoadMoreListener(OnLoadMoreListener listener) {
this.loadMoreListener = listener;
}
public void setIsLastPage(boolean isLastPage) {
this.isLastPage = isLastPage;
}
}
<file_sep>package com.example.baidu.retrofit.Study;
import android.util.SparseArray;
import android.util.SparseBooleanArray;
import android.util.SparseIntArray;
import java.util.HashMap;
/**
* Android为什么推荐使用SparseArray来替代HashMap?
* <p>
* https://blog.csdn.net/woshizisezise/article/details/79361458
*/
/**
* 稀疏矩阵
* <p>
* 替换 HashMap
*
* 主要是因为SparseArray不需要对key和value进行auto-boxing
*
* <p>
* 相应的也有SparseBooleanArray,用来取代HashMap<Integer, Boolean>,SparseIntArray 用来取代HashMap<Integer, Integer>,大家有兴趣的可以研究。
* <p>
* <p>
* <p>
* 总结:SparseArray是android里为<Interger,Object>这样的Hashmap而专门写的类,目的是提高内存效率,其核心是折半查找函数(binarySearch)。
* <p>
* 注意内存二字很重要,因为它仅仅提高内存效率,而不是提高执行效率,所以也决定它只适用于android系统(内存对android项目有多重要,地球人都知道)。
* <p>
*
* http://images.cnitblog.com/i/384215/201403/211043340846219.png
*
* http://images.cnitblog.com/i/384215/201403/211044337711918.png
*
* SparseArray有两个优点:
* 1.避免了自动装箱(auto-boxing),
*
* 2.数据结构不会依赖于外部对象映射。我们知道HashMap 采用一种所谓的“Hash 算法”来决定每个元素的存储位置,
* <p>
* 存放的都是数组元素的引用,通过每个对象的hash值来映射对象。而SparseArray则是用数组数据结构来保存映射,然后通过折半查找来找到对象。但其实一般来说,
* <p>
* SparseArray执行效率比HashMap要慢一点,因为查找需要折半查找,而添加删除则需要在数组中执行,而HashMap都是通过外部映射。但相对来说影响不大,
* <p>
* 最主要是SparseArray不需要开辟内存空间来额外存储外部映射,从而节省内存。
*/
public class SparseArrayClass extends SparseArray {
private HashMap<Integer, Object> hashmap = new HashMap<Integer, Object>();
private void getSparseArrayTest() {
SparseArray<String> sparse = new SparseArray<>();
long start = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
sparse.put(i, String.valueOf(i));
}
long memory = Runtime.getRuntime().totalMemory();
long end = System.currentTimeMillis();
long usedTime = end - start;
System.out.println("SparseArray消耗的时间是:" + usedTime + ",SparseArray占用的内存是:" + memory);
}
}
<file_sep>package com.example.baidu.retrofit.Study;
import android.os.Handler;
public class Handlers extends Handler {
/*
关于为什么 Looper 中的 loop() 方法不会造成主线程阻塞的原因就分析完了, 主要有两点原因:
1.耗时操作本身并不会导致主线程卡死, 导致主线程卡死的真正原因是耗时操作之后的触屏操作, 没有在规定的时间内被分发。
2.Looper 中的 loop()方法, 他的作用就是从消息队列MessageQueue 中不断地取消息, 然后将事件分发出去
https://user-gold-cdn.xitu.io/2019/2/26/16927e6098cf257b?imageView2/0/w/1280/h/960/format/webp/ignore-error/1
// 核心机制
去看下handler机制就明白了,网上一大把。
1.handler机制是使用pipe来实现的
2.主线程没有消息处理时阻塞在管道的读端
3.binder线程会往主线程消息队列里添加消息,然后往管道写端写一个字节,这样就能唤醒主线程从管道读端返回,也就是说queue.next()会调用返回
4.dispatchMessage()中调用onCreate, onResume
epoll+pipe,有消息就依次执行,没消息就block住,让出CPU,
等有消息了,epoll会往pipe中写一个字符,把主线程从block状态唤起,主线程就继续依次执行消息,怎么会死循环呢…
*/
}
<file_sep>package com.tool.cn.dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import com.tool.cn.BaseApplication;
import com.tool.cn.R;
import com.tool.cn.dialog.BaseDialog;
import java.util.Properties;
/**
* 相机相册选择框
* on 2017/6/8.
*/
public class CameraPhotoDialog extends BaseDialog implements View.OnClickListener {
TextView dialog_camera;
TextView dialog_photo;
TextView dialog_cancel;
private OnPickerListener onPickerListener;
private OnBackPressedListener onBackPressedListener;
public CameraPhotoDialog(Context context, Properties prop) {
super(context, R.layout.dialog_camera_photo, R.style.Theme_Dialog);
dialog_camera.setText(prop.getProperty("app.securityCenter.verified.takePicture")); //拍照
dialog_photo.setText(prop.getProperty("app.securityCenter.verified.photoAlbum")); //相册
dialog_cancel.setText(prop.getProperty("app.deposit.details.btn.cacncle")); //取消
}
@Override
protected void initView() {
Window window = getWindow();
window.setGravity(Gravity.BOTTOM);
WindowManager.LayoutParams windowLp = window.getAttributes(); // 获取对话框当前的参数值
windowLp.width = BaseApplication.mWidthPixels;
window.setAttributes(windowLp);
dialog_camera = getViewById(R.id.dialog_camera);
dialog_photo = getViewById(R.id.dialog_photo);
dialog_cancel = getViewById(R.id.dialog_cancel);
setOnClickListeners(this, dialog_camera, dialog_photo, dialog_cancel);
}
@Override
public void onClick(final View v) {
dismiss();
if (onPickerListener != null) {
onPickerListener.onPickerListener(v);
}
}
public interface OnPickerListener {
void onPickerListener(View view);
}
public void setOnPickerListener(OnPickerListener onClickListener) {
onPickerListener = onClickListener;
}
public interface OnBackPressedListener {
void onBackPressed();
}
public void setOnBackPressedListener(OnBackPressedListener onBackPressedListener){
this.onBackPressedListener =onBackPressedListener;
}
@Override
public void onBackPressed() {
super.onBackPressed();
if (onBackPressedListener != null) {
onBackPressedListener.onBackPressed();
}
}
}
<file_sep>package com.example.commonlibrary.utils;
import java.io.Closeable;
import java.io.IOException;
/**
* 2017/2/22 14:16.
*
*
* @version 1.0.0
* @class CloseUtils
* @describe 关闭IO流相关工具类
*/
@SuppressWarnings({"unused", "WeakerAccess"})
public class CloseUtils {
/**
* 关闭IO
*
* @param closeables closeable
*/
public static void closeIO(Closeable... closeables) {
if (closeables == null) return;
for (Closeable closeable : closeables) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 安静关闭IO
*
* @param closeables closeable
*/
public static void closeIOQuietly(Closeable... closeables) {
if (closeables == null) return;
for (Closeable closeable : closeables) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException ignored) {
}
}
}
}
}
<file_sep>package com.example.commonlibrary.widget.recycler;
import android.content.Context;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
/**recyclerview中的linear布局时用到的测量recyclerview高度
* Created by 关 on 2016/4/8.
*/
public class CustomLinearLayoutManager extends LinearLayoutManager {
RecyclerView recyclerView;
int spanCount;
public CustomLinearLayoutManager(Context context) {
super(context);
}
public CustomLinearLayoutManager(Context context, RecyclerView recyclerView) {
super(context);
this.recyclerView = recyclerView;
}
public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public CustomLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
super.onMeasure(recycler, state, widthSpec, heightSpec);
int measuredWidth = recyclerView.getMeasuredWidth();
int measuredHeight = recyclerView.getMeasuredHeight();
int myMeasureHeight = 0;
int count = state.getItemCount();
for (int i = 0; i < count; i++) {
View childView = recycler.getViewForPosition(i);
if (recyclerView != null) {
if (myMeasureHeight < measuredHeight) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) childView.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec, getPaddingLeft() + getPaddingRight(), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec, getPaddingTop() + getPaddingBottom(), p.height);
childView.measure(childWidthSpec, childHeightSpec);
myMeasureHeight += childView.getMeasuredHeight() + p.bottomMargin + p.topMargin;
}
recycler.recycleView(childView);
}
}
setMeasuredDimension(measuredWidth, Math.min(measuredHeight, myMeasureHeight));
}
}
<file_sep>package com.example.baidu.retrofit.Study;
import java.lang.reflect.Array;
import java.util.Arrays;
/**
* 二分查找法
*/
public class BinarySearch {
/**
* ContainerHelpers.binarySearch
*
* @param array
* @param size
* @param value
* @return
*/
// This is Arrays.binarySearch(), but doesn't do any argument validation.
static int binarySearch(int[] array, int size, int value) {
int lo = 0;
int hi = size - 1;
while (lo <= hi) {
final int mid = (lo + hi) >>> 1;
final int midVal = array[mid];
if (midVal < value) {
lo = mid + 1;
} else if (midVal > value) {
hi = mid - 1;
} else {
return mid; // value found
}
}
return ~lo; // value not present
}
/**
* @param a
* @param fromIndex
* @param toIndex
* @param key
* @return
*/
private static int binarySearch0(int[] a, int fromIndex, int toIndex,
int key) {
int low = fromIndex;
int high = toIndex - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = a[mid];
if (midVal < key)
low = mid + 1;
else if (midVal > key)
high = mid - 1;
else
return mid; // key found
}
return -(low + 1); // key not found.
}
/**
* 递归二分查找
*
* @param arr
* @param start
* @param end
* @param key
* @return
*/
public static int binarySearch(int[] arr, int start, int end, int key) {
if (start > end) {
return -1;
}
int mid = (end + start) >>> 1;
if (arr[mid] == key) {
return mid;
} else if (arr[mid] < key) {
return binarySearch(arr, mid + 1, end, key);
} else if (arr[mid] > key) {
return binarySearch(arr, start, mid - 1, key);
} else {
return -1;
}
}
}
|
299154b38a1b5dac23909ef662c5c2b17dbf2b72
|
[
"Java",
"Kotlin",
"Gradle"
] | 76
|
Java
|
flybigpig/Retrofit
|
41de6150ced74218dc9c9e69d99ad2e7d0b58fdc
|
c906ee8c63edeed71b44ecf9a56814dbbe03383a
|
refs/heads/master
|
<repo_name>chigoeu/chigoeu<file_sep>/index.php
<?php
header('Content-type: application/json');
echo file_get_contents('res.json');
<file_sep>/ping.php
<?php
header('Content-type: application/json');
error_reporting(0);
$domains = array('ping.chigo.cf','ping.chigo.ga','ping.chigo.gq','ping.chigo.ml','ping.chigo.tk');
foreach($domains as $host) {
$timehost = time().'.'.$host;
$res = dns_get_record($timehost, DNS_A);
//$resarr[] = $timehost;
$resarr[] = $res[0]['ip'];
}
$c = json_encode($resarr);
file_put_contents('res.json', $c);
echo $c;
|
a7d97907e953b6b2a9beca9cbe2fbca1968dbc45
|
[
"PHP"
] | 2
|
PHP
|
chigoeu/chigoeu
|
e60552730fc2c51e2ec3a64dbfab35f3bf1fa5fe
|
79268864e761ff9039e0a6377d5a1470d8ed9ed6
|
refs/heads/master
|
<repo_name>carlosxmerca/booknotes<file_sep>/precache-manifest.18d11adf2bee5165c3947bffd548ab5b.js
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "bd512e95ba1a34746c95",
"url": "/booknotes/css/app.088ca81a.css"
},
{
"revision": "f37dd1c1ddae0ecbe404",
"url": "/booknotes/css/chunk-vendors.52eaf30c.css"
},
{
"revision": "82b9c7a5a3f405032b1db71a25f67021",
"url": "/booknotes/img/logo.82b9c7a5.png"
},
{
"revision": "11fe06b5b9f6fa05f83d9010d74fb9be",
"url": "/booknotes/index.html"
},
{
"revision": "bd512e95ba1a34746c95",
"url": "/booknotes/js/app.5e9ee88d.js"
},
{
"revision": "b29b17813a03e1cff530",
"url": "/booknotes/js/chunk-2d0aab8a.038fac7f.js"
},
{
"revision": "f37dd1c1ddae0ecbe404",
"url": "/booknotes/js/chunk-vendors.d36ae75f.js"
},
{
"revision": "556cf907d7254d13b3a135174ce092a1",
"url": "/booknotes/manifest.json"
},
{
"revision": "b6216d61c03e6ce0c9aea6ca7808f7ca",
"url": "/booknotes/robots.txt"
}
]);
|
afa3f6bc0b7d21ef99b6480a28a8e1a768c9ae6f
|
[
"JavaScript"
] | 1
|
JavaScript
|
carlosxmerca/booknotes
|
a9e39441f396b3580fc174f951b31678babcf7f5
|
d5a91cfdd69d81b72a904ecdc4449b1efec23834
|
refs/heads/master
|
<file_sep># xamarin-background-video
Xamarin.Forms video in background demo project
<file_sep>using System;
using System.IO;
using BackgroundVideo.Controls;
using BackgroundVideo.iOS.Renderers;
using Foundation;
using MediaPlayer;
using UIKit;
using Xamarin.Forms;
using Xamarin.Forms.Platform.iOS;
[assembly: ExportRenderer(typeof(Video), typeof(VideoRenderer))]
namespace BackgroundVideo.iOS.Renderers
{
public class VideoRenderer : ViewRenderer<Video, UIView>
{
MPMoviePlayerController videoPlayer;
NSObject notification = null;
protected override void OnElementChanged(ElementChangedEventArgs<Video> e)
{
base.OnElementChanged(e);
if (Control == null)
{
InitVideoPlayer();
}
if (e.OldElement != null)
{
// Unsubscribe
notification?.Dispose();
}
if (e.NewElement != null)
{
// Subscribe
notification = MPMoviePlayerController.Notifications.ObservePlaybackDidFinish((sender, args) =>
{
/* Access strongly typed args */
Console.WriteLine("Notification: {0}", args.Notification);
Console.WriteLine("FinishReason: {0}", args.FinishReason);
Element?.OnFinishedPlaying?.Invoke();
});
}
}
void InitVideoPlayer()
{
var path = Path.Combine(NSBundle.MainBundle.BundlePath, Element.Source);
if (!NSFileManager.DefaultManager.FileExists(path))
{
Console.WriteLine("Video not exist");
videoPlayer = new MPMoviePlayerController();
videoPlayer.ControlStyle = MPMovieControlStyle.None;
videoPlayer.ScalingMode = MPMovieScalingMode.AspectFill;
videoPlayer.RepeatMode = MPMovieRepeatMode.One;
videoPlayer.View.BackgroundColor = UIColor.Clear;
SetNativeControl(videoPlayer.View);
return;
}
// Load the video from the app bundle.
NSUrl videoURL = new NSUrl(path, false);
// Create and configure the movie player.
videoPlayer = new MPMoviePlayerController(videoURL);
videoPlayer.ControlStyle = MPMovieControlStyle.None;
videoPlayer.ScalingMode = MPMovieScalingMode.AspectFill;
videoPlayer.RepeatMode = Element.Loop ? MPMovieRepeatMode.One : MPMovieRepeatMode.None;
videoPlayer.View.BackgroundColor = UIColor.Clear;
foreach (UIView subView in videoPlayer.View.Subviews)
{
subView.BackgroundColor = UIColor.Clear;
}
videoPlayer.PrepareToPlay();
SetNativeControl(videoPlayer.View);
}
protected override void OnElementPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
base.OnElementPropertyChanged(sender, e);
if (Element == null || Control == null)
return;
if (e.PropertyName == Video.SourceProperty.PropertyName)
{
InitVideoPlayer();
}
else if (e.PropertyName == Video.LoopProperty.PropertyName)
{
var liveImage = Element as Video;
if (videoPlayer != null)
videoPlayer.RepeatMode = Element.Loop ? MPMovieRepeatMode.One : MPMovieRepeatMode.None;
}
}
}
}
<file_sep>using System.Diagnostics;
using Xamarin.Forms;
namespace BackgroundVideo
{
public partial class BackgroundVideoPage : ContentPage
{
public BackgroundVideoPage()
{
InitializeComponent();
video.OnFinishedPlaying = () => { Debug.WriteLine("Video Finished"); };
}
}
}
|
e1663a400d68e31905e4b97dddde3f87b97cab14
|
[
"Markdown",
"C#"
] | 3
|
Markdown
|
rraallvv/xamarin-background-video
|
ddc4a6600ffb3d24ac4b4c4348047d26f14d0ef9
|
0b8500aed28310e6b1392ace9691c46c8053c51e
|
refs/heads/master
|
<file_sep>const express = require('express')
const { ApolloServer, gql } = require('apollo-server-express')
const { user } = require('./src/resolvers/user')
const { task } = require('./src/resolvers/task')
const typeDefs = gql`
type User {
id: ID!
username: String!
first_name: String
last_name: String
email: String!
password: String!
tasks: [Task]
}
type Task {
id: ID!
title: String!
user_id: ID!
author: User!
completed: Boolean!
description: String
author: User!
}
type Query {
user(id: ID!): User!
task(id: ID!): Task!
}
input createUserInput {
username: String!
first_name: String
last_name: String
email: String!
password: <PASSWORD>!
}
inputy createTaskInput {
title: String!
description: String
user_id: ID!
}
type Mutation {
createUser(input: createUserInput): String
createTask(input: createTaskInput): String
}
`
const resolvers = {
Query: {
...user.queries,
...task.queries
},
User: {
tasks({ user_id }) {
return task.allForUser(user_id)
}
},
Task: {
author({ user_id }) {
return user.byId(user_id)
}
}
}
const server = new ApolloServer({ typeDefs, resolvers })
const app = express()
const port = 3000
app.listen({ port }, () =>
console.log(`Server is ready at http:/localhost:${port}${server.graphqlPath}`)
)
<file_sep>const { user } = require("../user")
const AES = require("crypto-js/aes")
let createUserId
describe('User', async () => {
it('successfully gets user by id', async () => {
const { id, username, password, email} = await user.byId(1)
expect(id).toEqual(1)
expect(username).toBeDefined()
expect(password).toBeDefined()
expect(email).toBeDefined()
})
it('returns undefined if the user does not exist', async () => {
const res = await user.byId(999999)
expect(res).toBeUndefined()
})
it('successfully creates new user if provided with needed data and returns new id', async () => {
const randomString = Math.random()
.toString(24)
.substring(7)
const password = AES.encrypt('Message', randomString).toString()
const email = `${<EMAIL>`
createUserId = await user.create({
username: randomString,
first_name: randomString,
last_name: randomString,
email,
password
})
expect(createUserId).toBeDefined()
expect(createUserId).toBeGreaterThan(0)
})
it('does not work if trying to create user with incorrect data', async () => {
const { name } = await user.create({ username: 'asd', email: null, password: '<PASSWORD>' })
expect(name).toEqual("error")
})
})<file_sep>exports.up = (knex, _) =>
knex.schema.createTable('users', table => {
table.increments().primary()
table.timestamps(true, true)
table
.string('username')
.notNullable()
.unique()
table
.string('email')
.notNullable()
.unique()
table
.string('password')
.notNullable()
table
.string('first_name')
.nullable()
table
.string('last_name')
.nullable()
})
exports.down = (knex, _) => knex.schema.dropTable('users')
<file_sep>const { db, tables } = require("../../db/knex")
const byId = id =>
db(tables.TASKS)
.where({ id })
.first()
.then(task => task)
const all = () => db.select().table(tables.TASKS)
const allForUser = user_id =>
db(tables.TASKS)
.where(({ user_id }))
.then(tasks => tasks)
const remove = id =>
db(tables.TASKS)
.where(({ id }))
.del()
.returning('id')
.then(([id]) => id)
.catch(e => e);
const create = ({ title, description, user_id }) =>
db(tables.TASKS)
.insert({ title, description, user_id })
.returning('id')
.then(([id]) => id)
.catch(e => e)
const queries = {
task(_, { id }, ctx, info) {
return byId(id)
}
}
const mutations = {
createTask(
_,
{
input: { title, description, user_id }
},
ctx,
info
) {
return create({ title, description, user_id })
},
removeTask(_, { id }, ctx, info) {
return remove(id);
}
}
module.exports = {
task: {
mutations,
queries,
create,
allForUser,
all,
remove,
byId
}
}
<file_sep># RN Todo App Server
### Installation
- Create two postgres databases - **rn_todo_dev** and **rn_todo_test**
- Run `yarn install`
- Run `yarn run run-migrations:dev` to build database tables
- Run `yarn run run-seeds:dev` to include some data to database
- Run `yarn run start:dev` to start server for development
### Testing
- Run `yarn run test-full` to implement migrations and some data to test database before test running or if You want to just run tests You can use `yarn run test`<file_sep>const { task } = require("../task")
let createTaskId
describe('Task', async () => {
it('successfully gets tasks by user id', async () => {
const tasks = await task.allForUser(1)
tasks.forEach(task => {
expect(task).toHaveProperty('id')
expect(task).toHaveProperty('title')
expect(task.user_id).toEqual(1)
})
expect(tasks).toBeInstanceOf(Array)
})
it('successfully gets task by id', async () => {
const { id, title, user_id} = await task.byId(1)
expect(id).toEqual(1)
expect(title).toBeDefined()
expect(user_id).toBeDefined()
})
it('returns undefined if the task does not exist', async () => {
const res = await task.byId(999999)
expect(res).toBeUndefined()
})
it('successfully creates new task if provided with needed data and returns new id', async () => {
const randomString = Math.random()
.toString(24)
.substring(7)
createTaskId = await task.create({
title: randomString,
description: randomString,
user_id: 1
})
expect(createTaskId).toBeDefined()
expect(createTaskId).toBeGreaterThan(0)
})
it('does not work if trying to create task with incorrect data', async () => {
const { name } = await task.create({ title: null, description: 'zxc', user_id: 1 })
expect(name).toEqual("error")
})
it('gets all tasks from database', async () => {
const tasks = await task.all()
tasks.forEach(task => {
expect(task).toHaveProperty('id')
expect(task).toHaveProperty('title')
expect(task).toHaveProperty('user_id')
})
expect(tasks).toBeInstanceOf(Array)
})
it('removes task from the database, consuming id as a param', async () => {
const result = await task.remove(createTaskId)
expect(result).toEqual(createTaskId)
const getTask = await task.byId(createTaskId)
expect(getTask).toBeUndefined()
});
})<file_sep>exports.up = (knex, _) =>
knex.schema.createTable('tasks', table => {
table.increments().primary()
table.timestamps(true, true)
table
.string('title')
.notNullable()
table
.string('description', 1000)
table
.boolean('complete')
.notNullable()
.defaultTo(false)
//relationships
table
.integer('user_id')
.notNullable()
.references('users.id')
})
exports.down = (knex, _) => knex.schema.dropTable('tasks')
|
845566a5e58f67c121fb00ca3d3c5d9024eb7b91
|
[
"JavaScript",
"Markdown"
] | 7
|
JavaScript
|
Ryver966/React-Native-Todo-App
|
91ea1c407e8eec36aed1c2ad1a0dbd7e53c4a45f
|
fc592c15e46358effda68d0bb0491b263fa377ac
|
refs/heads/master
|
<repo_name>lubkli/asiop<file_sep>/asiop/StatusMenuController.swift
//
// StatusMenuController.swift
// asiop
//
// Created by <NAME> on 22/07/16.
// Copyright © 2016 lubkli. All rights reserved.
//
import Cocoa
class StatusMenuController : NSObject {
let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(NSVariableStatusItemLength)
let popover = NSPopover()
var eventMonitor: EventMonitor?
var preferencesWindowController: PreferencesWindowController?
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var statusMenu: NSMenu!
override func awakeFromNib() {
let icon = NSImage(named: "statusIcon")
icon?.template = true // best for dark mode
statusItem.image = icon
//statusItem.title = "ATARI SIO"
statusItem.menu = statusMenu
popover.contentViewController = PeripheralsViewController(nibName: "PeripheralsViewController", bundle: nil)
popover.appearance = NSAppearance.init(named: NSAppearanceNameAqua)
eventMonitor = EventMonitor(mask: [.LeftMouseDownMask, .RightMouseDownMask]) { [unowned self] event in
if self.popover.shown {
self.closePopover(event)
}
}
eventMonitor?.start()
}
func showPopover(sender: AnyObject?) {
if let button = statusItem.button {
popover.showRelativeToRect(button.bounds, ofView: button, preferredEdge: NSRectEdge.MinY)
}
eventMonitor?.start()
}
func closePopover(sender: AnyObject?) {
popover.performClose(sender)
eventMonitor?.stop()
}
@IBAction func peripheralsClicked(sender: AnyObject) {
if (popover.shown) {
closePopover(sender)
} else {
showPopover(sender)
}
}
@IBAction func preferencesClicked(sender: AnyObject) {
if (preferencesWindowController == nil) {
preferencesWindowController = PreferencesWindowController(windowNibName: "PreferencesWindowController")
}
preferencesWindowController?.showWindow(self)
preferencesWindowController?.window?.makeKeyAndOrderFront(nil)
NSApplication.sharedApplication().activateIgnoringOtherApps(true)
}
@IBAction func aboutClicked(sender: AnyObject) {
let alert = NSAlert()
alert.messageText = "About SIO Peripherals"
alert.informativeText = "SIO Peripherals emulator for 8-bit ATARI Computers.\n\nFor proper operation is necessary attached SIO2PC interface.\n\nProject home is at https://github.com/lubkli/asiop"
alert.addButtonWithTitle("OK")
alert.runModal()
/* let result = alert.runModal()
switch(result) {
case NSAlertFirstButtonReturn:
...
default:
break
} */
}
@IBAction func quitClicked(sender: NSMenuItem) {
NSApplication.sharedApplication().terminate(self)
}
}
<file_sep>/asiop/PreferencesWindowController.swift
//
// PreferencesWindowController.swift
// asiop
//
// Created by <NAME> on 06/08/16.
// Copyright © 2016 lubkli. All rights reserved.
//
import Cocoa
class PreferencesWindowController: NSWindowController {
@IBOutlet var preferencesWindow: NSWindow!
/*override convenience init() {
self.init(windowNibName: "PreferencesWindowController")
}*/
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
}
|
e86533793314af3d03b04dacb2fd657887be2bde
|
[
"Swift"
] | 2
|
Swift
|
lubkli/asiop
|
0a0408cbdad478de07004242d1f851a2545bfc21
|
b639df6efff63ae8078c5fbd9c8d3bdc0ec59cd7
|
refs/heads/master
|
<file_sep>##########################################################
####### Code for Pinnacles Biodiversity Paper ############
################# <NAME> 2017 ########################
setwd("~/Dropbox/ResearchProjects/Biodiv Paper/Pinnacles_Bee_Biodiversity")
library(dplyr)
library(plyr)
library(RColorBrewer)
library(tidyverse)
library(reshape2)
library(ggplot2)
library(extrafont)
library(vegan)
# font_import() # this takes a while so only run it if making figures to export with Arial font
loadfonts() # Adds fonts for PDF graphics only
library(showtext)
## add the Arial font
font_add("Arial", regular = "arial.ttf",
bold = "arialbd.ttf", italic = "ariali.ttf", bolditalic = "arialbi.ttf")
## Figure 1: Map made in ArcGIS using the file "loc_days_species.csv"
## Tables 1 & 2: Summary statistics of species and specimen numbers per year of study were calculated in excel using the file "Species_list.csv" (shared in Supplementary material)
## Figure 2a prep: Barplot comparisons across years
## Calculate how many years each species was collected
Species_years = read.csv("Species_list.csv", header = TRUE)
Species_years = subset(Species_years, Num_years != "NA", select = c("Family", "Species", "Num_years"))
## Group species by family and number of years recorded
fam_years = Species_years %>%
dplyr::group_by(Family, Num_years) %>%
dplyr::summarise(count = n())
## Calculate number of species per family
fam_num = Species_years %>%
dplyr::group_by(Family) %>%
dplyr::summarise(species_per_family = n())
## Coerce into crostab
spyears <- dcast(fam_years, Family~Num_years, value.var="count")
spyears = spyears %>% remove_rownames %>% column_to_rownames(var="Family")
spyears[is.na(spyears)] <- 0
spyears = as.matrix(spyears)
names_leg=c("Andrenidae (N = 97)", "Apidae (N = 122)" , "Colletidae (N = 21)", "Halictidae (N = 60)", "Megachilidae (N = 148)", "Melittidae (N = 2)")
# Fig 2b prep
Prop_specyear <- read.csv("SpeciesinFamily_450.csv", header = TRUE, row.names = 1)
years = c("All96", "New97", "New98", "New99", "New02", "New11", "New12")
prop_years = Prop_specyear[,years]/rowSums(Prop_specyear[,years])
totals = rowSums(Prop_specyear[,years])
color.vec = brewer.pal(n = 7, name = "YlGnBu")
# Figure 2 plotting (a and b)
###### Side by side barplot #######
# bitmap("Fig2.tiff", height = 12, width = 17, units = "cm", type = "tifflzw", res = 300)
loadfonts(device = "postscript")
postscript("Fig2.eps", width = 12, height = 18, horizontal = FALSE, onefile = FALSE, paper = "special", colormodel = "cmyk", family = "Arial")
par(mfrow=c(2,1), omi=c(1, 0.8, 0.2, 0))
# Fig 2a: Species per year in each family
par(mai=c(1.8, 0.5, 0.5, 0.2))
barplot(spyears, beside = TRUE, col=brewer.pal(n = 6, name = "Set3"))
mtext(side = 2, line = 2.75, text = "Number of species", font = 2, cex = 2)
mtext(side = 1, line = 3.75, text = "Number of years a species was present", font = 2, cex = 2)
legend("top", names_leg, pch=15, cex = 1.3, col=brewer.pal(n = 6, name = "Set3"), title = "Bee Families")
mtext("a", side = 1, line = 4, at = -2, cex = 3.5, font = 2)
## Figure 2b: Family accumulation over years
par(mai=c(0.5, 0.5, 1.8, 0.2))
barplot(t(prop_years), las=1, col=color.vec, names=c("Andrenidae \n (N = 97)", "Apidae \n (N = 122)" , "Colletidae \n (N = 21)", "Halictidae \n (N = 60)", "Megachilidae \n (N = 148)", "Melittidae \n (N = 2)"))
mtext(side = 2, line = 2.75, text = "Proportion of total species collected", font = 2, cex = 2)
mtext(side = 1, line = 3.75, text = "Bee Family (N = total species collected)", font = 2, cex = 2)
years_leg = c("1996", "1997", "1998", "1999", "2002", "2011", "2012")
legend(4.35, 1.16, legend=years_leg[6:7], xpd=NA, ncol=2, pch=22, pt.bg=color.vec[6:7], pt.cex=3, text.font = 1, title = "Recent Collection Years")
legend(3.6,1.16, legend=years_leg[5], xpd=NA, ncol=1, pch=22, pt.bg=color.vec[5], pt.cex=3, text.font = 1, title = "Bowl Study")
legend(1.5,1.16, legend=years_leg[1:4], xpd=NA, ncol=4, pch=22, pt.bg=color.vec[1:4], pt.cex=3, text.font = 1, title = "Early Museum Collection Years")
mtext("b", side = 1, line = 4, at = -0.2, cex = 3.5, font = 2)
dev.off() # run this line after figure code to finish saving out figure to file
## Figure 3: Habitat type rarefaction curve
samples = read.csv("samples.csv", header = TRUE, row.names = 1)
## Species accumulation curve
## observed curve
accumcurve = specaccum(samples, method = "rarefaction")
quartz(height = 6, width = 10)
## Fig save for journal specs
postscript("Fig3.eps", width = 10, height = 6, horizontal = FALSE, onefile = FALSE, paper = "special", colormodel = "cmyk", family = "Arial")
par(mai=c(1, 1, 0.8, 0.2))
plot(accumcurve, ci.type="poly", col = "black", lwd=2, ci.lty=0, ci.col="grey", ylab = "Number of bee species found", xlab = "Number of plot samples in recent survey", cex = 0.8, cex.lab = 1.3, font.lab =2)
## expected curve for comparison
accumcurve.random = specaccum(samples, "random")
plot(accumcurve.random, col="blue", add=TRUE)
dev.off()
## run to save figure as tiff file
tiff(filename = "Biodiv_Fig3.tiff", units = "in", compression = "lzw", res = 300, width = 10, height = 6)
# (run code script here)
dev.off() # then run this line after figure code to finish saving out figure to file
## Table 3: full data for these rank abundance summaries is shared in Supplementary material
## Figure 4: Map made in ARCGis using data from file "Study_comparison.csv"
#### Figure 5: Study comparison (Data from Table S1)
surveys = read.csv("Study_comparison.csv", header = TRUE) # may need to add 'stringsAsFactors = FALSE' if not importing correctly
names(surveys)
dim(surveys)
pinn_col = rep("black", times=length(surveys[,1]))
pinn_col[which(surveys$Study=="Pinnacles National Park, CA")]="red"
plot(surveys$Species ~ surveys$Area, las=1, pch=19, col = pinn_col)
lin_mod = lm(surveys$Species ~ surveys$Area)
abline(lin_mod)
text("topright", paste("R2=",round(summary(lin_mod)$ r.squared, digits=3), sep=""))
text(topright, paste("p-value=",round(summary(lin_mod)$ coefficients[[2,4]], digits=3), sep=""))
mtext("Linear model", line = 1, font=2)
plot(surveys$Species ~ log(surveys$Area), las=1, pch=19, col = pinn_col)
log_mod = lm(surveys$Species ~ log(surveys$Area))
abline(log_mod)
text(x=2.5, y=600, paste("R2=",round(summary(log_mod)$ r.squared, digits=3), sep=""))
text(x=2.5, y=550, paste("p-value=",round(summary(log_mod)$ coefficients[[2,4]], digits=3), sep=""))
mtext("Logarithmic model", line = 1, font=2)
plot(log(surveys$Species) ~ log(surveys$Area), las=1, pch=19, col = pinn_col)
power_mod = lm(log(surveys$Species) ~ log(surveys$Area))
abline(power_mod)
text(x=2.5, y=6.25, paste("R2=",round(summary(power_mod)$ r.squared, digits=3), sep=""))
text(x=2.5, y=6.1, paste("p-value=",round(summary(power_mod)$ coefficients[[2,4]], digits=3), sep=""))
mtext("power-law model", line = 1, font=2)
##Look for largest residual
plot(residuals(power_mod) ~ log(surveys$Area), las=1, pch=19, ylim=c(-max(abs(residuals(power_mod))), max(abs(residuals(power_mod))) ), col = pinn_col)
abline(h=0, col="gray")
abline(h = c(-residuals(power_mod)[which(surveys$Study=="Pinnacles National Park, CA")], residuals(power_mod)[which(surveys$Study=="Pinnacles National Park, CA")]), lty=2, col="darkred")
##Convert to a percentage of predicted.
percent_deviation_A = (surveys$Species - exp(predict(power_mod)))/exp(predict(power_mod))*100
sort_order = rev(order(percent_deviation_A))
percent_deviation = percent_deviation_A[sort_order]
bar_col = rep("gray20", times = length(surveys[,1]))
bar_col[which(percent_deviation>0)]="gray80"
beta = power_mod$coefficients
area_range = seq(from = min(surveys$Area), to = max(surveys$Area), length.out=300)
pred_species = exp(beta[1]+beta[2]*log(area_range))
quartz(width=10, height=6)
par(mfrow=c(1,2))
par(mar=c(5.5, 5, 2, 2)+0.1)
surveys_col = rep("gray20", times = length(surveys[,1]))
surveys_col[which(percent_deviation_A>0)]="gray80"
plot(surveys$Species ~ surveys$Area, las=1, pch=21, bg = surveys_col, ylab="Number of species", xlab="Area (sq. km.)")
points(x = area_range, y = pred_species, type='l', lwd=2)
points(x = area_range[which(surveys$Study=="Pinnacles National Park, CA")],
y = pred_species[which(surveys$Study=="Pinnacles National Park, CA")],
pch=21, cex=3)
par(mar=c(15, 6, 2, 2)+0.1)
barplot(height = percent_deviation, las=2, names.arg = surveys$Study[sort_order], yaxs = 'r', ylab = "Observed relative to predicted\nspecies per area (%)", col = bar_col)
abline(h=0)
box(which="plot")
legend("topright", legend = c("> predicted", "< predicted"), pch=22, pt.bg = c("gray80", "gray20"), pt.cex=2, inset=0.05, bty='n')
axis(side = 1, at = seq(from = 0.75, by = 1.2, length.out=length(surveys[,1])), labels=FALSE)
#### Fig save for journal specs
postscript("Fig5.eps", width = 10, height = 5.5, horizontal = FALSE, onefile = FALSE, paper = "special", colormodel = "cmyk", family = "Arial")
par(mfrow=c(1,2))
par(mar=c(7, 5, 3, 2)+0.1)
surveys_col = rep("gray20", times = length(surveys[,1]))
surveys_col[which(percent_deviation_A>0)]="gray80"
plot(log(surveys$Species) ~ log(surveys$Area), las=1, pch=21, bg = surveys_col, ylab="ln (Number of bee species)", xlab="ln (Area surveyed (sq.km.))", cex.lab = 1.2, font.lab = 2)
points(x = log(surveys$Area), y = predict(power_mod), type='l', lwd=2)
points(x = log(surveys$Area)[which(surveys$Study=="Pinnacles National Park, CA")],
y = log(surveys$Species)[which(surveys$Study=="Pinnacles National Park, CA")],
pch=21, cex=3, col = "red")
mtext("a", side = 1, line = 5, at = 1.5, cex = 2, font = 2)
par(mar=c(12, 6, 3, 2)+0.1)
barplot(height = percent_deviation, las=2, names.arg = surveys$Study[sort_order], cex.names = 0.75, yaxs = 'r', ylab = "Observed relative to predicted\nspecies per area (%)", col = bar_col, cex.lab = 1.2, font.lab = 2, border = c("red", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black"))
abline(h=0)
box(which="plot")
legend("topright", legend = c("> predicted", "< predicted"), pch=22, pt.bg = c("gray80", "gray20"), pt.cex=2, inset=0.05, bty='n')
axis(side = 1, at = seq(from = 0.75, by = 1.2, length.out=length(surveys[,1])), labels=FALSE)
mtext("b", side = 1, line = 10, at = -3, cex = 2, font = 2)
dev.off()
#### S1 Fig
# load data on floral richness per plot sample
flor_rich = read.csv("floral_richness.csv", header = TRUE)
dim(flor_rich)
quartz(width = 10, height = 5.5)
par(mfrow=c(1,2), omi=c(0.2, 0.3, 0, 0))
## Linear Regression of FlorDiv and bee Richness
rich_rich = lm(flor_rich$beeRichness ~ flor_rich$floralRichness)
summary(rich_rich)
plot(beeRichness ~ floralRichness, data=flor_rich, col="black", pch=19, cex = 0.8, xlab= "Number of floral taxa", ylab= "Number of bee species", las=1, cex.lab = 1.2, font.lab = 2)
#abline(diversity)
text(x = c(12,12), y = c(62,56), labels=c("r2 = 0.37", "p < 0.001"))
# Build power model of Floral Richnes ~ Bee Richness
rich_rich_powerlog = lm(log(beeRichness) ~ log(floralRichness), data=flor_rich)
summary(rich_rich_powerlog)
floral_range = seq(from=min(na.omit(flor_rich$floralRichness)), to=max(na.omit(flor_rich$floralRichness)), by=1)
floral_range
betas = coefficients(rich_rich_powerlog)
betas
# Plot a regression line showing log relationship plotted along non-transformed data above
divmod_predict = exp(betas[1]+betas[2]*log(floral_range))
points(divmod_predict ~ floral_range, type = "l")
mtext("a", side = 1, line = 3, at = -1, cex = 2, font = 2)
###### Linear Regression of FlorDiv and bee sqrtAbundance
rich_abun = lm(flor_rich$sqrtAbun ~ flor_rich$floralRichness)
summary(rich_abun)
plot(sqrtAbun ~ floralRichness, data=flor_rich, col="black", pch=19, cex = 0.8, xlab= "Number of floral taxa", ylab= "sqrt (Bee abundance)", las=1, cex.lab = 1.2, font.lab = 2)
#abline(diversity)
text(x = c(12,12), y = c(34,31), labels=c("r2 = 0.16", "p < 0.001"))
# Build power model of Floral Richnes ~ Bee Abundance
rich_abun_powerlog = lm(log(sqrtAbun) ~ log(floralRichness), data=flor_rich)
summary(rich_abun_powerlog)
floral_range = seq(from=min(na.omit(flor_rich$floralRichness)), to=max(na.omit(flor_rich$floralRichness)), by=1)
floral_range
betas = coefficients(rich_abun_powerlog)
betas
# Plot a regression line showing log relationship plotted along non-transformed data above
divmod_predict = exp(betas[1]+betas[2]*log(floral_range))
points(divmod_predict ~ floral_range, type = "l")
mtext("b", side = 1, line = 3, at = -1, cex = 2, font = 2)
# format figure for journal
postscript("S1Fig.eps", width = 10, height = 5.5, horizontal = FALSE, onefile = FALSE, paper = "special", colormodel = "cmyk", family = "Arial")
dev.off()
<file_sep># Pinnacles_Bee_Biodiversity
We resurveyed Pinnacles National Park for native bee species and compared results to bee inventories completed 10 and 15 years earlier, as well as to similar efforts conducted across the U.S.
This work was published in the peer-reviewed journal PLOS ONE on January 17, 2019: https://doi.org/10.1371/journal.pone.0207566
Contact: <EMAIL> for more information.
|
478419817ffa2905916958c43837d95d2fa19021
|
[
"Markdown",
"R"
] | 2
|
R
|
beecycles/pinnacles_bee_biodiversity
|
6431eba5d961e3e2750b22e5674a61b2cc8cc4a2
|
7f485fbba272c2e1a56c46ba7fbdf8fa7cf4f167
|
refs/heads/master
|
<file_sep># **Botball is cool**
<file_sep>void turnLeft(int time, int power) {
create_drive_direct(-power, power);
msleep(time);
create_stop();
}
void turnRight(int time, int power) {
create_drive_direct(power, -power);
msleep(time);
create_stop();
}
void moveForward(int time, int power) {
create_drive_direct(-power, -power);
msleep(time);
create_stop();
}
void moveBackward(int time, int power) {
create_drive_direct(power, power);
msleep(time);
create_stop();
}
void moveClaw(int x) {
set_servo_position(1, x);
msleep(100);
}
void maxArm(int x) {
int y = x - get_servo_position(0);
int i = 0;
int z = 0;
for(i=0; i<18; i++){
z=get_servo_position(0);
set_servo_position(0,z+((y+1)/18));
//set_servo_position(0,z+50);
msleep(50);
}
}
/*void moveArm(int x) {
done = 0;
for(int i = 10, i > 0, i = i - 1)
set_servo_position(0, x - i);
sleep(0.1);
done = 1;
}*/
void openClaw() {
set_servo_position(1, 500);
msleep(100);
}
void openSlow() {
int i=0;
int y = 500-get_servo_position(1);
int z = get_servo_position(1);
for(i=0; i<8; i++) {
set_servo_position(1, z+((i+1)*y)/8);
msleep(50);
}
}
void closeClaw() {
set_servo_position(1, 1100);
msleep(100);
}
|
be76b9f944d47b3e5d1c75b09c71bff7e303d74c
|
[
"Markdown",
"C"
] | 2
|
Markdown
|
botball-Curiosity/546Curiosity
|
af8318261232551ed17b803528c92778f50166b2
|
cf3cf4da64e20f1721ab532dc1ba92d1e53af9a3
|
refs/heads/master
|
<repo_name>shiv3/CiscoTyping<file_sep>/HTML/gacha.php
<?php
session_start();
?>
<head>
<script type="text/javascript">
var gacha = {
main : function(){
gacha.init();
if(false){
//no get
$("#monster_zone_content").hide();
}else {
//get
//視覚効果
gacha.effect();
//モンスターの登場
gacha.entrance();
//フラグオン
//send_server(rnd);
}
},
//初期化
init : function(){
},
effect : function(){
},
entrance : function(){
var src = "../image/monster/"+<?php echo $_SESSION['get']; ?>+".png";
$("#monster_zone_content>img").attr("src", src);
}
}
</script>
<style>
#result_zone {
text-align: center;
font-size: 70px;
font-family:'monospace','Small Fonts',monospace;
text-shadow: 5px 5px 5px #999;
}
#message {
text-align: center;
font-size : 24px;
font-family :'monospace','Small Fonts',monospace;
text-shadow : 2px 2px 2px #999;
}
#monster_zone_content {
text-align: center;
}
#monster_zone_content img{
margin-top : 30px;
zoom : 2.0;
}
#button_zone {
text-align: center;
}
#button_zone button {
width : 300px;
height : 80px;
}
</style>
</head>
<div id="gacha_wrap" onload="gacha.event()">
<div id="result_zone">G a m e O v e r</div>
<div style="height : 230px;">
<div id="monster_zone_content">
<img src="../image/monster/5.png" /><br />
<span id="message">You Got New Baddy</span>
</div>
</div>
<div id="button_zone">
<button id="rtm" onclick="load_html('index.html')"> Return To Menu </button>
</div>
<script type="text/javascript">
gacha.main();
</script>
</div><file_sep>/Javascript/補欠/load_objects.js
var load_objects = function(number){
this.amount_objects = number; //読みたい画像の数
this.count_loadedobjects = 0; //読み込み終わった画像の数
this.preload_que = null; //読み込み前の待ち画像行列
this.loadedobjects_que = null; //読み終わった表示待ち行列
this.objects_x = null; //画像のx座標(配列)
this.objects_y = null; //画像のy座標(配列)
this.objects_species = null; //オブジェクトの種類 : 0:画像 1:文字
this.string_font = null;
this.string_style = null;
//ここから初期化
this.preload_que = new Array();
this.loadedobjects_que = new Array();
this.objects_x = new Array();
this.objects_y = new Array();
this.objects_species = new Array();
this.string_font = new Array();
this.string_style = new Array();
this.set_image = function(src, x, y){
this.preload_que.push(src);
this.objects_x.push(x);
this.objects_y.push(y);
this.objects_species.push(0);
}
this.set_text = function(str, x, y, font, style){
this.preload_que.push(str);
this.objects_x.push(x);
this.objects_y.push(y);
this.objects_species.push(1);
this.string_font.push(font);
this.string_style.push(style);
}
this.carryout = function(base){
if(this.objects_species[this.count_loadedobjects] == 0){
var Obj = new Image();
Obj.addEventListener('load', function(){
base.loadedobjects_que.push(Obj); //pushは要素数ごと増やす
base.count_loadedobjects++;
if(base.amount_objects == base.count_loadedobjects){
base.display();
}else{
base.carryout(base, base.count_loadedobjects);
}
}, false);
Obj.src = base.preload_que[base.count_loadedobjects];
}else if(this.objects_species[this.count_loadedobjects] == 1){
this.loadedobjects_que.push(this.preload_que[base.count_loadedobjects]);
this.count_loadedobjects++;
if(this.amount_objects == this.count_loadedobjects){
this.display();
}else{
this.carryout(base, this.count_loadedobjects);
}
}else {
colsole.log("予期せぬ動作をしています。");
}
}
//
this.display = function(){
while(this.loadedobjects_que.length > 0){
if(this.objects_species[0] == 0){
GUI.context.drawImage(this.loadedobjects_que[0], this.objects_x[0], this.objects_y[0]);
this.loadedobjects_que.splice(0, 1); //0番目から1つの要素を削除。そして前に詰める。
this.objects_x.splice(0, 1);
this.objects_y.splice(0, 1);
this.objects_species.splice(0, 1);
}else if(this.objects_species[0] == 1){
GUI.context.font = this.string_font[0];
GUI.context.fillStyle = this.string_style[0];
GUI.context.fillText(this.loadedobjects_que[0], this.objects_x[0], this.objects_y[0]);
this.loadedobjects_que.splice(0, 1);
this.objects_x.splice(0, 1);
this.objects_y.splice(0, 1);
this.string_style.splice(0, 1);
this.string_font.splice(0, 1);
this.objects_species.splice(0, 1);
}
}
}
this.show_array1 = function(){
for(var i=0;i<this.preload_que.length;i++){
console.log(this.preload_que[i]);
}
}
this.show_array2 = function(){
for(var i=0;i<this.loadedimages_que.length;i++){
console.log(this.loadedobjects_que[i]);
}
}
}<file_sep>/HTML/php/getmonster.php
<?php
session_start();
header('Content-Type: application/javascript; charset=utf-8');
$json = file_get_contents('php://input'); //読み込み用ストリーム
$data = json_decode($json, true);
$get = $data['get'];
$_SESSION['guide'][$get] = 1;
$_SESSION['get'] = $get;
$callback = isset($_GET['callback']) ? $_GET["callback"] : "";
$callback = htmlspecialchars(strip_tags($callback));
printf("{$callback}(%s)", json_encode( $get ));
?><file_sep>/Javascript/game/新しいフォルダー/timer.js
/*
使い方 : startcountにカウント数をセットして実行
*/
var timer = {
time : 1000,
//時間をセットする。
settime : function(t){
this.time = t;
},
//これを実行するとカウントダウン開始
startcount : function(a_time){
this.settime(a_time);
this.countdownloop();
},
//
decreasetime : function(t){
this.time -= t;
},
//画面への出力
showtime : function(){
//ここに出力の命令を書く
},
//カウントダウン開始
countdownloop : function(){
if(this.time > 0){
this.time -= 1;
this.showtime();
//音楽の切り替え
CtoC.sound_switch();
setTimeout("timer.countdownloop()",100);
}else{
CtoC.finish_game();
}
}
}<file_sep>/Javascript/game/effect.js
var Effect = function(num){
this.id = num;
this.image_loader;
this.preload_my_images = function(){
this.image_loader = new load_animation();
console.log(effect_db[this.id]['sprite'] +"の画像をセット");
this.image_loader.set_pass(effect_db[this.id]['sprite']);
//画像の読み込みを開始
this.image_loader.load_que_successive(this.image_loader);
}
}
//敵が死ぬ間際消えるやつ
var Vanishment_effect = function(){
this.vanish_count = 0;
this.carryout = function(){
GUI.image_context.globalAlpha = 1 - this.vanish_count / 30;
this.vanish_count++;
if(this.vanish_count > 30){
type_game_global.state_flg = 0;
this.vanish_count = 0;
clearTimeout(GUI.main_loop);
setTimeout(function(){
state_watcher.transfer_dungeon();
}, 1000);
}
}
}
//ダメージ発生時に相手が動くやつ
var take_damage_enemy = function(){
this.count = 0;
this.carryout = function(){
if(this.count > 30 && this.count < 60){
GUI.image_context.globalAlpha = 0;
}
this.count++;
}
}
//ダメージが可視化できるやつ
var Damage_effect = function(damage, x, y){
this.damage = damage;
this.count = 0;
this.init_x = x;
this.init_y = y;
this.effect = function(myself, index){
GUI.string_context.font = "32px 'Small Fonts'";
GUI.string_context.fillStyle = "black";
this.x = this.init_x;
this.y = this.init_y - 50 * Math.sin(Math.PI*this.count*9/180);
GUI.string_context.fillText(this.damage, this.x, this.y);
if(this.count > 20){
GUI.damage.splice(index);
}else{
this.count++;
}
}
}
<file_sep>/Javascript/game/新しいフォルダー/load_images.js
var load_images = function(number){
this.amount_images = number; //読みたい画像の数
this.count_loadedimages = 0; //読み込み終わった画像の数
this.preload_que = null; //読み込み前の待ち画像行列
this.loadedimages_que = null; //読み終わった表示待ち行列
this.image_src = null; //パス(配列)
this.image_x = null; //画像のx座標(配列)
this.image_y = null; //画像のy座標(配列)
//ここから初期化
this.preload_que = new Array();
this.loadedimages_que = new Array();
this.image_src = new Array();
this.image_x = new Array();
this.image_y = new Array();
this.set_image = function(obj, src, x, y){
this.preload_que.push(obj);
this.image_src.push(src);
this.image_x.push(x);
this.image_y.push(y);
}
this.carryout = function(base){
//alert(this.preload_que[this.count_loadedimages]);
this.preload_que[this.count_loadedimages].addEventListener('load', function(){
base.loadedimages_que.push(base.preload_que[base.count_loadedimages]); //pushは要素数ごと増やす
base.count_loadedimages++;
if(base.amount_images == base.count_loadedimages){
base.display();
}else{
base.carryout(base);
}
}, false);
//alert(this.image_src[this.count_loadedimages]);
this.preload_que[this.count_loadedimages].src = this.image_src[this.count_loadedimages];
}
//
this.display = function(){
for(var i=0;i<this.loadedimages_que.length;i++){
GUI.image_context.drawImage(this.loadedimages_que[i], this.image_x[i], this.image_y[i]);
}
}
this.regeneration = function(){
//いらない?
}
this.show_array1 = function(){
for(var i=0;i<this.preload_que.length;i++){
console.log(this.preload_que[i]);
}
}
this.show_array2 = function(){
for(var i=0;i<this.loadedimages_que.length;i++){
console.log(this.loadedimages_que[i]);
}
}
}
<file_sep>/Javascript/data/baddy_data.js
var baddy_db = new Array();
baddy_db[0] = {
//common
'id' : 0,
'name' : '<NAME>',
'hp' : 120,
'atk' : 10,
'dex' : 40,
//human
'type' : 'debug',
'mode' : "normal",
}
baddy_db[1] = {
//common
'id' : 1,
'name' : '<NAME>',
'hp' : 90,
'atk' : 50,
'dex' : 20,
//human
'type' : 'debug',
'mode' : "normal",
}
baddy_db[2] = {
//common
'id' : 2,
'name' : 'Hippogriff',
'hp' : 150,
'atk' : 30,
'dex' : 30,
//human
'type' : 'cisco',
'mode' : "normal",
}
baddy_db[3] = {
//common
'id' : 3,
'name' : 'M.D.Wurm',
'hp' : 50,
'atk' : 10,
'dex' : 10,
//human
'type' : 'cisco',
'mode' : "normal",
}
baddy_db[4] = {
//common
'id' : 4,
'name' : '<NAME>',
'hp' : 50,
'atk' : 10,
'dex' : 10,
//human
'type' : 'cisco',
'mode' : "normal",
}
baddy_db[5] = {
//common
'id' : 5,
'name' : 'Faelizard',
'hp' : 150,
'atk' : 40,
'dex' : 40,
//human
'type' : 'cisco',
'mode' : "normal",
}
baddy_db[6] = {
//common
'id' : 6,
'name' : 'kerobat',
'hp' : 130,
'atk' : 50,
'dex' : 10,
//human
'type' : 'cisco',
'mode' : "normal",
}
baddy_db[7] = {
//common
'id' : 7,
'name' : 'D.Schneider',
'hp' : 220,
'atk' : 80,
'dex' : 30,
//human
'type' : 'cisco',
'mode' : "normal",
}<file_sep>/Javascript/game/battle_system.js
//ゲーム終了処理を専門にした関数群
var state_watcher = {
game_set : 0,
vanishment : null,
//役割 : メインループを止めずに余分な処理を排除して遷移の準備をする
//1:敵の攻撃を止める
//2.敵の消失エフェクトをする
//3:入力を止める?(いまのところやらない方向)
watching_game_state : function(){
//game_set == 1 -> 敵が死んでいる
if(this.game_set === 1){
//this.vanishment.carryout();
}else{
this.enemy_take_damage_animation(); //
this.change_game_set_flg(); //敵の生死確認
}
},
change_game_set_flg : function(){
//ある意味アニメーションの分岐 -> 死:vanish 生:
if(unit_management.enemy.hp <= 0){
this.game_set = 1; //戦闘が終了したことを示す。
unit_management.enemy.alive = 0;
//敵の攻撃を止める
if(EnemyAttack){
clearTimeout(EnemyAttack);
}
//蛍の光 @ここじゃなく遷移前
audio_class.init("../sound/gameover.mp3", false);
//消失エフェクト エフェクト終了時にstate_flgを0にする
this.vanishment = new Vanishment_effect();
}else if(unit_management.your_baddy.hp <= 0){
this.game_set = 1; //戦闘が終了したことを示す。
unit_management.your_baddy.alive = 0;
//敵の攻撃を止める
if(EnemyAttack){
clearTimeout(EnemyAttack);
}
//消失エフェクト エフェクト終了時にstate_flgを0にする
this.vanishment = new Vanishment_effect();
}
},
enemy_take_damage_animation : function(){
},
initiate_battle_state : function(){
//state_watcher
this.game_set = 0;
this.vanishment = null;
//GUI
GUI.enemy = null;
GUI.effect = null;
GUI.damage = null;
GUI.main_loop = null;
//sound
//なし
//typing_mondai
typing_mondai.mean = null;
typing_mondai.command = null;
typing_mondai.now_typing = "";
//unit_management
unit_management.enemy = null;
//battle_system
battle_system.accumulate_damage = 0;
},
transfer_dungeon : function(){
//勝ち
type_game_global.dungeon.defeated_monster.push(type_game_global.dungeon.encounting);
this.initiate_battle_state();
console.log("探索モードへ");
type_game_global.dungeon.main();
//GUI.image_context.clearRect(0, 0, image_layer.width, image_layer.height);
//GUI.string_context.clearRect(0, 0, image_layer.width, image_layer.height);
//GUI.string_context.clearRect(0, 0, image_layer.width, image_layer.height);
}
}
/*戦闘システム
キーを打ったら攻撃 ->
ダメージ計算 -> 自分ATK/10
命中率 -> 自分SPD/(相手SPD*2)
その他
ノーミスボーナス
コンボ補正
*/
var battle_system = {
accumulate_damage : 0,
hit_judge : function(your_spd, enemy_spd){
var hit_flg = 0;
var hit_probability = your_spd / (enemy_spd * 2) * 100;
var rnd = Math.floor(Math.random() * 100);
//alert("確率:"+hit_probability+"<br>数値:"+rnd);
if(hit_probability > rnd){
hit_flg = 1;
}
return hit_flg;
},
damage_calculate : function(basis_atk){
var damage = (basis_atk / 10); //ダメージ計算式
damage = parseInt(damage);
return damage;
},
unit_attack : function(attacker, target){
console.log(attacker.name +"が"+ target.name +"に攻撃!");
//var hit = battle_system.hit_judge(attacker.dex, target.dex);
var hit = true;
if(hit === true){
var damage = battle_system.damage_calculate(attacker.atk);
console.log(target.unit_type);
if(target.unit_type === "enemy"){
this.accumulate_damage += damage;
}else {
target.take_damage(damage);
}
}
},
baddy_slash : function(target){
target.take_damage(this.accumulate_damage);
//エフェクト処理
var damage_str = new Damage_effect(this.accumulate_damage, 560, 200);
GUI.damage.push(damage_str);
GUI.effect.push(GUI.effect_data[0]);
this.accumulate_damage = 0;
}
}<file_sep>/Javascript/common/storage.js
//ストレージへのアクセス
var storage_class = {
local_storage : null,
// ウェブストレージの対応を調べる
correspondence : function(){
if(window.localStorage){
// ローカルストレージオブジェクトを取得する
storage_class.local_storage = window.localStorage;
// 出力テスト
console.log(storage_class.local_storage);
}
},
ObjectToJson : function(obj){
console.log('*ObjectToJsonを開始します。*');
console.log('第一引数:'+obj+' [データ型]'+typeof obj);
var str;
if(typeof obj === 'object'){
try{
// オブジェクトからJSON文字列に変換
str = JSON.stringify(obj);
return str;
}catch(e){
console.log('エラーが発生しました。');
return false;
}
}else {
console.log('変換しません。');
return obj;
}
},
JsonToObject : function(a_json){
console.log('*JsonToObjectを開始します。*');
//暇があったらisJson関数実装してください。
var translate = JSON.parse(a_json);
return translate;
},
//JSON形式でのストレージへの保存
put : function(a_key,a_data){
console.log('*putを開始します。*');
console.log('第一引数:'+a_key+' [データ型]'+typeof a_key);
console.log('第二引数:'+a_data+' [データ型]'+typeof a_data);
if(typeof a_key === 'string'){
try{
//書き込むデータをjson形式に変換する。
var jsondata = storage_class.ObjectToJson(a_data);
console.log('jsonに変換できました。');
// JSON 文字列を保存(key, data)
localStorage.setItem(a_key, jsondata);
console.log('書き込みに成功しました。');
}catch(e){
console.log('書き込みに失敗しました。');
}
}
},
//データの取得
get : function(a_key){
console.log('*getを開始します。*');
console.log('第一引数:'+a_key+' [データ型]'+typeof a_key);
if(typeof a_key === 'string'){
try{
//json形式でデータを取り出す。
var jsondata = localStorage.getItem(a_key);
console.log(jsondata+'を読み込みました。'+typeof jsondata);
// JSON文字列からオブジェクトに変換
var objdata = storage_class.JsonToObject(jsondata);
console.log('読み込みに成功しました。');
return objdata;
}catch(e){
alert("読み込みに失敗しました。");
return false;
}
}
}
}
<file_sep>/Javascript/data/enemy_data.js
var enemy_db = new Array();
enemy_db[0] = {
'id' : 0,
'name' : 'ブルーバード',
'hp' : 50,
'atk' : 30,
'spd' : 30,
'atk_freq' : 800,
}
enemy_db[1] = {
'id' : 1,
'name' : 'モンゴリアンデスワーム',
'hp' : 100,
'atk' : 100,
'spd' : 5,
'atk_freq' : 1000,
}
enemy_db[2] = {
'id' : 2,
'name' : 'ユメガエル',
'hp' : 50,
'atk' : 30,
'spd' : 20,
'atk_freq' : 500,
}
enemy_db[3] = {
'id' : 3,
'name' : 'ヒッポグルフ',
'hp' : 30,
'atk' : 60,
'spd' : 30,
'atk_freq' : 2000,
}
/*
enemy_db[4] = {
'id' : 4,
'name' : 'Mギンチャク',
'hp' : 60,
'atk' : 10,
'spd' : 20,
'atk_freq' : 250,
'src' : {
0 : '../image/monster/hippo.png'
}
}
enemy_db[5] = {
'id' : 5,
'name' : 'けつばん',
'hp' : 1,
'atk' : 1,
'spd' : 1,
'atk_freq' : 1000,
'src' : {
0 : '../image/monster/a.bmp'
}
}
*/<file_sep>/Javascript/common/ajax.js
var post_to_php = {
}
function registration(url){
$("#sousin").css("display","none");
var param = {
//"ticket": ticket,
"deck" : value
}; //テキストとハッシュ値
//ajaxでの送信
$.ajax({
type: "post",
url: url,
data: JSON.stringify(param),
crossDomain: false,
dataType : "jsonp",
scriptCharset: 'utf-8',
}).done(function(data){
alert(data);
$("#sousin").css("display","inline");
}).fail(function(XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
$("#sousin").css("display","inline");
});
}<file_sep>/Javascript/game/typing_mode.js
function initiate_state(){
var success = 0;
console.log("1ゲームの初期化中です...");
switch(type_game_global.initiate_counter){
case 0:
//状態を「バトル」に
type_game_global.state_flg = 1;
//BGMを変更
audio_class.init("../sound/normal.mp3", true);
type_game_global.initiate_counter++;
GUI.common_initiate();
break;
case 1: //ゲーム開始!
//エネいー
unit_management.create_enemy();
//文字の入力判定の設定
CtoC.initiate_section();
//GUIメインループの起動
GUI.main();
console.log("a");
//敵の攻撃開始
console.log("***************** 敵の攻撃開始 *****************");
EnemyAttack = setTimeout(function(){
unit_management.enemy.attack(unit_management.enemy, unit_management.your_baddy);
}, 5000 - unit_management.enemy.dex * 40);
success = 1;
type_game_global.initiate_counter = 0;
break;
default : //フラグの設定ミスの場合ここへ
console.log("********* 読み込みが完全に完了できなかったので強制的に開始します **********");
/*
if(){
type_game_global.initiate_counter = 1;
}*/
break;
}
if(success !== 1){
var repeat = setTimeout(function(){initiate_state()}, 16);
}
}
/* 今出題されている問題を格納 */
var typing_mondai = {
mean : null, //コマンドの意味
command : null, //シスココマンド
now_typing : "", //現在打ち込み終わった文
set_mondai : function(mean, command){
this.mean = mean;
this.command = command.toUpperCase();
this.now_typing = "";
},
show_mondai : function(){
console.log("mean : " + this.mean);
console.log("command : " + this.command);
}
}
var CtoC = {
combo : 0,
initiate_section : function(){
//ランダムに問題を生成。
var rnd = Math.floor(Math.random() * (Object.keys(t_mondai[unit_management.your_baddy.qtype]).length - 1));
console.log(Object.keys(t_mondai['cisco']).length);
typing_mondai.set_mondai(t_mondai[unit_management.your_baddy.qtype][rnd]['meaning'], t_mondai[unit_management.your_baddy.qtype][rnd]['command']);
},
check_keycode : function(evt){
console.log(evt.keyCode+"Key が押されました");
var kc = evt.keyCode;
if (kc == 27) {//エスケープキーが押された
CtoC.push_Escape();
}else{
CtoC.next_char(evt,kc);
}
},
next_char : function(evt,kc){
var chr = CtoC.trans_specialchar(kc);
//入力文字の正誤判定
var tf = CtoC.check_correspond(chr, typing_mondai.now_typing.length);
//この問題をクリアしたか判定(全文字入力済み)
if(typing_mondai.command.length <= typing_mondai.now_typing.length){
console.log("Go Next Q.");
sounds.system.playSound(2);
if(type_game_global.state_flg === 1){
battle_system.baddy_slash(unit_management.enemy);
CtoC.initiate_section();
}
}
//alert(typing_mondai.command.length+"/"+typing_mondai.now_typing.length);
},
check_correspond : function(input_char, num){
var true_or_faulse = 0;
var target_char = typing_mondai.command.charAt(num).toUpperCase(); //正解文字
if(input_char === target_char){
true_or_faulse = 1;
typing_mondai.now_typing += input_char;
sounds.system.playSound(0);
console.log("good : " + input_char);
CtoC.combo++;
battle_system.unit_attack(unit_management.your_baddy, unit_management.enemy);
}else{
console.log("boo :");
typing_mondai.show_mondai();
sounds.system.playSound(1);
CtoC.combo = 0;
}
return true_or_faulse;
},
push_Enter : function(){
console.log("Enter Key が押されました");
},
push_Escape : function(){
console.log("Escape Key が押されました");
CtoC.finish_game();
},
trans_specialchar : function(kc){
var key;
if(kc === 189){//ハイフン
kc = 45;
console.log("-");
}else if(kc === 190){//ドット
kc = 46;
console.log(".");
}
key = String.fromCharCode(kc);//それ以外全部
return key;
/*
String.fromCharCode(n);
charCodeAt(n));
キーコード調べセット
*/
},
}
<file_sep>/HTML/farm.php
<script type="text/javascript">
var farm = {
'my_baddy' : null
};
var farm_func = {
registration : function(){
if(farm['my_baddy'] === null){
alert("バディを選択してくれ!");
return;
}
var param = {
"baddy" : farm['my_baddy']
};
//ajaxでの送信
$.ajax({
type: "post",
url: "php/farm_registration.php",
data: JSON.stringify(param),
crossDomain: false,
dataType : "jsonp",
scriptCharset: 'utf-8',
}).done(function(data){
alert("オッスオラ悟空、よろしくな!");
PHP_Reception['baddy'] = data;
//$("#sousin").css("display","inline");
}).fail(function(XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
//$("#sousin").css("display","inline");
});
}
}
<?php
session_start();
for($i=0;$i<8;$i++){
if($_SESSION['guide'][$i] == 1){
echo '$(".list_cell").eq('.$i.').append("<img src=\'../image/monster/'.$i.'.png\' />");';
echo '$(".list_cell").eq('.$i.').click(function(){
$("#pv_name").text(baddy_db['.$i.'][\'name\']);
$("#pv_hp").text(baddy_db['.$i.'][\'hp\']);
$("#pv_str").text(baddy_db['.$i.'][\'atk\']);
$("#pv_dex").text(baddy_db['.$i.'][\'dex\']);
$("#pv_image img").attr("src", "../image/monster/'.$i.'.png");
farm[\'my_baddy\'] = '.$i.';
});';
}
}
?>
</script>
<style>
#baddy_list {
float : left;
width : 70%;
background-color : red;
}
#baddy_info {
float : left;
width : 30%;
background-color : white;
}
.table_list {
}
.table_list tr {
heiht : 100%;
background-color: white;
}
.list_cell {
width : 100px;
}
.baddy_state img {
float : left;
}
.baddy_state span {
clear : left;
}
#regist_button {
width : 30%;
height : 50px;
}
</style>
<div id="farm_wrap">
<div id="baddy_list">
<div id="list_head" style="height:65px;">Card List</div>
<TABLE class="table_list" width="100%" border="5px">
<tr align="center" height="100px">
<td class="list_cell"></td>
<td class="list_cell"></td>
<td class="list_cell"></td>
<td class="list_cell"></td>
<td class="list_cell"></td>
</tr>
<tr align="center" height="100px">
<td class="list_cell"></td>
<td class="list_cell"></td>
<td class="list_cell"></td>
<td class="list_cell"></td>
<td class="list_cell"></td>
</tr>
<tr align="center" height="100px">
<td class="list_cell"></td>
<td class="list_cell"></td>
<td class="list_cell"></td>
<td class="list_cell"></td>
<td class="list_cell"></td>
</tr>
<tr align="center" height="100px">
<td class="list_cell">16</td>
<td class="list_cell">17</td>
<td class="list_cell">18</td>
<td class="list_cell">19</td>
<td class="list_cell">20</td>
</tr>
</TABLE>
</div>
<div class="menubar_back3" onclick="load_html('index.html')">←</div>
<!-- ここからバディ情報 -->
<table id="baddy_info" border="3px">
<tr>
<td width="30%">Name</td>
<td id="pv_name" width="70%" align="center">名前</td>
</tr>
<tr>
<td id="pv_image" colspan="2" align="center" height="60px"><img src="../image/icon/heart.png" /></td>
</tr>
<tr>
<td align="center"><img src="../image/icon/heart.png" /></td>
<td id="pv_hp" align="center">HP</td>
</tr>
<tr>
<td align="center"><img src="../image/icon/sword.png" /></td>
<td id="pv_str" align="center">STR</td>
</tr>
<tr>
<td align="center"><img src="../image/icon/feather.png" /></td>
<td id="pv_dex" align="center">DEX</td>
</tr>
<tr>
<td align="center">type</td>
<td id="pv_pse" align="center"></td>
</tr>
<tr>
<td align="center">special</td>
<td id="pv_dex" align="center"></td>
</tr>
</table>
<button id="regist_button" onclick="farm_func.registration();">バディ登録</button>
<!-- ここまでデッキ情報 -->
</div><file_sep>/Javascript/common/audio.js
audio_class = {
audio : null,
init : function(a_src, a_loop){
if(this.audio != null){
console.log("多重演奏を強制敵に終了させました。");
this.audio.pause();
}
console.log("audio initを開始します。");
// Audioオブジェクト作成
this.audio = new Audio("");
// load()直後に再生しないようにautoplayをfalseに設定
if(typeof a_loop !== 'boolean'){
console.log("第二引数が不正です。 typeof: "+typeof a_loop);
}
this.audio.autoplay = false;
// Audioファイルのアドレス指定
this.audio.src = a_src;
//ループ
this.audio.loop = a_loop;
//オーディオのロード
this.audio.load();
},
play : function(){
this.audio.play();
},
//一時停止
pause : function(){
this.audio.pause();
},
seek_src : function(){
var str = this.audio.src;
var trim = str.lastIndexOf('/') + 1;
var output = str.substr(trim);
//console.log(output);
}
}
/*
ブラウザで音源を鳴らすためのAPIをクラス化
メソッド一覧
init() :
*/
function WebAudioAPI(name) {
this.name = name;
root = this;
root.context;
root.dogBarkingBuffer = null;
root.source;
root.gainNode;
root.request;
root.init = function(){
try{
var s = window.AudioContext || window.webkitAudioContext
root.context = new s
//alert("initiarize complete.");
}
catch(e){
alert('Web Audio API is not supported in root browser');
}
}
root.loadSound = function(src, base){
root.request = new XMLHttpRequest(); //この XMLHttpRequestが音楽データを取得するメソッドとなる
//(jQueryの$.ajax()はレスポンスのデータタイプ ArrayBuffer に対応していない)
root.request.open('GET', src, true); //ここに読み込むファイルを記述
root.request.responseType = 'arraybuffer'; //一般的な固定長のバイナリデータのバッファを示すために使われるデータタイプ
// 非同期的にデコード
//request()が読まれた時
//取得した音源をAudioContextを用いてデコードし、AudioBufferNodeを生成する
root.request.onload = function() {
base.context.decodeAudioData(base.request.response, function(buffer) {//decodeAudioDataが完了したらコールバック関数として実行される
base.dogBarkingBuffer = buffer;
type_game_global.state++;
//base.playSound();
}); //コールバック関数の処理:デコード済みのPCMデータbufferを受け取り、AudioBufferとして格納。
}
root.request.send(); //サーバに HTTP リクエストを送信する。送信先の URL、送信方式(GET や POST など)は、open で指定したものになる。データを送信しない時でも必要で、その時は send(null) とする。
//alert("load completed.");
}
root.playSound = function(){
if(!root.context.createGain){
root.context.createGain = root.context.createGainNode;
}
root.gainNode = root.context.createGain();
root.source = root.context.createBufferSource(); // バッファソースの作成
root.source.buffer = root.dogBarkingBuffer; // tell the source which sound to play
root.source.connect(root.gainNode);
//gainnode関係の処理
root.gainNode.connect(root.context.destination);
if (!root.source.start){
root.source.start = root.source.noteOn(0);
}
root.source.start(0);
// play the source now
//source.loopとかもある
}
root.changeVolume = function(va) {
var fraction = parseInt(va) / parseInt(64);
root.gainNode.gain.value = fraction * fraction;
}
root.stop = function() {
//alert("ok");
if(!root.source.stop){
root.source.stop = source.noteOff;
}
root.source.stop(0);
}
/*
URLにアクセスして音源(たとえばoggファイル)を取得する
取得した音源をAudioContextを用いてデコードし、AudioBufferNodeを生成する
AudioContextからAudioBufferSourceNodeを生成し、AudioBufferNodeや再生オプションを設定する
AudioDestinationNodeにAudioBufferSourceNodeを接続し、音楽を出力(nodeOn())する
*/
//AudioContextによりデコード
}
function WebAudioAPI_kai(){
root = this;
root.context;
root.preload_que = new Array();
root.dogBarkingBuffer = new Array(9);
root.source;
root.gainNode;
root.request;
root.count = 0;
root.init = function(){
try{
root.context = window.AudioContext || window.webkitAudioContext
root.request = new XMLHttpRequest(); //この XMLHttpRequestが音楽データを取得するメソッドとなる
//alert("initiarize complete.");
}
catch(e){
alert('Web Audio API is not supported in root browser');
}
}
root.set_sound = function(src){
root.preload_que.push(src);
}
root.loadSound = function(base){
//(jQueryの$.ajax()はレスポンスのデータタイプ ArrayBuffer に対応していない)
root.request.open('GET', root.preload_que[root.count], true); //ここに読み込むファイルを記述
root.request.responseType = 'arraybuffer'; //一般的な固定長のバイナリデータのバッファを示すために使われるデータタイプ
// 非同期的にデコード
//request()が読まれた時
//取得した音源をAudioContextを用いてデコードし、AudioBufferNodeを生成する
root.request.onload = function() {
var audioCtx = new base.context;
audioCtx.decodeAudioData(base.request.response).then(function(buffer) {//decodeAudioDataが完了したらコールバック関数として実行される
base.dogBarkingBuffer[base.count] = buffer;
base.count++;
if(base.count === base.preload_que.length){
type_game_global.initiate_counter++;
}else {
base.loadSound(base);
}
//base.playSound();
}); //コールバック関数の処理:デコード済みのPCMデータbufferを受け取り、AudioBufferとして格納。
}
root.request.send(); //サーバに HTTP リクエストを送信する。送信先の URL、送信方式(GET や POST など)は、open で指定したものになる。データを送信しない時でも必要で、その時は send(null) とする。
//alert("load completed.");
}
root.playSound = function(n){
if(!root.context.createGain){
root.context.createGain = root.context.createGainNode;
}
root.gainNode = root.context.createGain();
root.source = root.context.createBufferSource(); // バッファソースの作成
root.source.buffer = root.dogBarkingBuffer[n]; // tell the source which sound to play
root.source.connect(root.gainNode);
//gainnode関係の処理
root.gainNode.connect(root.context.destination);
if (!root.source.start){
root.source.start = root.source.noteOn(0);
}
root.source.start(0);
// play the source now
//source.loopとかもある
}
root.changeVolume = function(va) {
var fraction = parseInt(va) / parseInt(64);
root.gainNode.gain.value = fraction * fraction;
}
root.stop = function() {
//alert("ok");
if(!root.source.stop){
root.source.stop = source.noteOff;
}
root.source.stop(0);
}
/*
URLにアクセスして音源(たとえばoggファイル)を取得する
取得した音源をAudioContextを用いてデコードし、AudioBufferNodeを生成する
AudioContextからAudioBufferSourceNodeを生成し、AudioBufferNodeや再生オプションを設定する
AudioDestinationNodeにAudioBufferSourceNodeを接続し、音楽を出力(nodeOn())する
*/
//AudioContextによりデコード
}<file_sep>/Javascript/game/dungeon.js
var Dungeon = function(){
this.name;
this.floor = 0;
this.battle = 4;
//エンカウント関係
this.encounting = 0; //現在エンカウント中の敵
this.encount_monster = [
3,4,5,6
];
this.boss = 7;
//キャプチャー関係
this.defeated_monster = new Array();
this.initiate_dungeon = function(){
}
this.main = function(){
console.log("散策中...");
this.floor++;
if(this.floor > this.battle || unit_management.your_baddy.alive === 0){
this.capture();
}else{
type_game_global.state_flg = 0;
//イベントの発生
this.enemy_encount();
}
}
this.enemy_encount = function(){
if(this.floor === this.battle){
//Boss
this.encounting = this.boss;
}else{
//通常
console.log("aa"+this.encount_monster.length);
var rnd = Math.floor(Math.random() * (this.encount_monster.length));
this.encounting = this.encount_monster[rnd];
}
initiate_state();
}
this.capture = function(){
var rnd = Math.floor(Math.random() * this.defeated_monster.length);
if(this.defeated_monster[rnd] === null){
load_html("gacha.html");
}else{
var param = {
"get" : this.defeated_monster[rnd]
};
console.log("******"+param['get']);
//ajaxでの送信
$.ajax({
type: "post",
url: "../HTML/php/getmonster.php",
data: JSON.stringify(param),
crossDomain: false,
dataType : "jsonp",
scriptCharset: 'utf-8',
}).done(function(data){
PHP_Reception['guide'][data['get']] = 1;
load_html("../HTML/gacha.php");
}).fail(function(XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
});
}
}
}
<file_sep>/HTML/toppage.php
<?php
session_start();
if(!isset($_SESSION['baddy']) ){
//初ログインなら
$_SESSION['id'] = 'null';
$_SESSION['baddy'] = 'null';
for($i=0;$i<8;$i++){
$_SESSION['guide'][$i] = 0;
}
}
?>
<!DOCTYPE html>
<!-- saved from url=(0048)file://localhost/Users/Shun/Downloads/index.html -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>バディバトラー</title>
<link rel="styleSheet" type="text/css" href="../css/typing.css">
<!-- プラグイン -->
<script type="text/javascript" src="../Javascript/jquery.min.js"></script>
<!-- メニュー画面関連 -->
<script type="text/javascript" src="../Javascript/top_menue.js"></script>
<!-- 汎用関数 -->
<script type="text/javascript" src="../Javascript/common/storage.js"></script>
<script type="text/javascript" src="../Javascript/common/audio.js"></script>
<script type="text/javascript" src="../Javascript/common/load_images_kai.js"></script>
<!-- その他 -->
<script type="text/javascript" src="../Javascript/studymode.js"></script>
<!-- 各種データ -->
<script type="text/javascript" src="../Javascript/data/mondai.js"></script>
<script type="text/javascript" src="../Javascript/data/baddy_data.js"></script>
<script type="text/javascript" src="../Javascript/data/enemy_data.js"></script>
<script type="text/javascript" src="../Javascript/data/skill_data.js"></script>
<script type="text/javascript">
PHP_Reception = {
'id' : <?php echo '"'+$_SESSION['id']+'"'; ?>,
'baddy' : <?php echo $_SESSION['baddy'] ?>,
'guide' : {
0 : <?php echo $_SESSION['guide'][0] ?>,
1 : <?php echo $_SESSION['guide'][1] ?>,
2 : <?php echo $_SESSION['guide'][2] ?>,
3 : <?php echo $_SESSION['guide'][3] ?>,
4 : <?php echo $_SESSION['guide'][4] ?>,
5 : <?php echo $_SESSION['guide'][5] ?>,
6 : <?php echo $_SESSION['guide'][6] ?>,
7 : <?php echo $_SESSION['guide'][7] ?>
}
}
audio_class.init("../sound/menu.mp3", true);
function page_transfer(){
if(PHP_Reception['baddy'] === null){
load_html('firstlogin.html');
}else {
load_html('index.html');
}
}
</script>
</head>
<body onload="page_transfer()" style="overflow: hidden; background-color:#000000">
<!-- ここからゲーム画面要素 ゲーム画面 -->
<div id="gameframe">
<div id="menulist"></div>
<canvas id="MyMonster" style="position: absolute;left: 550px;top: 150px; width: 500px; height: 300px;">
</canvas>
</div>
</body>
</html><file_sep>/Javascript/game/baddyfight.js
var battle_unit = function(){
this.unit_type;
this.name;
this.image_loader; //ここに全画像含む画像処理のクラスがはいる
this.image; //現在表示中のスプライトの番号
this.src_que;
this.hp;
this.atk;
this.spd;
this.alive;
this.take_damage = function(damage){
this.hp -= damage;
}
}
var Enemy = function(number){
battle_unit.call(this);
this.prototype = new battle_unit();
//Enemy固有ステータス
this.attack_frequency;
this.skill;
this.attack
//this.attack_loop;
//基礎ステータスの設定
this.unit_type = "enemy";
this.id = baddy_db[number]['id'];
this.name = baddy_db[number]['name'];
this.hp = baddy_db[number]['hp'];
this.atk = baddy_db[number]['atk'];
this.dex = baddy_db[number]['dex'];
this.alive = 1;
this.src = number;
this.attack = function(myself, target){
console.log("敵の攻撃!");
battle_system.unit_attack(myself, target);
var next_attack = 5000 - this.dex * 40;
if(type_game_global.state_flg === 1){
EnemyAttack = setTimeout(function(){myself.attack(myself, target)}, next_attack);
}else if(type_game_global.state_flg === 0){
}
}
}
var Baddy = function(number){
battle_unit.call(this);
this.prototype = new battle_unit();
//基礎ステータスの設定
this.unit_type = "baddy";
this.name = baddy_db[number]['name'];
this.hp = baddy_db[number]['hp'];
this.atk = baddy_db[number]['atk'];
this.dex = baddy_db[number]['dex'];
this.qtype = baddy_db[number]['type'];
this.mode = baddy_db[number]['mode'];
this.alive = 1;
//this.display_neutral();
this.src= number;
}
var skill_translater = function(owner, num, sequence){
switch(num){
case 0:
owner.combo_bonus_skill[sequence] = new skill_burnning();
break;
case 1:
owner.combo_bonus_skill[sequence] = new skill_icestorm();
break;
default:
owner.combo_bonus_skill[sequence] = new skill_none();
break;
}
}
<file_sep>/HTML/php/farm_registration.php
<?php
session_start();
header('Content-Type: application/javascript; charset=utf-8');
$json = file_get_contents('php://input'); //読み込み用ストリーム
$data = json_decode($json, true);
$baddy = $data['baddy'];
$_SESSION['baddy'] = $baddy;
$callback = isset($_GET['callback']) ? $_GET["callback"] : "";
$callback = htmlspecialchars(strip_tags($callback));
printf("{$callback}(%s)", json_encode( $_SESSION['baddy'] ));
?><file_sep>/Javascript/補欠/typing_game.js
// ゲーム画面のスクリプト
/*
include : Javascript/game/load_images.js
include : Javascript/mondai.js
*/
/* ゲームモード読み込み時のコールバック。ゲーム全体での初期化を行う。 */
var typingcallback = function(){
//問題の設定
if(localStorage.length < 1){
console.log("*初回通信を開始します。");
mondai_class.putmondai();
}else{
console.log("*通信処理を無視します。");
}
mondai_class.getmondai();
//ゲームモードを開始にする
CtoC.game_state = 1;
//音楽を設定
audio_class.init("../sound/normal.mp3", true);
//ユニットの設定
unit_management.create_baddy();
unit_management.create_enemy();
//攻撃開始
unit_management.enemy.attack(unit_management.enemy, unit_management.your_baddy);
//GUIの初期化を行う
GUI.common_initiate();
GUI.main();
//文字の入力判定の設定
CtoC.initiate_section();
window.document.addEventListener("keydown", function(e){
if(CtoC.game_state === 1){
CtoC.check_keycode(e);
}else if(CtoC.game_state === 0){
//onleydownイベントの解除
window.document.removeEventListener("keydown", arguments.callee, false);
}
}, false);
/*
window.document.onkeydown = function(e){
CtoC.check_keycode(e);
}
*/
}
/* 今出題されている問題を格納 */
var typing_mondai = {
mean : null, //コマンドの意味
command : null, //シスココマンド
now_typing : "", //現在打ち込み終わった文
set_mondai : function(mean, command){
this.mean = mean;
this.command = command.toUpperCase();
this.now_typing = "";
},
show_mondai : function(){
console.log(this.mean);
console.log(this.command);
}
}
var CtoC = {
game_state : 0, //0 -> 停止 ; 1 -> バトル中 ;
quiznumber : 0,
kikikan : 0,
combo : 0,
initiate_section : function(){
//ランダムに問題を生成。
var rnd = Math.floor(Math.random() * mondai_class.mondai.length) - 1; //末尾はNullなので外しておく
typing_mondai.set_mondai(mondai_class.mondai[rnd]['meaning'], mondai_class.mondai[rnd]['command']);
//unit_management.your_baddy.combo_bonus();
},
check_keycode : function(evt){
console.log(evt.keyCode+"Key が押されました");
var kc = evt.keyCode;
if (kc == 27) {//エスケープキーが押された
CtoC.push_Escape();
}else{
CtoC.next_char(evt,kc);
}
},
push_Enter : function(){
console.log("Enter Key が押されました");
},
push_Escape : function(){
console.log("Escape Key が押されました");
CtoC.finish_game();
},
trans_specialchar : function(kc){
var key;
if(kc === 189){//ハイフン
kc = 45;
console.log("-");
}else if(kc === 190){//ドット
kc = 46;
console.log(".");
}
key = String.fromCharCode(kc);//それ以外全部
return key;
/*
String.fromCharCode(n);
charCodeAt(n));
キーコード調べセット
*/
},
next_char : function(evt,kc){
var tf;
var chr = CtoC.trans_specialchar(kc);
//入力文字の正誤判定
tf = CtoC.check_correspond(chr, typing_mondai.now_typing.length, typing_mondai.command.length);
//この問題をクリアしたか判定(全文字入力済み)
if(typing_mondai.command.length <= typing_mondai.now_typing.length){
console.log("Go Next Q.");
CtoC.initiate_section();
}
//alert(typing_mondai.command.length+"/"+typing_mondai.now_typing.length);
},
check_correspond : function(input_char, num, length){
var tf = 0;
var target_char = typing_mondai.command.charAt(num).toUpperCase();
//alert(input_char+"/"+target_char);
if(input_char === target_char){
tf = 1;
typing_mondai.now_typing += input_char;
console.log("good : " + input_char);
CtoC.combo++;
//@
battle_system.unit_attack(unit_management.your_baddy, unit_management.enemy);
}else{
console.log("boo : " + typing_mondai.now_typing);
CtoC.combo = 0;
}
return tf;
},
//ゲーム終了処理
finish_game : function(){
//蛍の光
audio_class.init("../sound/gameover.mp3", false);
//ゲームステートの変更
CtoC.game_state = 0; //ゲームステートを終了に
if(unit_management.your_baddy.hp <= 0 && unit_management.enemy.hp <= 0){
//引き分け
unit_management.your_baddy.hp = 0;
unit_management.enemy.hp = 0;
alert("引き分け");
}else if(unit_management.enemy.hp <= 0){
//勝ち
unit_management.enemy.hp = 0;
alert("勝ち");
}else {
//負け
unit_management.your_baddy.hp = 0;
alert("負け");
}
}
}
var GUI = {
image_canvas : null,
image_context : null,
string_canvas : null,
string_context : null,
//Imageオブジェクト
baddy : null,
enemy : null,
type_bar : null,
background : null,
//描画クラス
Draw_image : null,
//ゲームのメインループ GUI部分 システム監視
main : function(){
/* GUI部分 */
//領域の初期化
GUI.image_context.clearRect(0, 0, image_layer.width, image_layer.height);
GUI.string_context.clearRect(0, 0, image_layer.width, image_layer.height);
//描画処理
GUI.display_baddy_status();
GUI.display_enemy_status();
GUI.display_basis_images();
GUI.display_mondai_sentences();
/* システム監視 */
//勝敗判定
if(unit_management.your_baddy.hp <= 0 || unit_management.enemy.hp <= 0){
CtoC.finish_game();
}else {
//再呼び出し
setTimeout("GUI.main()", 18);
}
},
preload_image : function(src){
},
common_initiate : function(){
GUI.image_canvas = document.getElementById("image_layer");
GUI.image_context = GUI.image_canvas.getContext("2d");
GUI.string_canvas = document.getElementById("string_layer");
GUI.string_context = GUI.string_canvas.getContext("2d");
//unit_management.baddy.image = new Image();
GUI.enemy = new Image();
GUI.type_bar = new Image();
GUI.Draw_image = new load_images(2);
GUI.Draw_image.set_image(GUI.type_bar, "../image/frame01.png", 100, 200);
GUI.Draw_image.set_image(GUI.enemy, unit_management.enemy.image, 25, 25);
//GUI.Draw_image.set_image(unit_management.your_baddy.image, unit_management.your_baddy.image_src, 250, 25);
GUI.Draw_image.carryout(GUI.Draw_image);
},
add_damage_effect : function(){
//ダメージ発生時の処理
/*
var damage_que = new Array();
damage_que.push();
GUI.display_damage();
*/
},
display_damage : function(damage_obj){
//ダメージ継続(setTimeout)
/*
GUI.string_context.font = "14px 'MS Pゴシック'";
GUI.string_context.fillStyle = "black";
for(var i=0;i<damage_que.length;i++){
GUI.string_context.fillText(damage_obj.value, 200, damage_obj.y); //ここで座標(カウント)を持っているオブジェクトを渡す
}
setTimeout(myself);
*/
},
display_basis_images : function(){
GUI.Draw_image.display();
},
display_mondai_sentences : function(){
GUI.string_context.font = "28px 'MS Pゴシック'";
GUI.string_context.fillStyle = "blue";
GUI.string_context.fillText(typing_mondai.command, 200, 350);
GUI.string_context.font = "28px 'MS Pゴシック'";
GUI.string_context.fillStyle = "black";
GUI.string_context.fillText(typing_mondai.now_typing, 200, 350);
GUI.string_context.font = "25px 'MS Pゴシック'";
GUI.string_context.fillStyle = "red";
GUI.string_context.fillText(typing_mondai.mean, 200, 250);
},
display_enemy_status : function(){
//エネミーのデータの表示
GUI.string_context.font = "25px 'MS Pゴシック'";
GUI.string_context.fillStyle = "black";
GUI.string_context.fillText("Name : " + unit_management.enemy.name, 100, 50);
GUI.string_context.font = "25px 'MS Pゴシック'";
GUI.string_context.fillStyle = "black";
GUI.string_context.fillText("HP : " + unit_management.enemy.hp, 100, 75);
GUI.string_context.font = "25px 'MS Pゴシック'";
GUI.string_context.fillStyle = "black";
GUI.string_context.fillText("ATK : " + unit_management.enemy.atk, 100, 100);
GUI.string_context.font = "25px 'MS Pゴシック'";
GUI.string_context.fillStyle = "black";
GUI.string_context.fillText("SPD : " + unit_management.enemy.spd, 100, 125);
},
display_baddy_status : function(){
GUI.string_context.font = "25px 'MS Pゴシック'";
GUI.string_context.fillStyle = "black";
GUI.string_context.fillText("Name : " + unit_management.your_baddy.name, 400, 50);
GUI.string_context.font = "25px 'MS Pゴシック'";
GUI.string_context.fillStyle = "black";
GUI.string_context.fillText("HP : " + unit_management.your_baddy.hp, 400, 75);
GUI.string_context.font = "25px 'MS Pゴシック'";
GUI.string_context.fillStyle = "black";
GUI.string_context.fillText("ATK : " + unit_management.your_baddy.atk, 400, 100);
GUI.string_context.font = "25px 'MS Pゴシック'";
GUI.string_context.fillStyle = "black";
GUI.string_context.fillText("SPD : " + unit_management.your_baddy.spd, 400, 125);
GUI.string_context.font = "25px 'MS Pゴシック'";
GUI.string_context.fillStyle = "red";
GUI.string_context.fillText(CtoC.combo + " COMBO", 670, 50);
},
you_win : function(){
},
you_lose : function(){
}
}
var unit_management = {
your_baddy : null,
enemy : null,
create_baddy : function(){
this.your_baddy = new Baddy();
this.your_baddy.summon_piyomaru();
},
create_enemy : function(){
this.enemy = new Enemy();
this.enemy.summon_Qcon();
},
save_baddy_session : function(){
}
}
/*戦闘システム
キーを打ったら攻撃 ->
ダメージ計算 -> 自分ATK/10
命中率 -> 自分SPD/(相手SPD*2)
その他
ノーミスボーナス
コンボ補正
*/
var battle_system = {
hit_judge : function(your_spd, enemy_spd){
var hit_flg = 0;
var hit_probability = your_spd / (enemy_spd * 2) * 100;
var rnd = Math.floor(Math.random() * 100);
//alert("確率:"+hit_probability+"<br>数値:"+rnd);
if(hit_probability > rnd){
hit_flg = 1;
}
return hit_flg;
},
damage_calculate : function(basis_atk){
var damage = (basis_atk / 10); //ダメージ計算式
return damage;
},
unit_attack : function(attacker, target){
var hit = battle_system.hit_judge(attacker.spd, target.spd);
if(hit === 1){
var damage = battle_system.damage_calculate(attacker.atk);
target.take_damage(damage);
//console.log(target.hp);
}
}
}
|
c8b6701062e622081b271e157ae940e061f06a2f
|
[
"JavaScript",
"PHP"
] | 19
|
PHP
|
shiv3/CiscoTyping
|
549d2584abe428ea2c6bccfcada35c504c9f324d
|
82700c9903530a6b64af1743c5822eb4eb7b7b0b
|
refs/heads/master
|
<file_sep>/*
MIT License
Copyright (c) 2017 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package codegenfw
// Returns true if the word is reserved.
type WordFilter func(s string) bool
func hasPrefix(a,p string) bool {
la,lp := len(a),len(p)
if la<lp { return false }
return a[:lp]==p
}
func WF_ANSI_C(s string) bool {
switch s {
case "auto","break","case","char","const","continue","default","do","double","else",
"enum","extern","float","for","goto","if","int","long","register","return","short","signed","sizeof","static",
"struct","switch","typedef","union","unsigned","void","volatile","while": return true
}
return false
}
// WF_ANSI_C + asm typeof inline
func WF_ModernC(s string) bool {
switch s {
case "auto","break","case","char","const","continue","default","do","double","else",
"enum","extern","float","for","goto","if","int","long","register","return","short","signed","sizeof","static",
"struct","switch","typedef","union","unsigned","void","volatile","while":
return true
case "asm","typeof","inline":
return true
}
return false
}
// This is a very Picky keyword filter, trying to cut off all GCC keywords.
func WF_GccC(s string) bool {
switch s {
case "auto","break","case","char","const","continue","default","do","double","else",
"enum","extern","float","for","goto","if","int","long","register","return","short","signed","sizeof","static",
"struct","switch","typedef","union","unsigned","void","volatile","while":
return true
case "asm","typeof","inline":
return true
case "__attribute__","__complex__", "__declspec","__ea","__extension__","__far","__imag__","__real__","__memx",
"__thread","__func__","__asm__":
return true
case "__FUNCTION__","__PRETTY_FUNCTION__","__STDC_HOSTED__":
return true
case "__FILE__","__LINE__": return true
}
ls := len(s)
if ls>=2 {
if s[0]=='_' {
m := s[1]
if (m>='A') && (m<='Z') { /* exclude "_" + UpperCaseChar */ return true }
switch m {
// restrict _exit, _xabort, _xbegin, _xend, _xtest
case 'e','x': return true
}
}
}
if ls>=3 {
if s[:2]=="__" {
m := s[2]
//if (m>='A') && (m<='Z') { /* exclude "__" + UpperCaseChar */ return true }
if (m!='_') && ((m<'0')||(m>'9')) {
n := s[2:] // get rid of the "__"-prefix!
if hasPrefix(n,"atomic") { return true }
if hasPrefix(n,"builtin") { return true }
if hasPrefix(n,"sync") { return true }
if hasPrefix(n,"flash") { return true }
if hasPrefix(n,"float") { return true }
if hasPrefix(n,"fp") { return true }
if hasPrefix(n,"int") { return true }
}
}
}
return false
}
<file_sep># Code Generation Library (to generate C code)
Not usable yet......
```go
package main
import "os"
import "io"
import "fmt"
import "github.com/byte-mug/codegenfw"
func out(w io.Writer) {
blk := new(codegenfw.Block)
blk.Childs.Init()
{
blk.Childs.PushBack(codegenfw.Declare("int","a"))
blk.Childs.PushBack(codegenfw.NewLiteral("a","7"))
blk.Childs.PushBack(codegenfw.TouchVariable("a"))
blk.Childs.PushBack(codegenfw.NewLiteral(1,`"Let's begin!"`))
blk.Childs.PushBack(codegenfw.NewCall("printf(%s)",nil,1))
blk.Childs.PushBack(codegenfw.Label("restart"))
doif := codegenfw.CS_If_Then_Else("a")
// if-then-else
blk.Childs.PushBack(doif)
doif.Childs.PushBack(codegenfw.NewLiteral(1,`"Hello!"`))
doif.Childs.PushBack(codegenfw.NewExpr("printf(%s)",0,nil,1))
doelse := doif.EBlock
doelse.Childs.PushBack(codegenfw.NewLiteral(2,`"Again!"`))
doelse.Childs.PushBack(codegenfw.NewCall("printf(%s)",nil,2))
doelse.Childs.PushBack(codegenfw.NewLiteral(3,`1`))
doelse.Childs.PushBack(codegenfw.NewOp("(%s-%s)","a","a",3))
doelse.Childs.PushBack(codegenfw.GoTo("restart"))
/*
Let's do:
a = 1
a = a+1
a = a+1
a = a+1
a = a+1
prinft("a = %d",a);
*/
blk.Childs.PushBack(codegenfw.NewLiteral("a","1")) // a = 1
blk.Childs.PushBack(codegenfw.NewLiteral(4,`1`)) // $4 = 1
blk.Childs.PushBack(codegenfw.NewLiteral(5,`"a = %d"`)) // $5 = "..."
blk.Childs.PushBack(codegenfw.NewOp("(%s+%s)","a","a",4)) //a = a+$4
blk.Childs.PushBack(codegenfw.NewOp("(%s+%s)","a","a",4)) //a = a+$4
blk.Childs.PushBack(codegenfw.NewOp("(%s+%s)","a","a",4)) //a = a+$4
blk.Childs.PushBack(codegenfw.NewOp("(%s+%s)","a","a",4)) //a = a+$4
blk.Childs.PushBack(codegenfw.NewCall("printf(%s,%s)",nil,5,"a")) // printf(%5,a)
}
fmt.Fprintln(w,"#include","<stdio.h>")
fmt.Fprintln(w)
fmt.Fprintln(w,"void main(){")
{
gen := &codegenfw.Generator{Dest:w,Indent:"\t"}
gen.Block(blk,codegenfw.GA_COUNT)
gen.Block(blk,codegenfw.GA_GENERATE)
}
fmt.Fprintln(w,"}")
fmt.Fprintln(w)
fmt.Fprintln(w)
}
func main() {
f,e := os.Create("program.c")
if e!=nil { fmt.Println(e); return }
defer f.Close()
out(f)
}
```
Results in...
```c
#include <stdio.h>
void main(){
int a ;
a = 7;
printf("Let's begin!") ;
restart:
if(a){
printf("Hello!") ;
}else{
printf("Again!") ;
a = (a-1) ;
goto restart;
}
printf("a = %d",((((1+1)+1)+1)+1)) ;
}
```
<file_sep>/*
MIT License
Copyright (c) 2017 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package codegenfw
import "math/rand"
import "fmt"
// Returns true if the word is reserved.
//type WordFilter func(s string) bool
/*
Creates a Name-Changing function, that replaces reserved identifiers (as specified
trough 'wf') such as keywords with new names.
*/
func GetNameChanger(wf WordFilter) (func(string)string) {
tl := make(map[string]string)
am := make(map[string]bool)
gen := rand.NewSource(12345)
return func(o string) (string) {
if t,ok := tl[o]; ok { return t }
if a,ok := am[o]; !(a&&ok) {
if !wf(o) { return o } /* return unchanged */
}
for {
s := fmt.Sprintf("___temp_%v",gen.Int63())
if a,ok := am[s]; a&&ok { continue } /* FAIL! Next! */
tl[o] = s
return s
}
}
}
<file_sep>/*
MIT License
Copyright (c) 2017 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package codegenfw
import "container/list"
type EFlags uint
func (e EFlags) Has(i EFlags) bool { return (e&i)==i }
const (
E_HAS_DEST = EFlags(1<<iota)
E_CHEAP
E_LITERAL
E_NO_OMIT
E_TIME_CRITICAL // time critical instructions must not be reordered.
)
const eflags_and = E_CHEAP|E_LITERAL
func efjoin(o,a EFlags) EFlags {
return (o & ^eflags_and)|(a & eflags_and)
}
type ExprRef struct{
Name string
Num uint
}
func (e ExprRef) SSA() bool { return len(e.Name)==0 }
func NewExprRef(i interface{}) ExprRef {
switch v := i.(type) {
case string: return ExprRef{v,0}
case uint: return ExprRef{"",v}
case int: return ExprRef{"",uint(v)}
}
panic("illegal value")
}
type ExprRefMap struct{
names map[string]interface{}
nums map[uint]interface{}
}
func (e *ExprRefMap) Update(k ExprRef, f func(interface{},bool) (interface{},bool)) (interface{},bool) {
if len(k.Name)==0 {
if e.nums==nil { e.nums = make(map[uint]interface{}) }
i,ok := e.nums[k.Num]
i,ok = f(i,ok)
if ok { e.nums[k.Num] = i }
return i,ok
}
if e.names==nil { e.names = make(map[string]interface{}) }
i,ok := e.names[k.Name]
i,ok = f(i,ok)
if ok { e.names[k.Name] = i }
return i,ok
}
func (e *ExprRefMap) Delete(k ExprRef) {
if len(k.Name)==0 {
if e.nums==nil { return }
delete(e.nums,k.Num)
}
if e.names==nil { return }
delete(e.names,k.Name)
}
func (e *ExprRefMap) Iterate(f func(k ExprRef,v interface{})) {
if e.nums!=nil {
for n,v := range e.nums { f(ExprRef{"",n},v) }
}
if e.names!=nil {
for n,v := range e.names { f(ExprRef{n,0},v) }
}
}
func Noop(i interface{},ok bool) (interface{},bool) { return i,ok }
func Incr(i interface{},ok bool) (interface{},bool) {
n := 0
if ok {
if m,ok := i.(int); ok { n = m }
}
n++
if n<=0 { return nil,false }
return n,true
}
func Decr(i interface{},ok bool) (interface{},bool) {
n := 0
if ok {
if m,ok := i.(int); ok { n = m }
}
if n<=0 { return nil,false }
n--
return n,true
}
func Put(i interface{}) (func(i interface{},ok bool) (interface{},bool)) {
return func(interface{},bool) (interface{},bool) { return i,true }
}
type Expr struct{
Dest ExprRef
Src []ExprRef
Fmt string
Flags EFlags
}
func NewExpr(fmt string,f EFlags,dst interface{}, src ...interface{}) (result *Expr) {
result = new(Expr)
result.Fmt = fmt
result.Flags = f
if dst!=nil {
result.Flags |= E_HAS_DEST
result.Dest = NewExprRef(dst)
} else { result.Flags &= ^E_HAS_DEST }
if l := len(src); l>0 {
result.Src = make([]ExprRef,l)
for i,srci := range src { result.Src[i] = NewExprRef(srci) }
}
return
}
// New Operation (eg. Flags = E_CHEAP)
func NewOp(fmt string,dst interface{}, src ...interface{}) (result *Expr) {
return NewExpr(fmt,E_CHEAP,dst,src...)
}
// New Expression that is a call (eg. Flags = E_TIME_CRITICAL)
func NewCall(fmt string,dst interface{}, src ...interface{}) (result *Expr) {
return NewExpr(fmt,E_TIME_CRITICAL,dst,src...)
}
// New Expression with side effect. (eg. Flags = E_NO_OMIT)
func NewSE(fmt string,dst interface{}, src ...interface{}) (result *Expr) {
return NewExpr(fmt,E_NO_OMIT,dst,src...)
}
func NewLiteral(dst interface{},val string) *Expr {
return &Expr{NewExprRef(dst),nil,val,E_HAS_DEST|E_LITERAL|E_CHEAP}
}
type Block struct{
Childs list.List
}
type ControlStruct struct{
Block
Fmt string
Src []ExprRef
Fmt2 string
Src2 []ExprRef
// The "else"-block. This is called "else" block because
// it is only useful when "if-then-else" is used.
EBlock *Block
}
func CS_If_Then_Else(cond interface{}) *ControlStruct {
c := new(ControlStruct)
c.Childs.Init()
c.EBlock = new(Block)
c.EBlock.Childs.Init()
c.Fmt = "if(%s)"
c.Fmt2 = "else"
c.Src = []ExprRef{NewExprRef(cond)}
return c
}
func ControlStruct1(fmt string,src ...interface{}) *ControlStruct {
return ControlStruct3(fmt,src,"",nil)
}
func ControlStruct2(fmt string,src ...interface{}) *ControlStruct {
return ControlStruct3("",nil,fmt,src)
}
func ControlStruct3(fmt string,src []interface{},fmt2 string,src2 []interface{}) *ControlStruct {
c := new(ControlStruct)
c.Childs.Init()
c.Fmt = fmt
c.Fmt2 = fmt2
if l := len(src); l>0 {
c.Src = make([]ExprRef,l)
for i,srci := range src { c.Src[i] = NewExprRef(srci) }
}
if l := len(src2); l>0 {
c.Src2 = make([]ExprRef,l)
for i,srci := range src2 { c.Src2[i] = NewExprRef(srci) }
}
return c
}
type Label string
type GoTo string
type EnforceStore string
type TouchVariable string
type Declaration struct{
DataType string
Names []string
}
func Declare(t string, names ...string) *Declaration { return &Declaration{t,names} }
type SetVolatile struct{
Variable string
Volatile bool
}
<file_sep>/*
MIT License
Copyright (c) 2017 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package codegenfw
import (
"io"
"fmt"
//"bytes"
)
//import "container/list"
type GenAction uint
const (
GA_COUNT = GenAction(iota)
GA_GENERATE
)
const (
curlo = "{"
curlc = "}"
)
type GenFlags uint
func (a GenFlags) Has(b GenFlags) bool { return (a&b)==b }
const (
GF_ENFORCE_STORE = GenFlags(1<<iota)
)
func revcnt_incr(i interface{},ok bool) (interface{},bool) {
if !ok { i = []int{0} }
arr,ok := i.([]int)
if len(arr)==0 { arr = []int{0} }
arr[len(arr)-1]++
return arr,true
}
func revcnt_decr(i interface{},ok bool) (interface{},bool) {
if !ok { i = []int{0} }
arr,ok := i.([]int)
if len(arr)==0 { arr = []int{0} }
arr[len(arr)-1]--
return arr,true
}
func revcnt_incr_first(i interface{},ok bool) (interface{},bool) {
if !ok { i = []int{0} }
arr,ok := i.([]int)
if len(arr)==0 { arr = []int{0} }
arr[0]++
return arr,true
}
func revcnt_decr_first(i interface{},ok bool) (interface{},bool) {
if !ok { i = []int{0} }
arr,ok := i.([]int)
if len(arr)==0 { arr = []int{0} }
arr[0]--
return arr,true
}
func revcnt_newrev(i interface{},ok bool) (interface{},bool) {
if !ok { i = []int{0} }
if !ok { return []int{0,0},true}
arr,ok := i.([]int)
if !ok { return []int{0,0},true}
if len(arr)==0 { return []int{0,0},true}
arr = append(arr,0)
return arr,true
}
func revcnt_pullrev(i interface{},ok bool) (interface{},bool) {
if !ok { i = []int{0} }
arr,ok := i.([]int)
if len(arr)!=0 { arr = arr[1:] }
return arr,true
}
func revcnt_count_first(i interface{},ok bool) int {
if !ok { return 0 }
n,ok := i.([]int)
if !ok { return 0 }
if len(n)==0 { return 0 }
return n[0]
}
func eflags_cast(i interface{},ok bool) EFlags {
j,ok2 := i.(EFlags)
if ok&&ok2 { return j }
return 0
}
func bool_cast(i interface{},ok bool) bool {
j,ok2 := i.(bool)
return ok && ok2 && j
}
func (e EFlags) set(i interface{},ok bool) (interface{},bool) {
return (e|eflags_cast(i,ok)),true
}
func (e EFlags) clear(i interface{},ok bool) (interface{},bool) {
return (eflags_cast(i,ok)&^e),true
}
type Generator struct{
Dest io.Writer
Indent string
Flags GenFlags
revcnt,tree,eflags,volm ExprRefMap
ind string
}
func (g *Generator) pushind() func() {
o := g.ind
g.ind = o+g.Indent
return func(){ g.ind = o }
}
func (g *Generator) Sync(ga GenAction) {
if ga==GA_GENERATE {
kl := []ExprRef{}
g.tree.Iterate(func(k ExprRef,v interface{}){
if k.SSA() { return }
fmt.Fprintf(g.Dest,"%s%s = %s ;\n",g.ind,k.Name,v)
kl = append(kl,k)
})
for _,k := range kl { g.tree.Delete(k) }
}
}
func (g *Generator) vec(src []ExprRef,ga GenAction) ([]interface{},EFlags,EFlags) {
switch ga {
case GA_COUNT:
for _,r := range src {
g.revcnt.Update(r,revcnt_incr)
}
case GA_GENERATE:
vec := make([]interface{},len(src))
aflags := ^EFlags(0)
oflags := EFlags(0)
for i,r := range src {
if t,ok := g.tree.Update(r,Noop); ok {
vec[i] = t
temp1 := eflags_cast(g.eflags.Update(r,Noop))
oflags |= temp1
aflags &= temp1
} else if r.SSA() {
panic(fmt.Sprint("no such value: ",r))
} else {
vec[i] = r.Name
}
cnt := revcnt_count_first(g.revcnt.Update(r,revcnt_decr_first))
if cnt<1 {
g.tree.Delete(r)
g.eflags.Delete(r)
}
}
return vec,oflags,aflags
}
return nil,0,0
}
func (g *Generator) Expr(e *Expr,ga GenAction) {
vec,oflags,aflags := g.vec(e.Src,ga)
oflags |= e.Flags
aflags &= e.Flags
switch ga {
case GA_COUNT:
if e.Flags.Has(E_HAS_DEST) {
g.revcnt.Update(e.Dest,revcnt_newrev)
}
case GA_GENERATE:
subtree := e.Fmt
if e.Flags.Has(E_LITERAL) {
if len(vec)>0 { panic("Literals must not have operands") }
} else {
subtree = fmt.Sprintf(e.Fmt,vec...)
}
if e.Flags.Has(E_HAS_DEST) {
cnt := revcnt_count_first(g.revcnt.Update(e.Dest,revcnt_pullrev))
nflags := efjoin(oflags,aflags)
// Whether Store is required or not.
require_store := g.Flags.Has(GF_ENFORCE_STORE)||
// Time-Critical instructions must be evaluated immediately.
nflags.Has(E_TIME_CRITICAL)||
// if the destination variable is volatile, store is required
bool_cast(g.volm.Update(e.Dest,Noop))
// wether the code must be evaluated or not.
must_evaluate := nflags.Has(E_NO_OMIT)||
nflags.Has(E_TIME_CRITICAL)
if require_store && !e.Dest.SSA() {
fmt.Fprintf(g.Dest,"%s%s = %s ;\n",g.ind,e.Dest.Name,subtree)
} else if cnt==1 {
g.tree.Update(e.Dest,Put(subtree))
g.eflags.Update(e.Dest,Put(nflags))
} else if nflags.Has(E_CHEAP) {
g.tree.Update(e.Dest,Put(subtree))
g.eflags.Update(e.Dest,Put(nflags))
} else if e.Dest.SSA() {
if cnt==0 { // oops... the code doesn't consume the value.
// In this case, the code must be evaluated.
if must_evaluate {
fmt.Fprintf(g.Dest,"%s%s ;\n",g.ind,subtree)
}
}
panic("When SSA, value count must be 1")
} else {
fmt.Fprintf(g.Dest,"%s%s = %s ;\n",g.ind,e.Dest.Name,subtree)
}
} else {
fmt.Fprintf(g.Dest,"%s%s ;\n",g.ind,subtree)
}
}
}
func (g *Generator) Block(b *Block,ga GenAction) {
defer g.pushind()()
for e := b.Childs.Front(); e!=nil; e = e.Next() {
if x,ok := e.Value.(*Expr); ok {
g.Expr(x,ga)
}
if x,ok := e.Value.(*Block); ok {
g.Sync(ga)
if ga == GA_GENERATE {
fmt.Fprintf(g.Dest,"%s%s\n",g.ind,curlo)
}
g.Block(x,ga)
if ga == GA_GENERATE {
fmt.Fprintf(g.Dest,"%s%s\n",g.ind,curlc)
}
}
if x,ok := e.Value.(*ControlStruct); ok {
g.Sync(ga)
vec,_,_ := g.vec(x.Src,ga)
if ga == GA_GENERATE {
fmt.Fprintf(g.Dest,"%s",g.ind)
fmt.Fprintf(g.Dest,x.Fmt,vec...)
fmt.Fprintln(g.Dest,curlo)
}
g.Block(&x.Block,ga)
vec,_,_ = g.vec(x.Src2,ga)
if ga == GA_GENERATE {
fmt.Fprintf(g.Dest,"%s%s",g.ind,curlc)
fmt.Fprintf(g.Dest,x.Fmt2,vec...)
if x.EBlock!=nil {
fmt.Fprintln(g.Dest,curlo)
}else{
fmt.Fprintln(g.Dest)
}
}
if x.EBlock!=nil {
g.Block(x.EBlock,ga)
if ga == GA_GENERATE {
fmt.Fprintf(g.Dest,"%s%s",g.ind,curlc)
fmt.Fprintln(g.Dest)
}
}
}
if x,ok := e.Value.(Label); ok {
g.Sync(ga)
if ga == GA_GENERATE {
fmt.Fprintf(g.Dest,"%s:\n",string(x))
}
}
if x,ok := e.Value.(GoTo); ok {
g.Sync(ga)
if ga == GA_GENERATE {
fmt.Fprintf(g.Dest,"%sgoto %s;\n",g.ind,string(x))
}
}
if x,ok := e.Value.(EnforceStore); ok {
if (ga == GA_GENERATE) && len(x)>0 {
er := ExprRef{string(x),0}
s,ok := g.tree.Update(er,Noop)
if ok {
fmt.Fprintf(g.Dest,"%s%s = %s;\n",g.ind,er.Name,s)
g.tree.Delete(er)
}
}
}
if x,ok := e.Value.(TouchVariable); ok {
if len(x)>0 {
er := ExprRef{string(x),0}
switch ga {
case GA_COUNT:
g.revcnt.Update(er,revcnt_incr)
case GA_GENERATE:
g.revcnt.Update(er,revcnt_decr_first)
s,ok := g.tree.Update(er,Noop)
if ok {
fmt.Fprintf(g.Dest,"%s%s = %s;\n",g.ind,er.Name,s)
g.tree.Delete(er)
}
}
}
}
if x,ok := e.Value.(*Declaration); ok {
if (ga == GA_GENERATE) && len(x.Names)>0 {
fmt.Fprintf(g.Dest,"%s%s %s",g.ind,x.DataType,x.Names[0])
for _,n := range x.Names[1:] { fmt.Fprintf(g.Dest," ,%s",n) }
fmt.Fprintln(g.Dest," ;")
}
}
if x,ok := e.Value.(SetVolatile); ok {
if (ga == GA_GENERATE) && len(x.Variable)>0 {
er := ExprRef{x.Variable,0}
g.volm.Update(er,Put(x.Volatile))
/*
If the variable is now volatile, enforce store.
*/
if x.Volatile {
s,ok := g.tree.Update(er,Noop)
if ok {
fmt.Fprintf(g.Dest,"%s%s = %s;\n",g.ind,er.Name,s)
g.tree.Delete(er)
g.eflags.Delete(er)
}
}
}
}
}
g.Sync(ga)
}
|
7a6750a50b7c2f057fc11428846473fd2f4f2278
|
[
"Markdown",
"Go"
] | 5
|
Go
|
byte-mug/codegenfw
|
e13150b9cff5b68b96a1da61583fa4e0f01081af
|
a7bed67ea15aba56a9d259b1c189e17e0909ca8d
|
refs/heads/master
|
<file_sep># Surveyor
Simple Survey Manager with nodejs and mongodb
## Prerequisites
MongoDB
## Install
```
npm install
```
and
```
npm install -g nodemon
```
## Start Server
```
npm start
```<file_sep>var app = require('../index');
//var express = require('express');
var middleware = require('../middlewares');
var controllers = require('../controllers');
const routerJson=[
{
path:"/api",
children:[
{
path: "/user",
children:[
{
path:"/users",
controller: controllers.api.user.userList
},{
path:"/users",
method:"post",
controller: controllers.api.user.userCreate
},{
path:"/profile",
controller: controllers.api.user.info,
middleware:[ middleware.shouldLogin ]
},{
controller: controllers.main.errorHandler
}
]
},{
path: "/survey",
//middleware:[ middleware.shouldLogin ],
children:[
{
path: "/surveys",
controller: controllers.api.survey.listOfUser
},{
path: "/surveys",
method: "post",
controller: controllers.api.survey.createOfUser
},{
path: "/:survey_id/:question_id/result",
method: "post",
controller: controllers.api.result.createResult
}
]
}
]
},{
children:[
{
path:"/",
controller: controllers.main.index
},{
path:"/login",
controller: controllers.main.loginPage,
middleware: [ app.securityManager.csrfProtection ]
},{
path:"/login",
method:"post",
controller: controllers.main.login,
middleware: [ app.securityManager.csrfProtection ]
},{
path: "/join",
controller: controllers.main.registerPage
},{
path: "/logout",
controller: controllers.main.logout
},{
path: "/embed/:id",
controller: controllers.main.embed_survey
},{
path: "/account",
middleware: [middleware.shouldLogin],
children:[
{
path: "/my_surveys",
controller: controllers.main.my_surveys
},{
path: "/create_survey",
controller: controllers.main.create_survey
},{
path: "/show_servey/:id",
controller: controllers.main.show_survey
},{
path: "/show_servey/:id/:question_id",
controller: controllers.main.show_question
},{
path:"/show_servey/:id/:question_id/results",
controller: controllers.main.show_question_results
},{
path: "/export",
controller: controllers.main.export
}
]
},{
controller: controllers.main.errorHandler
},{
path: "*",
controller: controllers.main.notFound
}
]
}
];
module.exports.router=require('../system').router.createRouterFromJson(routerJson);<file_sep>var mongoose = require('mongoose');
const mongoDB = 'mongodb://127.0.0.1/surveyor';
mongoose.Promise=global.Promise;
mongoose.connect(mongoDB,{ useNewUrlParser: true});
module.exports.user=require('./user');
module.exports.survey=require('./survey');
module.exports.question=require('./question');
module.exports.result=require('./result');<file_sep>var app = require('../index');
var Survey = require('../models').survey;
var util = require('util');
var Result = require('../models').result;
var XLSX = require('xlsx');
module.exports.index=function(req,res){
if(req.isAuthenticated())
res.render('dashboard',{user:req.user});
else
res.render('index');
};
module.exports.my_surveys=function(req,res){
Survey
.find({user: req.user._id})
.sort('-created_at')
.exec().then((surveys)=>{
res.render('survey_list',{user:req.user,list:surveys});
})
};
module.exports.create_survey=(req,res)=>{
res.render('create_survey',{user:req.user});
};
module.exports.show_survey=(req,res)=>{
Survey
.findOne({user: req.user._id,_id: req.params.id})
.exec().then((servey)=>{
res.render('show_survey',{user:req.user,servey:servey});
}).catch((err)=>{
res.render('500',{err:err});
})
};
module.exports.embed_survey=(req,res)=>{
Survey
.findById(req.params.id)
.exec().then((servey)=>{
res.render('embed_survey',{servey:servey});
}).catch((err)=>{
res.render('500',{err:err});
});
};
module.exports.show_question=(req,res)=>{
Survey
.findOne({user: req.user._id,_id: req.params.id})
.exec().then((servey)=>{
var question=servey.questionnaires.id(req.params.question_id);
//res.send(util.inspect(question));
if(question)
res.render('show_question',{user:req.user,servey_name:servey.name,question:question});
else
res.render('500',{err:'question does not exist'});
})
};
module.exports.show_question_results=(req,res)=>{
var data={};
Survey
.findOne({user: req.user._id,_id: req.params.id})
.exec().then((servey)=>{
data.question=servey.questionnaires.id(req.params.question_id);
if(data.question==null) res.send("No question");
return Result
.mapReduce({
map:function(){for(var i=0;i<this.choices.length;i++) emit(this.choices[i],1)},
reduce:function(key,values){return values.length},
query:{survey:req.params.id,question:req.params.question_id}
});
}).then((result)=>{
var choices={};
data.question.choices.forEach((item)=>{
choices[item._id]={count:0,text:item.text};
});
var stat={max:0};
result.results.forEach((item)=>{
choices[item._id].count=item.value;
if(stat.max<item.value) stat.max=item.value;
});
res.render('show_result',{user:req.user,question:data.question.question,choices:choices,max:stat.max});
}).catch((err)=>{
res.render('500',{err:err});
})
};
module.exports.export=(req,res)=>{
Survey
.find({user: req.user._id})
.exec().then((surveys)=>{
var wb=XLSX.utils.book_new();
surveys.forEach((s)=>{
var data = s.questionnaires.map((q)=>{
var d={question:q.question};
q.choices.forEach((c,i)=>{
d['choice'+(i+1)]=c.text
})
return d
});
var ws=XLSX.utils.json_to_sheet(data);
XLSX.utils.book_append_sheet(wb,ws,s.name);
})
res.writeHead(200, [['Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet']]);
res.end(XLSX.write(wb, {type: 'buffer'}));
}).catch((err)=>{
res.render('500',{err:err});
})
};
module.exports.loginPage=function(req,res){
if(req.isAuthenticated())
res.redirect('/');
else
res.render('login',{
csrfToken:req.csrfToken(),
nextUrl: ((req.query.next) ? "?next="+req.query.next: ""),
loginerror:(req.query.error!=undefined),
loginerrormsg:req.flash('loginerrormsg')
});
};
module.exports.registerPage=function(req,res){
res.render('join',{});
};
module.exports.login=function(req,res,next){
app.securityManager.authenticateLogin(req,res,next,function(err,user,info){
if (err) return next(err);
req.flash('loginerrormsg', (info)?info.message:"");
if (!user) return res.redirect('/login?error=1'+((req.query.next)?"&next="+req.query.next:""));
// Manually establish the session...
req.login(user, function(err) {
if (err) return next(err);
if(req.query.next) return res.redirect(req.query.next);
return res.redirect('/');
});
});
};
module.exports.logout=function(req,res){
req.logout();
res.redirect('/');
};
module.exports.notFound=function(req,res){
res.render('404',{origin:req.originalUrl});
};
module.exports.errorHandler=function (err, req, res, next) {
if (err.code === 'EBADCSRFTOKEN') res.status(403).send('Hack Attempt!');
else if(err.code === 'ENEEDROLE') res.render('500',{err:err});
else return next(err);
};<file_sep>var express = require('express');
var app = module.exports = express();
app.use('/static',express.static('static'));
app.set('view engine','html');
app.engine('html',require('ejs').renderFile);
var securityManager = module.exports.securityManager = require('./boot');
require('./routes');
var port=process.env.PORT || 8000;
app.listen(port,function(){
console.log("Listening on 'http://127.0.0.1:"+port);
});
|
5188333afd333f92eb9242494ae0e85e630ea4f2
|
[
"Markdown",
"JavaScript"
] | 5
|
Markdown
|
sureshdevaraj/surveyor
|
0faa99040c089c9c9b2ee8895ea383f54ecf145f
|
0e56418a4727ba3e307788e0d1352efe6594e0c7
|
refs/heads/master
|
<repo_name>shammishailaj/core<file_sep>/utils/sites.go
package utils
import (
"github.com/backpulse/core/models"
)
func HasPremiumFeatures(site models.Site, size float64) bool {
if len(site.Collaborators) > 1 {
return true
}
if site.TotalSize > 500 {
return true
}
return false
}
<file_sep>/database/videos.go
package database
import (
"time"
"github.com/backpulse/core/models"
"gopkg.in/mgo.v2/bson"
)
func AddVideo(video models.Video) error {
video.UpdatedAt = time.Now()
video.CreatedAt = time.Now()
err := DB.C(videosCollection).Insert(video)
return err
}
func GetVideo(videoID bson.ObjectId) (models.Video, error) {
var video models.Video
err := DB.C(videosCollection).FindId(videoID).One(&video)
return video, err
}
func GetGroupVideos(id bson.ObjectId) ([]models.Video, error) {
var videos []models.Video
err := DB.C(videosCollection).Find(bson.M{
"video_group_id": id,
}).All(&videos)
return videos, err
}
func UpdateVideo(id bson.ObjectId, video models.Video) error {
err := DB.C(videosCollection).UpdateId(id, bson.M{
"$set": bson.M{
"title": video.Title,
"content": video.Content,
"youtube_url": video.YouTubeURL,
},
})
return err
}
func RemoveVideo(id bson.ObjectId) error {
err := DB.C(videosCollection).RemoveId(id)
return err
}
func UpdateVideosIndexes(siteID bson.ObjectId, videos []models.Video) error {
for _, video := range videos {
err := DB.C(videosCollection).Update(bson.M{
"site_id": siteID,
"_id": video.ID,
}, bson.M{
"$set": bson.M{
"index": video.Index,
},
})
if err != nil {
return err
}
}
return nil
}
<file_sep>/database/videogroups.go
package database
import (
"time"
"github.com/backpulse/core/models"
"gopkg.in/mgo.v2/bson"
)
func AddVideoGroup(videoGroup models.VideoGroup) error {
videoGroup.UpdatedAt = time.Now()
videoGroup.CreatedAt = time.Now()
err := DB.C(videoGroupsCollection).Insert(videoGroup)
return err
}
func UpdateVideoGroup(id bson.ObjectId, group models.VideoGroup) error {
err := DB.C(videoGroupsCollection).UpdateId(id, bson.M{
"$set": bson.M{
"title": group.Title,
"image": group.Image,
},
})
return err
}
func GetVideoGroup(ID bson.ObjectId) (models.VideoGroup, error) {
var videoGroup models.VideoGroup
err := DB.C(videoGroupsCollection).FindId(ID).One(&videoGroup)
videos, err := GetGroupVideos(videoGroup.ID)
if err != nil {
return models.VideoGroup{}, nil
}
videoGroup.Videos = videos
return videoGroup, err
}
func GetVideoGroupByShortID(id string) (models.VideoGroup, error) {
var videoGroup models.VideoGroup
err := DB.C(videoGroupsCollection).Find(bson.M{
"short_id": id,
}).One(&videoGroup)
videos, err := GetGroupVideos(videoGroup.ID)
if err != nil {
return models.VideoGroup{}, nil
}
videoGroup.Videos = videos
return videoGroup, err
}
func GetVideoGroups(siteID bson.ObjectId) ([]models.VideoGroup, error) {
var videoGroups []models.VideoGroup
err := DB.C(videoGroupsCollection).Find(bson.M{
"site_id": siteID,
}).All(&videoGroups)
return videoGroups, err
}
func RemoveVideoGroup(id bson.ObjectId) error {
err := DB.C(videoGroupsCollection).RemoveId(id)
return err
}
func UpdateVideoGroupsIndexes(siteID bson.ObjectId, groups []models.VideoGroup) error {
for _, g := range groups {
err := DB.C(videoGroupsCollection).Update(bson.M{
"site_id": siteID,
"_id": g.ID,
}, bson.M{
"$set": bson.M{
"index": g.Index,
},
})
if err != nil {
return err
}
}
return nil
}
|
ec23e970e8df7e01ce643505cf88cb0e198a5e08
|
[
"Go"
] | 3
|
Go
|
shammishailaj/core
|
b25333a385dd42e2a847a9980d104a692f5d4fd4
|
5663aaec1e8bc13d7bcc2a78e1729a326aac0d02
|
refs/heads/main
|
<file_sep># Amazon-Clone
Amazon clone with basic authentication
|
1e1e5ca0847a4c03f2fba0ba595d4d8119263bd4
|
[
"Markdown"
] | 1
|
Markdown
|
Tsvetomir95/Amazon-Clone
|
4cec42e76d506ab9a28d028027379556cd1f918a
|
e96283b8b34f7550a29c190b4310c115ef248f23
|
refs/heads/master
|
<repo_name>MC923-dev/ItemChunkLimiter<file_sep>/itemlimiter/ItemLimiter.java
package itemlimiter;
import itemlimiter.handler.InternalListener;
import org.bukkit.plugin.java.JavaPlugin;
public class ItemLimiter extends JavaPlugin {
private ItemLimiterConfig c;
@Override
public void onEnable() {
saveDefaultConfig();
c = new ItemLimiterConfig(getConfig());
getServer().getPluginManager().registerEvents(new InternalListener(c), this);
}
}
<file_sep>/README.md
# ItemChunkLimiter
Restricts number of dropped items in chunks
|
4ac4c2ffbb60b70a733155b7ce6b19398478f02d
|
[
"Markdown",
"Java"
] | 2
|
Java
|
MC923-dev/ItemChunkLimiter
|
5f514c9a00af5de9a3181a41a39a3d0ddd141980
|
91acc95dca85aab50a7c88bd96fac6ae95383e02
|
refs/heads/master
|
<repo_name>Edwinngera/BuildingManagement<file_sep>/site/models/power.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const PowerSchema = new Schema({
room_id: {
type: String,
required: true
},
power: {
type: Number,
required: true
},
current: {
type: Number,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = Occupancy = mongoose.model("Power", PowerSchema);
<file_sep>/site/models/devices.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const DevicesSchema = new Schema({
fan_state: {
type: Number,
required: true
},
bulb_state: {
type: Number,
required: true
},
date: {
type: Date,
default: Date.now
},
room_id: {
type: String,
required: true
}
});
module.exports = DhtSensor = mongoose.model("Devices", DevicesSchema);
<file_sep>/README.md
# BuildingManagement
peter@peter:~/Documents/Projects/BuildingManagement\$ dmesg | grep ttyUSB
picocom /dev/ttyUSB1 -b 115200
https://docs.micropython.org/en/latest/esp8266/tutorial/repl.html
https://learn.sparkfun.com/tutorials/micropython-programming-tutorial-getting-started-with-the-esp32-thing/all
peter@peter:~/Documents/Projects/BuildingManagement/esp/motion-sensor$ sudo ampy --port /dev/ttyUSB0 --baud 115200 put main.py
peter@peter:~/Documents/Projects/BuildingManagement/esp/motion-sensor$ sudo ampy --port /dev/ttyUSB0 --baud 115200 ls
peter@peter:~$ nmap -sP 192.168.0.1/24
peter@peter:~$ arp -a -n
ctrl a
ctrl x
ssh pi@<IP>
Next you will be prompted for the password for the pi login: the default password on Raspbian is <PASSWORD>. For security reasons it is highly recommended to change the default password on the Raspberry Pi. You should now be able to see the Raspberry Pi prompt, which will be identical to the one found on the Raspberry Pi itself.
mosquitto_sub –d –t armtronix_mqtt
mosquitto_pub –d –t armtronix_mqtt –m “Hello armtronix”
ping raspberrypi.local
lt --port 8000
http://wp.spoton.cz/2017/11/29/micropython-on-esp-01-8266/
https://medium.com/@akash0x53/esp8266-micropython-101-435085ffae5c
https://medium.com/@shalandy/deploy-git-subdirectory-to-heroku-ea05e95fce1f
https://medium.com/salted-bytes/mqtt-raspberry-pi-with-nodejs-478a4839bc43
<file_sep>/esp/dht-sensor/main.py
import connectWifi
import time
import config
import json
from dht import DHT11
from machine import Pin
from umqtt.simple import MQTTClient
connectWifi.connect()
d = DHT11(Pin(2))
SERVER = config.MQTT_CONFIG['MQTT_HOST']
PORT = config.MQTT_CONFIG['PORT']
SENSOR_ID = config.MQTT_CONFIG['SENSOR_ID']
PUB_TOPIC = config.MQTT_CONFIG['PUB_TOPIC']
def read_sensor():
return {
"temperature": d.temperature(),
"humidity": d.humidity()
}
def send(data):
c = MQTTClient(SENSOR_ID, SERVER, 1883)
c.connect()
c.publish(PUB_TOPIC, json.dumps(data))
c.disconnect()
def main():
while True:
data = read_sensor()
print("Sending data", data)
send(data)
if __name__ == "__main__":
main()
<file_sep>/esp/relay-fan/config.py
MQTT_CONFIG = {
'SENSOR_ID': 'FAN',
'MQTT_HOST': '192.168.0.179',
'PORT': '1883',
'PUB_TOPIC': 'building/room/relay/fan',
}
WIFI_CONFIG = {
'WIFI_ESSID': 'skypee.exe',
'WIFI_PASSWORD': '<PASSWORD>'
}
<file_sep>/site/client/src/reducers/deviceReducer.js
import { GET_MOTION_DATA, GET_OCCUPANCY_DATA } from "../actions/types";
import { GET_CLIMATE_DATA } from "../actions/types";
import { GET_POWER_DATA } from "../actions/types";
import { GET_DEVICES_DATA } from "../actions/types";
const initialState = {
motionData: null
};
export default function(state = initialState, action) {
switch (action.type) {
case GET_MOTION_DATA:
return {
...state,
motionData: action.payload
};
case GET_CLIMATE_DATA:
return {
...state,
climateData: action.payload
};
case GET_POWER_DATA:
return {
...state,
powerData: action.payload
};
case GET_DEVICES_DATA:
return {
...state,
devicesData: action.payload
};
case GET_OCCUPANCY_DATA:
return {
...state,
occupancyData: action.payload
};
default:
return state;
}
}
<file_sep>/site/client/src/container/Climate/Climate.js
import React, { Component } from "react";
import TopMenu from "../../components/TopMenu/TopMenu";
import LeftMenu from "../../components/LeftMenu/LeftMenu";
import LineChartComponent from "../../components/LineChartComponent/LineChartComponent";
import { Grid } from "semantic-ui-react";
import { connect } from "react-redux";
import { getClimateData } from "../../actions/deviceActions";
import PropTypes from "prop-types";
class Climate extends Component {
componentDidMount() {
this.props.getClimateData();
}
componentWillReceiveProps(nextProps) {
this.props.getClimateData();
}
render() {
const { climateData } = this.props.devicesData;
let climateDataSet;
// data = Object.keys(climateData).map(item => climateData[item]);
// console.log(typeof data);
if (climateData === null) {
climateDataSet = null;
} else {
if (undefined !== climateData && climateData.length > 0) {
climateDataSet = Object.keys(climateData)
.sort((a, b) => b - a)
.map(item => climateData[item])
.sort((a, b) => b - a);
}
}
return (
<div>
<TopMenu />
<Grid>
<Grid.Column width={2}>
<LeftMenu />
</Grid.Column>
<Grid.Column width={14}>
<LineChartComponent
deviceData={climateDataSet}
title={"Climate Data"}
xaxis={"date"}
line1={"temperature"}
line2={"humidity"}
y_axis={"Temperature(°C) & Humidity(Relative Humidity)"}
/>
</Grid.Column>
</Grid>
</div>
);
}
}
Climate.propTypes = {
getClimateData: PropTypes.func.isRequired,
devicesData: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
devicesData: state.devices
});
export default connect(
mapStateToProps,
{ getClimateData }
)(Climate);
<file_sep>/site/client/src/container/Devices/Devices.js
import React, { Component } from "react";
import TopMenu from "../../components/TopMenu/TopMenu";
import LeftMenu from "../../components/LeftMenu/LeftMenu";
import LineChartComponent from "../../components/LineChartComponent/LineChartComponent";
import { Grid } from "semantic-ui-react";
import { connect } from "react-redux";
import { getDevicesData } from "../../actions/deviceActions";
import PropTypes from "prop-types";
class Devices extends Component {
componentDidMount() {
this.props.getDevicesData();
}
componentWillReceiveProps(nextProps) {
this.props.getDevicesData();
}
render() {
const { devicesData } = this.props.devicesData;
let theDevicesDataSet;
// data = Object.keys(climateData).map(item => climateData[item]);
// console.log(typeof data);
if (devicesData === null) {
theDevicesDataSet = null;
} else {
if (undefined !== devicesData && devicesData.length > 0) {
theDevicesDataSet = Object.keys(devicesData)
.sort((a, b) => b - a)
.map(item => devicesData[item])
.sort((a, b) => b - a);
}
}
return (
<div>
<TopMenu />
<Grid>
<Grid.Column width={2}>
<LeftMenu />
</Grid.Column>
<Grid.Column width={14}>
<LineChartComponent
deviceData={theDevicesDataSet}
title={"Devices Data"}
xaxis={"date"}
line1={"bulb_state"}
line2={"fan_state"}
y_axis={"Devices State"}
/>
</Grid.Column>
</Grid>
</div>
);
}
}
Devices.propTypes = {
getDevicesData: PropTypes.func.isRequired,
devicesData: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
devicesData: state.devices
});
export default connect(
mapStateToProps,
{ getDevicesData }
)(Devices);
<file_sep>/esp/relay-bulb/main.py
import connectWifi
import time
import config
import json
from dht import DHT11
from machine import Pin
from umqtt.simple import MQTTClient
connectWifi.connect()
RPin = Pin(2, Pin.OUT, value=0)
SERVER = config.MQTT_CONFIG['MQTT_HOST']
PORT = config.MQTT_CONFIG['PORT']
SENSOR_ID = config.MQTT_CONFIG['SENSOR_ID']
PUB_TOPIC = config.MQTT_CONFIG['PUB_TOPIC']
c = MQTTClient(SENSOR_ID, SERVER)
def relay_on():
send("Relay on")
RPin.on()
def relay_off():
send("Relay off")
RPin.off()
def send(data):
c.publish(PUB_TOPIC, json.dumps(data))
def sub_cb(topic, msg):
print((topic, msg))
command = msg.decode('ASCII')
if command == "on":
relay_on()
elif command == "off":
relay_off()
def main(server=SERVER):
c.set_callback(sub_cb)
c.connect()
c.subscribe(PUB_TOPIC)
while True:
if True:
# Blocking wait for message
c.wait_msg()
else:
# Non-blocking wait for message
c.check_msg()
# Then need to sleep to avoid 100% CPU usage (in a real
# app other useful actions would be performed instead)
time.sleep(1)
c.disconnect()
if __name__ == "__main__":
main()
<file_sep>/site/models/room.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const RoomSchema = new Schema({
room_name: {
type: String,
required: true
},
room_description: {
type: String,
required: true
},
priviledge_level: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = Room = mongoose.model("Room", RoomSchema);
<file_sep>/site/client/src/components/LeftMenu/LeftMenu.js
import React, { Component } from "react";
import { Menu } from "semantic-ui-react";
import { connect } from "react-redux";
import { logoutUser } from "../../actions/authActions";
import PropTypes from "prop-types";
class LeftMenu extends Component {
onLogoutClick(e) {
e.preventDefault();
this.props.logoutUser();
}
render() {
return (
<div>
<Menu secondary pointing vertical style={{ minHeight: "100vh" }}>
<Menu.Item
onClick={() => {
window.location.href = "/dashboard";
}}
>
<Menu.Header>Dashboard</Menu.Header>
</Menu.Item>
<Menu.Item
onClick={() => {
window.location.href = "/climate";
}}
>
<Menu.Header>Climate</Menu.Header>
</Menu.Item>
<Menu.Item
onClick={() => {
window.location.href = "/occupancy";
}}
>
<Menu.Header>Occupancy</Menu.Header>
</Menu.Item>
<Menu.Item
onClick={() => {
window.location.href = "/devices";
}}
>
<Menu.Header>Devices</Menu.Header>
</Menu.Item>
<Menu.Item
onClick={() => {
window.location.href = "/power";
}}
>
<Menu.Header>Power</Menu.Header>
</Menu.Item>
</Menu>
</div>
);
}
}
LeftMenu.propTypes = {
logoutUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth
});
export default connect(
mapStateToProps,
{ logoutUser }
)(LeftMenu);
<file_sep>/esp/test/main.py
# The MIT License (MIT)
# Copyright (c) 2019 <NAME>
# https://opensource.org/licenses/MIT
#
# Example MicroPython and CircuitPython code showing how to use the MQTT protocol to
# publish data to an Adafruit IO feed
#
# Tested using the releases:
# ESP8266
# MicroPython 1.9.3
# MicroPython 1.9.4
# MicroPython 1.10
# CircuitPython 2.3.1 (needs addition of CircuitPython specific umqtt module)
# CircuitPython 3.0.0 (needs addition of CircuitPython specific umqtt module)
# ESP32
# MicroPython 1.9.4 (needs addition of MicroPython umqtt module)
# MicroPython 1.10
#
# Tested using the following boards:
# Adafruit Feather HUZZAH ESP8266
# Adafruit Feather HUZZAH ESP32
# WeMos D1 Mini
#
# User configuration parameters are indicated with "ENTER_".
import network
import time
from umqtt.robust import MQTTClient
import os
import gc
import sys
from dht import DHT11
from machine import Pin
d = DHT11(Pin(0))
# WiFi connection information
WIFI_SSID = 'YWCA_Beecher'
WIFI_PASSWORD = '<PASSWORD>'
# turn off the WiFi Access Point
ap_if = network.WLAN(network.AP_IF)
ap_if.active(False)
# connect the device to the WiFi network
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(WIFI_SSID, WIFI_PASSWORD)
# wait until the device is connected to the WiFi network
MAX_ATTEMPTS = 20
attempt_count = 0
while not wifi.isconnected() and attempt_count < MAX_ATTEMPTS:
attempt_count += 1
time.sleep(1)
if attempt_count == MAX_ATTEMPTS:
print('could not connect to the WiFi network')
sys.exit()
# create a random MQTT clientID
random_num = int.from_bytes(os.urandom(3), 'little')
mqtt_client_id = bytes('client_'+str(random_num), 'utf-8')
# connect to Adafruit IO MQTT broker using unsecure TCP (port 1883)
#
# To use a secure connection (encrypted) with TLS:
# set MQTTClient initializer parameter to "ssl=True"
# Caveat: a secure connection uses about 9k bytes of the heap
# (about 1/4 of the micropython heap on the ESP8266 platform)
ADAFRUIT_IO_URL = b'io.adafruit.com'
ADAFRUIT_USERNAME = b'peterokwara'
ADAFRUIT_IO_KEY = b'7f61d8c6412a48a1bb1ef095ab4db80a'
ADAFRUIT_IO_FEEDNAME = b'climate'
client = MQTTClient(client_id=mqtt_client_id,
server=ADAFRUIT_IO_URL,
user=ADAFRUIT_USERNAME,
password=ADAFRUIT_IO_KEY,
ssl=False)
try:
client.connect()
except Exception as e:
print('could not connect to MQTT server {}{}'.format(type(e).__name__, e))
sys.exit()
# publish free heap statistics to Adafruit IO using MQTT
#
# format of feed name:
# "ADAFRUIT_USERNAME/feeds/ADAFRUIT_IO_FEEDNAME"
mqtt_feedname = bytes(
'{:s}/feeds/{:s}'.format(ADAFRUIT_USERNAME, ADAFRUIT_IO_FEEDNAME), 'utf-8')
PUBLISH_PERIOD_IN_SEC = 10
while True:
try:
free_heap_in_bytes = gc.mem_free()
client.publish(mqtt_feedname,
bytes(str(free_heap_in_bytes), 'utf-8'),
qos=0)
client.publish(mqtt_feedname,
"ahhahah", qos=0)
time.sleep(PUBLISH_PERIOD_IN_SEC)
except KeyboardInterrupt:
print('Ctrl-C pressed...exiting')
client.disconnect()
sys.exit()
<file_sep>/site/client/src/components/TopMenu/TopMenu.js
import React, { Component } from "react";
import { Menu, Icon } from "semantic-ui-react";
import { connect } from "react-redux";
import { logoutUser } from "../../actions/authActions";
import PropTypes from "prop-types";
class TopMenu extends Component {
onLogoutClick(e) {
e.preventDefault();
this.props.logoutUser();
}
render() {
return (
<div>
<Menu secondary pointing>
<Menu.Item
name="Dashboard"
onClick={this.handleItemClick}
className="menu-logo"
/>
<Menu.Menu position="right">
<Menu.Item name="logout" onClick={this.onLogoutClick.bind(this)}>
Logout
<Icon style={{ paddingLeft: "5px" }} name="user" size="small" />
</Menu.Item>
</Menu.Menu>
</Menu>
</div>
);
}
}
TopMenu.propTypes = {
logoutUser: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
auth: state.auth
});
export default connect(
mapStateToProps,
{ logoutUser }
)(TopMenu);
<file_sep>/site/client/src/container/Dashboard/Dashboard.js
import React, { Component } from "react";
import TopMenu from "../../components/TopMenu/TopMenu";
import LeftMenu from "../../components/LeftMenu/LeftMenu";
import { Grid, Header } from "semantic-ui-react";
import {
getClimateData,
getDevicesData,
getOccupancyData,
getPowerData
} from "../../actions/deviceActions";
import PropTypes from "prop-types";
import { connect } from "react-redux";
class Dashboard extends Component {
componentDidMount() {
this.props.getClimateData();
this.props.getDevicesData();
this.props.getOccupancyData();
this.props.getPowerData();
}
componentWillReceiveProps(nextProps) {
this.props.getClimateData();
this.props.getDevicesData();
this.props.getOccupancyData();
this.props.getPowerData();
}
render() {
const { climateData } = this.props.devicesData;
const { devicesData } = this.props.devicesData;
const { occupancyData } = this.props.devicesData;
const { powerData } = this.props.devicesData;
let temperature;
let humidity;
if (climateData === null) {
temperature = null;
humidity = null;
} else {
if (undefined !== climateData && climateData.length > 0) {
temperature = Object.values(climateData)[0].temperature;
humidity = Object.values(climateData)[0].humidity;
}
}
let bulb_state;
let fan_state;
if (devicesData === null) {
bulb_state = null;
fan_state = null;
} else {
if (undefined !== devicesData && devicesData.length > 0) {
bulb_state = Object.values(devicesData)[0].bulb_state;
fan_state = Object.values(devicesData)[0].fan_state;
}
}
let occupancy;
if (occupancyData === null) {
occupancy = null;
} else {
if (undefined !== occupancyData && occupancyData.length > 0) {
occupancy = Object.values(occupancyData)[0].occupancy;
}
}
let power;
let current;
if (powerData === null) {
power = null;
current = null;
} else {
if (undefined !== powerData && powerData.length > 0) {
power = Object.values(powerData)[0].power;
current = Object.values(powerData)[0].current;
}
}
return (
<div>
<TopMenu />
<Grid>
<Grid.Column width={2}>
<LeftMenu />
</Grid.Column>
<Grid.Column
width={10}
style={{ paddingTop: "200px", paddingLeft: "300px" }}
>
<Grid columns="two">
<Grid.Row>
<Grid.Column style={{ paddingBottom: "100px" }}>
<Header as="h1">Climate</Header>
<Header as="h1" color="grey">
Temperature: {temperature}
</Header>
<Header as="h1" color="grey">
Humidity: {humidity}
</Header>
</Grid.Column>
<Grid.Column>
<h1>Devices</h1>
<Header as="h1" color="grey">
Fan state: {fan_state}
</Header>
<Header as="h1" color="grey">
Bulb state: {bulb_state}
</Header>
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>
<h1>Occupancy</h1>
<Header as="h1" color="grey">
Occupancy: {occupancy}
</Header>
</Grid.Column>
<Grid.Column>
<h1>Power</h1>
<Header as="h1" color="grey">
Current: {current}
</Header>
<Header as="h1" color="grey">
Power: {power}
</Header>
</Grid.Column>
</Grid.Row>
</Grid>
</Grid.Column>
</Grid>
</div>
);
}
}
Dashboard.propTypes = {
getClimateData: PropTypes.func.isRequired,
getDevicesData: PropTypes.func.isRequired,
getOccupancyData: PropTypes.func.isRequired,
getPowerData: PropTypes.func.isRequired,
devicesData: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
devicesData: state.devices
});
export default connect(
mapStateToProps,
{ getClimateData, getDevicesData, getOccupancyData, getPowerData }
)(Dashboard);
<file_sep>/site/routes/api/climate.js
const express = require("express");
const router = express.Router();
const Climate = require("../../models/climate");
// @route POST api/climate
// @desc Create sensor data from dht sensor
// @access Public
router.post("/", (req, res) => {
const newClimate = new Climate({
temperature: req.body.temperature,
humidity: req.body.humidity,
room_id: req.body.room_id
});
newClimate.save().then(Climate => res.json(Climate));
});
// @route GET api/climate/all
// @desc Return all climate data
// @access Public
router.get("/all", (req, res) => {
Climate.find()
.sort({ date: -1 })
.then(climatedata => res.json(climatedata));
});
module.exports = router;
<file_sep>/site/client/src/App.js
import React, { Component } from "react";
import "./App.css";
import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
import SignIn from "./container/SignIn/SignIn";
import SignUp from "./container/SignUp/SignUp";
import Dashboard from "./container/Dashboard/Dashboard";
import Climate from "./container/Climate/Climate";
import Power from "./container/Power/Power";
import Devices from "./container/Devices/Devices";
import Occupancy from "./container/Occupancy/Occupancy";
import { Provider } from "react-redux";
import store from "./store";
import jwt_decode from "jwt-decode";
import setAuthToken from "./utils/setAuthToken";
import { setCurrentUser, logoutUser } from "./actions/authActions";
import PrivateRoute from "./components/Common/PrivateRoute";
// check for token
if (localStorage.jwtToken) {
// set auth token header auth
setAuthToken(localStorage.jwtToken);
// decode token and get user info and expiration
const decoded = jwt_decode(localStorage.jwtToken);
// set user and isAuthenticated
store.dispatch(setCurrentUser(decoded));
// check for expired token
const currentTime = Date.now() / 1000;
if (decoded.exp < currentTime) {
// logout the user
store.dispatch(logoutUser());
// TODO: clear current profile
// Redirect to login
window.location.href = "/";
}
}
class App extends Component {
render() {
return (
<Provider store={store}>
<Router>
<div className="App">
<Route exact path="/" component={SignIn} />
<Route exact path="/signup" component={SignUp} />
<Switch>
<PrivateRoute exact path="/dashboard" component={Dashboard} />
</Switch>
<Switch>
<PrivateRoute exact path="/Climate" component={Climate} />
</Switch>
<Switch>
<PrivateRoute exact path="/power" component={Power} />
</Switch>
<Switch>
<PrivateRoute exact path="/devices" component={Devices} />
</Switch>
<Switch>
<PrivateRoute exact path="/occupancy" component={Occupancy} />
</Switch>
</div>
</Router>
</Provider>
);
}
}
export default App;
<file_sep>/site/routes/api/occupancy.js
const express = require("express");
const router = express.Router();
const Occupancy = require("../../models/occupancy");
// @route POST api/occupancy
// @desc Create sensor data from pir motion sensor
// @access Public
router.post("/", (req, res) => {
const newOccupancy = new Occupancy({
room_id: req.body.room_id,
occupancy: req.body.occupancy
});
newOccupancy.save().then(Occupancy => res.json(Occupancy));
});
// @route GET api/occupancy/all
// @desc Return all motion sensor data
// @access Public
router.get("/all", (req, res) => {
Occupancy.find()
.sort({ date: -1 })
.then(occupancydata => res.json(occupancydata));
// console.log(req.Occupancy.sensor1);
});
module.exports = router;
<file_sep>/esp/current-sensor/main.py
import connectWifi
import time
import config
import json
import time
import utime
import machine
import math
from umqtt.simple import MQTTClient
connectWifi.connect()
ADC_SCALE = 1023.0
VREF = 5.0
sensitivity = 0.185
U = 230
adc = machine.ADC(0)
SERVER = config.MQTT_CONFIG['MQTT_HOST']
PORT = config.MQTT_CONFIG['PORT']
SENSOR_ID = config.MQTT_CONFIG['SENSOR_ID']
PUB_TOPIC = config.MQTT_CONFIG['PUB_TOPIC']
def calibrate():
global zero
acc = 0
x = 0
while x < 10:
acc += adc.read()
x = x + 1
zero = acc / 10
return zero
def read_sensor():
frequency = 50
period = 1000000 / frequency
Isum = 0
measurements_count = 0
t_start = utime.ticks_ms()
while (utime.ticks_ms() - t_start < period):
Inow = adc.read() - zero
Isum += Inow*Inow
measurements_count = measurements_count + 1
Irms = math.sqrt(Isum/measurements_count) / ADC_SCALE * VREF / sensitivity
P = U * Irms
return {
"current": Irms,
"power": P
}
def send():
c = MQTTClient(SENSOR_ID, SERVER, 1883)
c.connect()
c.publish(PUB_TOPIC, "sawasawao")
c.disconnect()
def main():
calibrate()
while True:
data = read_sensor()
# print("Sending data", data)
send()
# time.sleep(10)
if __name__ == "__main__":
main()
<file_sep>/site/client/src/actions/types.js
export const GET_ERRORS = "GET_ERRORS";
export const SET_CURRENT_USER = "SET_CURRENT_USER";
export const GET_MOTION_DATA = "GET_MOTION_DATA";
export const GET_CLIMATE_DATA = "GET_CLIMATE_DATA";
export const GET_POWER_DATA = "GET_POWER_DATA";
export const GET_DEVICES_DATA = "GET_DEVICES_DATA";
export const GET_OCCUPANCY_DATA = "GET_OCCUPANCY_DATA";
<file_sep>/esp/motion-sensor/main.py
import esp
import machine
import connectWifi
import time
import config
import utime
from machine import Pin
from umqtt.simple import MQTTClient
connectWifi.connect()
# define pins for the pir motion sensor
pinPir = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_UP)
pinPir1 = machine.Pin(2, machine.Pin.IN, machine.Pin.PULL_UP)
state = 'off'
lockLow = True
motiondetectedone = 0
motiondetectedtwo = 0
pause = 7000
takeLowTime = ''
SERVER = config.MQTT_CONFIG['MQTT_HOST']
PORT = config.MQTT_CONFIG['PORT']
SENSOR_ID = config.MQTT_CONFIG['SENSOR_ID']
PUB_TOPIC = config.MQTT_CONFIG['PUB_TOPIC']
def sub_cb(topic, msg):
global state, motiondetectedone, motiondetectedtwo, updatestate
print((topic, msg))
command = msg.decode('ASCII')
channel = topic.decode('ASCII')
# check for topic and handle accordingly
if channel == "pir_cmd":
if command == "on":
state = "on"
print("Turned on")
if command == "off":
state = "off"
print("Turned off")
motiondetectedone = 0
motiondetectedtwo = 0
if channel == "pir_state":
if command == "on":
motiondetectedone = 1
motiondetectedtwo = 1
if command == "off":
motiondetectedone = 0
motiondetectedtwo = 0
def main(server=SERVER, port=PORT):
c = MQTTClient(SENSOR_ID, SERVER, 1883)
c.set_callback(sub_cb)
while True:
global state, motiondetectedone, updatestate, lockLow, takeLowTime, motiondetectedtwo
c.connect()
if pinPir.value() == 1 and motiondetectedone == 0:
c.publish(PUB_TOPIC, b"pir1on")
motiondetectedone = 1
print("motiondetected state is (on)", motiondetectedone)
if pinPir.value() == 0 and motiondetectedone == 1:
c.publish(PUB_TOPIC, b"pir1off")
motiondetectedone = 0
print("motiondetected state is (off)", motiondetectedone)
c.disconnect()
c.connect()
if pinPir1.value() == 1 and motiondetectedtwo == 0:
c.publish(PUB_TOPIC, b"pir2on")
motiondetectedtwo = 1
print("motiondetected state is (on)", motiondetectedtwo)
if pinPir1.value() == 0 and motiondetectedtwo == 1:
c.publish(PUB_TOPIC, b"pir2off")
motiondetectedtwo = 0
print("motiondetected state is (off)", motiondetectedtwo)
c.disconnect()
if __name__ == "__main__":
main()
<file_sep>/site/routes/api/power.js
const express = require("express");
const router = express.Router();
const Power = require("../../models/power");
// @route POST api/power
// @desc Create data on power consupmtion and current consumption
// @access Public
router.post("/", (req, res) => {
const newPower = new Power({
room_id: req.body.room_id,
power: req.body.power,
current: req.body.current
});
newPower.save().then(Power => res.json(Power));
});
// @route GET api/power/all
// @desc Return all motion sensor data
// @access Public
router.get("/all", (req, res) => {
Power.find()
.sort({ date: -1 })
.then(Powerdata => res.json(Powerdata));
// console.log(req.Power.sensor1);
});
module.exports = router;
<file_sep>/site/client/src/components/SingleLineChartComponent/SingleLineChartComponent.js
import React from "react";
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
Label
} from "recharts";
const SingleLineChartComponent = props => (
<div>
<h1>{props.title}</h1>
<LineChart
width={1500}
height={700}
data={props.deviceData}
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
>
<XAxis dataKey="date">
<Label value="Date and time" offset={5} position="insideBottomLeft" />
</XAxis>
<YAxis
label={{ value: props.y_axis, angle: -90, position: "insideLeft" }}
/>
<CartesianGrid strokeDasharray="3 3" />
<Tooltip />
<Legend />
<Line
type="monotone"
dataKey={props.line1}
stroke="#8884d8"
activeDot={{ r: 8 }}
/>
</LineChart>
</div>
);
export default SingleLineChartComponent;
|
d2b8b25048678be765330ce02f1d038ac932a903
|
[
"JavaScript",
"Python",
"Markdown"
] | 22
|
JavaScript
|
Edwinngera/BuildingManagement
|
9b765b214f1ed9c0f29b0d033bfff94f59b9f89a
|
5bc9a81364878f54818295d42091481a2b32f7bc
|
refs/heads/master
|
<file_sep>import string
import os
import time
import random
def get_board(boardSize):
board = []
for row in range(boardSize+2):
board.append([])
for column in range(boardSize+2):
board[row].append(0)
return board
def valid_input(boardSize):
while True:
coordinate,direct = get_input()
if (direct == 'v' or direct == 'h') and coordinate[0].isalpha() and coordinate[1].isdigit():
if len(coordinate) == 2:
if (coordinate[0].upper() in string.ascii_uppercase[0:boardSize] and int(coordinate[1]) in range(1,boardSize+1)):
break
else:
print('Invalid input!')
continue
elif len(coordinate)==3 and coordinate[0].upper() in string.ascii_uppercase[0:boardSize] and int(coordinate[1]) == 1 and int(coordinate[2]) == 0:
break
else:
print('Invalid input!')
continue
return coordinate,direct
def get_input():
coordinate = input('Your coordinate: ')
direct = input('Vertical or horizontal (v/h): ')
return coordinate,direct
def print_board(board,boardSize):
print(' ',end="")
for number in range(1,boardSize+1):
print(str(number)+' ',end='')
print('\r')
for row in range(1,len(board)-1):
print(string.ascii_uppercase[row-1]+'|',end="")
for column in range(1,len(board[row])-1):
if board[row][column] == 1:
print('\33[31m'+'X'+'\033[0m'+'|',end="")
else:
print('0|',end="")
print('\r')
print('\r')
def get_coordinates(coordinate):
if len(coordinate) == 2:
letter = coordinate[0].upper()
row=string.ascii_uppercase.index(letter)+1
column = int(coordinate[1])
return row,column
else:
letter = coordinate[0].upper()
row=string.ascii_uppercase.index(letter)+1
column = 10
return row,column
def placing(board,row,column,ships,direct):
board[row][column] = 1
if ships[0] == 2 and direct == 'v':
board[row+1][column] = 1
elif ships[0] == 2 and direct == 'h':
board[row][column+1] = 1
def place(ships,board,coordinate,direct,boardSize):
row,column=get_coordinates(coordinate)
while True:
if board[row][column] == 1:
print('This place is taken!')
coordinate,direct=valid_input(boardSize)
row,column=get_coordinates(coordinate)
continue
elif board[row+1][column] == 0 and board[row-1][column] == 0 and board[row][column+1] == 0 and board[row][column-1] == 0:
placing(board,row,column,ships,direct)
break
else:
print('Ships are too close!')
coordinate,direct=valid_input(boardSize)
row,column=get_coordinates(coordinate)
continue
def place_horizontal(ships,board,coordinate,direct,boardSize):
row,column=get_coordinates(coordinate)
while True:
if board[row][column] == 1 or board[row][column+1] == 1:
print('This place is taken!')
coordinate,direct=valid_input(boardSize)
row,column=get_coordinates(coordinate)
continue
elif column == boardSize:
print('Ship is out of board!')
coordinate,direct=valid_input(boardSize)
row,column=get_coordinates(coordinate)
continue
elif board[row][column-1] == 0 and board[row-1][column] == 0 and board[row-1][column+1] == 0 and board[row][column+2] == 0 and board[row+1][column+1] == 0 and board[row+1][column] == 0:
board[row][column] = 1
board[row][column+1] = 1
break
else:
print('Ships are too close!')
coordinate,direct=valid_input(boardSize)
row,column=get_coordinates(coordinate)
continue
def place_vertical(ships,board,coordinate,direct,boardSize):
row,column=get_coordinates(coordinate)
while True:
if board[row][column] == 1 or board[row+1][column] == 1:
print('This place is taken!')
coordinate,direct=valid_input(boardSize)
row,column=get_coordinates(coordinate)
continue
elif row == boardSize:
print('Ship is out of board!')
coordinate,direct=valid_input(boardSize)
row,column=get_coordinates(coordinate)
continue
elif board[row][column-1] == 0 and board[row+1][column-1] == 0 and board[row+2][column] == 0 and board[row+1][column+1] == 0 and board[row][column+1] == 0 and board[row-1][column] == 0:
board[row][column] = 1
board[row+1][column] = 1
break
else:
print('Ships are too close!')
coordinate,direct=valid_input(boardSize)
row,column=get_coordinates(coordinate)
continue
def place_ship(ships,board,coordinate,direct,boardSize):
if ships[0] == 1:
place(ships,board,coordinate,direct,boardSize)
else:
if direct == 'v':
place_vertical(ships,board,coordinate,direct,boardSize)
else:
place_horizontal(ships,board,coordinate,direct,boardSize)
def board_size():
boardSize=int(input('Your board size: '))
while True:
if boardSize in range(1,11):
break
else:
print('Invalid input! (must be between 5-10)')
boardSize=int(input('Your board size: '))
continue
return boardSize
def player1_place(boardSize):
os.system('clear')
player1 = get_board(boardSize)
ships = [random.randint(1,2) for i in range(boardSize)]
countShips = sum(ships)
while len(ships) != 0:
print('Player 1')
print('\r')
print_board(player1,boardSize)
print(f"Your ship size is {ships[0]}.")
coordinate,direct = valid_input(boardSize)
place_ship(ships,player1,coordinate,direct,boardSize)
del ships[0]
os.system('clear')
print_board(player1,boardSize)
print(countShips)
return player1, countShips
def player2_place(boardSize):
os.system('clear')
player2 = get_board(boardSize)
ships = [random.randint(1,2) for i in range(boardSize)]
countShips=sum(ships)
while len(ships) != 0:
print('Player 2')
print('\r')
print_board(player2,boardSize)
print(f"Your ship size is {ships[0]}.")
coordinate,direct = valid_input(boardSize)
place_ship(ships,player2,coordinate,direct,boardSize)
del ships[0]
os.system('clear')
print_board(player2,boardSize)
print(countShips)
return player2,countShips
def print_board_shoot(board,boardSize):
print(' ',end="")
for number in range(1,boardSize+1):
print(str(number)+' ',end='')
print('\r')
for row in range(1,len(board)-1):
print(string.ascii_uppercase[row-1]+' ',end="")
for column in range(1,len(board[row])-1):
if board[row][column] == 0 or board[row][column] == 1:
print('0|',end="")
elif board[row][column] == 2:
print('\33[34m'+'M'+'\033[0m'+'|',end="")
elif board[row][column] == 3:
print('\33[33m'+'H'+'\033[0m'+'|',end="")
else:
print('\33[31m'+'S'+'\033[0m'+'|',end="")
print('\r')
print('\r')
def valid_shoot(boardSize):
while True:
coordinate = get_shoot()
if coordinate[0].isalpha() and coordinate[1].isdigit() and len(coordinate) == 2:
if (coordinate[0].upper() in string.ascii_uppercase[0:boardSize] and int(coordinate[1]) in range(1,boardSize+1)):
break
elif len(coordinate) == 3 and coordinate[0].upper() in string.ascii_uppercase[0:boardSize] and coordinate[1] == 1 and coordinate[2] ==0:
break
else:
print('Invalid input!')
continue
else:
print('Invalid input!')
continue
return coordinate
def get_shoot():
coordinate = input('Your coordinate: ')
return coordinate
def shooting(player,coordinate):
row,column = get_coordinates(coordinate)
while True:
if player[row][column] == 0:
print("You've missed!")
player[row][column] = 2
break
elif player[row][column] == 1 and (player[row+1][column] == 1 or player[row][column+1] == 1 or player[row-1][column] == 1 or player[row][column-1] == 1):
print('You\'ve hit a ship!')
player[row][column] = 3
break
elif player[row][column] == 1 and player[row+1][column] == 3:
print('You\'ve sunk a ship!')
player[row][column] = 4
player[row+1][column] = 4
break
elif player[row][column] == 1 and player[row-1][column] == 3:
print('You\'ve sunk a ship!')
player[row][column] = 4
player[row-1][column] = 4
break
elif player[row][column] == 1 and player[row][column+1] == 3:
print('You\'ve sunk a ship!')
player[row][column] = 4
player[row][column+1] = 4
break
elif player[row][column] == 1 and player[row][column-1] == 3:
print('You\'ve sunk a ship!')
player[row][column] = 4
player[row][column-1] = 4
break
elif player[row][column] == 1 and (player[row+1][column] == 0 or player[row+1][column] == 2) and (player[row-1][column] == 0 or player[row-1][column] == 2) and (player[row][column+1] == 0 or player[row-1][column] == 2) and (player[row][column-1] == 0 or player[row][column-1] == 2):
print('You\'ve sunk a ship!')
player[row][column] = 4
break
def check_win(player,countShips,playerNumber):
countSunks=0
for row in range(len(player)):
for column in range(len(player[row])):
if player[row][column] == 4:
countSunks+=1
if countSunks == countShips:
os.system("clear")
print(f"Player {playerNumber} wins!")
print("Game over!")
time.sleep(5)
return True
else:
return False
def get_limit():
print("Shooting phase")
try:
limit=int(input('Number of turns: '))
except ValueError:
print('Invalid input!')
limit=int(input('Number of turns: '))
while True:
if limit in range(5,51):
break
else:
print('Invalid input! (must be between 5-50)')
limit=int(input('Number of turns: '))
continue
return limit
def check_turn(limit,count):
if limit != count:
print(f'Turns left: {limit-count}')
return False
else:
print('No more turns, it\'s a draw!')
time.sleep(5)
return True
def shoot(player1,player2,countShips,boardSize):
limit=get_limit()
won=False
turn=False
count=1
used_player1=[]
used_player2=[]
while won is False and turn is False:
if count % 2 == 1:
os.system('clear')
print('Player 1')
print('\r')
print_board_shoot(player2,boardSize)
coordinate=valid_shoot(boardSize)
while True:
if coordinate in used_player1:
print('You already shoot this place!')
coordinate=valid_shoot(boardSize)
continue
else:
break
used_player1.append(coordinate)
shooting(player2,coordinate)
turn=check_turn(limit,count)
won=check_win(player2,countShips,1)
time.sleep(2)
os.system('clear')
else:
os.system('clear')
print('Player 2')
print('\r')
print_board_shoot(player1,boardSize)
coordinate=valid_shoot(boardSize)
while True:
if coordinate in used_player2:
print('You already shoot this place!')
coordinate=valid_shoot(boardSize)
continue
else:
break
used_player2.append(coordinate)
shooting(player1,coordinate)
turn=check_turn(limit,count)
won=check_win(player1,countShips,2)
time.sleep(2)
os.system('clear')
count += 1
def main():
os.system('clear')
boardSize = board_size()
os.system('clear')
player1, countShips = player1_place(boardSize)
os.system('clear')
letter = input("Next player's placement phase")
player2, countShips = player2_place(boardSize)
os.system('clear')
os.system('clear')
shoot(player1,player2, countShips,boardSize)
if __name__ == "__main__":
main()
|
d54bb314e4e1c0ad5a329c5c95f5cc71708409a4
|
[
"Python"
] | 1
|
Python
|
nembence/battleship
|
955240197409e74d8440767637a7e79658117455
|
568e3d32c2434d7bee2441cef6eae363b769c558
|
refs/heads/master
|
<repo_name>NetScrn/twitty<file_sep>/config/loader.rb
# frozen_string_literal: true
require 'rubygems'
require 'bundler/setup'
module Twitty
MODE = ENV['ENVIRONMENT'] || :development
Bundler.require :default, MODE
Dotenv.load
Sequel::Model.db = Sequel.connect(
adapter: :postgres,
host: 'localhost',
database: 'twitty_dev',
user: ENV.fetch('DB_USERNAME'),
password: ENV.fetch('<PASSWORD>')
)
require_all 'api'
require_all 'models'
end<file_sep>/api/twitty_api.rb
class TwittyAPI < Grape::API
format :json
get :index do
User.all.map(&:values)
end
end
<file_sep>/models/User.rb
class User < Sequel::Model(:users)
end
<file_sep>/Gemfile
# frozen_string_literal: true
source 'http://rubygems.org'
ruby '2.5.3'
gem 'grape'
gem 'grape-entity'
gem 'rack-cors'
gem 'dotenv'
gem 'pg'
gem 'rake'
gem 'require_all'
gem 'sequel'
group :development, :test do
gem 'pry'
gem 'faker', :git => 'https://github.com/stympy/faker.git', :branch => 'master'
end
<file_sep>/config.ru
# frozen_string_literal: true
require './config/loader'
require 'rack/cors'
use Rack::Cors do
allow do
origins 'localhost'
resource '*', headers: :any, methods: [:get, :post, :put, :delete]
end
end
run TwittyAPI.new
<file_sep>/Rakefile
# frozen_string_literal: true
require 'rubygems'
require 'bundler/setup'
Bundler.require :default, :development
Dotenv.load
DB_USERNAME = ENV['DB_USERNAME']
DB_PASSWORD = ENV['DB_PASSWORD']
DATABASE_NAME = 'twitty_dev'
namespace :db do
task :create do
db = Sequel.connect(
adapter: :postgres,
host: 'localhost',
database: 'postgres',
user: DB_USERNAME,
password: <PASSWORD>
)
db.run("create database #{DATABASE_NAME};")
db.run("grant all privileges on database #{DATABASE_NAME} to #{DB_USERNAME};")
end
task :drop do
db = Sequel.connect(
adapter: :postgres,
host: 'localhost',
database: 'postgres',
user: DB_USERNAME,
password: <PASSWORD>
)
db.run("drop database #{DATABASE_NAME};")
end
task :migrate, [:version] do |t, args|
db = Sequel.connect(
adapter: :postgres,
host: 'localhost',
database: DATABASE_NAME,
user: DB_USERNAME,
password: <PASSWORD>
)
Sequel.extension :migration
version = args[:version].to_i if args[:version]
Sequel::Migrator.run(db, 'config/db/migrations', target: version)
end
task :seed do
Sequel::Model.db = Sequel.connect(
adapter: :postgres,
host: 'localhost',
database: DATABASE_NAME,
user: DB_USERNAME,
password: <PASSWORD>
)
require_all 'models'
100.times do
username = Faker::Name.unique.name
email = Faker::Internet.unique.email
password = '<PASSWORD>'
User.create(username: username, email: email, password: <PASSWORD>)
end
end
end
|
4c1cd9ef1d8f3c700a7cb4ff5ab2c247472cbb82
|
[
"Ruby"
] | 6
|
Ruby
|
NetScrn/twitty
|
c74febba451d176eaddc346d576df918af536ea6
|
53aa10ee4520aa6ee47ccb4eed401fc5610cfc79
|
refs/heads/master
|
<file_sep>package com.example.zujianhuaapp.message.fragment;
/*
* 包名: com.example.zujianhuaapp.home.fragment
* Created by ASUS on 2018/2/15.
* 描述: TODO
*/
import android.view.View;
import android.widget.TextView;
import com.example.zujianhuaapp.base.BaseFragment;
public class MessageFragment extends BaseFragment{
private TextView textView;
@Override
public View initView() {
textView=new TextView(mcontext);
textView.setTextSize(18);
return textView;
}
@Override
public void initData() {
super.initData();
textView.setText("MessageFragment");
}
}
<file_sep>package com.example.zujianhuaapp;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.example.zujianhuaapp.base.BaseFragment;
import com.example.zujianhuaapp.home.fragment.HomeFragment;
import com.example.zujianhuaapp.message.fragment.MessageFragment;
import com.example.zujianhuaapp.mine.fragment.MineFragment;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private static final int REQUEST_QRCODE = 0x01;
private RelativeLayout mHomeLayout;
private RelativeLayout mPondLayout;
private RelativeLayout mMessageLayout;
private RelativeLayout mMineLayout;
private TextView mHomeView;
private TextView mPondView;
private TextView mMessageView;
private TextView mMineView;
private int position=0;
private ArrayList<BaseFragment> fragments;
private BaseFragment Fragment;
private BaseFragment baseFragment=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_layout);
initView();
initFragment();
}
@Override
protected void onResume() {
super.onResume();
}
private void initFragment() {
fragments = new ArrayList<>();
fragments.add(new HomeFragment());
fragments.add(new MessageFragment());
fragments.add(new MineFragment());
baseFragment = getFragment(position);
switchFragment(Fragment, baseFragment);
}
private void initView() {
mHomeLayout = (RelativeLayout) findViewById(R.id.home_layout_view);
mHomeLayout.setOnClickListener(this);
mPondLayout = (RelativeLayout) findViewById(R.id.pond_layout_view);
mPondLayout.setOnClickListener(this);
mMessageLayout = (RelativeLayout) findViewById(R.id.message_layout_view);
mMessageLayout.setOnClickListener(this);
mMineLayout = (RelativeLayout) findViewById(R.id.mine_layout_view);
mMineLayout.setOnClickListener(this);
mHomeView = (TextView) findViewById(R.id.home_image_view);
mPondView = (TextView) findViewById(R.id.fish_image_view);
mMessageView = (TextView) findViewById(R.id.message_image_view);
mMineView = (TextView) findViewById(R.id.mine_image_view);
mHomeView.setBackgroundResource(R.drawable.comui_tab_home_selected);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.home_layout_view:
mHomeView.setBackgroundResource(R.drawable.comui_tab_home_selected);
mPondView.setBackgroundResource(R.drawable.comui_tab_pond);
mMessageView.setBackgroundResource(R.drawable.comui_tab_message);
mMineView.setBackgroundResource(R.drawable.comui_tab_person);
position = 0;
baseFragment= getFragment(position);
switchFragment(Fragment, baseFragment);
break;
case R.id.message_layout_view:
mMessageView.setBackgroundResource(R.drawable.comui_tab_message_selected);
mHomeView.setBackgroundResource(R.drawable.comui_tab_home);
mPondView.setBackgroundResource(R.drawable.comui_tab_pond);
mMineView.setBackgroundResource(R.drawable.comui_tab_person);
position = 1;
baseFragment = getFragment(position);
switchFragment(Fragment, baseFragment);
break;
case R.id.mine_layout_view:
mMineView.setBackgroundResource(R.drawable.comui_tab_person_selected);
mHomeView.setBackgroundResource(R.drawable.comui_tab_home);
mPondView.setBackgroundResource(R.drawable.comui_tab_pond);
mMessageView.setBackgroundResource(R.drawable.comui_tab_message);
position = 2;
baseFragment = getFragment(position);
switchFragment(Fragment, baseFragment);
break;
}
}
private BaseFragment getFragment(int position) {
if (fragments != null && fragments.size() > 0) {
BaseFragment baseFragment = fragments.get(position);
return baseFragment;
}
return null;
}
private void switchFragment(Fragment fromFragment, BaseFragment nextFragment) {
if (Fragment != nextFragment) {
Fragment = nextFragment;
if (nextFragment != null) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
//判断nextFragment是否添加
if (!nextFragment.isAdded()) {
//隐藏当前Fragment
if (fromFragment != null) {
transaction.hide(fromFragment);
}
transaction.add(R.id.content_layout, nextFragment).commit();
} else {
//隐藏当前Fragment
if (fromFragment != null) {
transaction.hide(fromFragment);
}
transaction.show(nextFragment).commit();
}
}
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
/*switch (requestCode) {
case REQUEST_QRCODE:
if (resultCode == Activity.RESULT_OK) {
String code = data.getStringExtra("SCAN_RESULT");
Log.i("HomeFragment",code);
code="http://www.baidu.com";
if (code.contains("http") || code.contains("https")) {
Intent intent = new Intent(mcontext, AdBrowserActivity.class);
intent.putExtra(AdBrowserActivity.KEY_URL, code);
startActivity(intent);
} else {
Toast.makeText(mcontext, code, Toast.LENGTH_SHORT).show();
}
}
break;
}*/
if (requestCode == REQUEST_QRCODE && resultCode == RESULT_OK) {
if (data != null) {
String content = data.getStringExtra("SCAN_RESULT");
Log.i("HomeFragment",content);
Toast.makeText(MainActivity.this, content, Toast.LENGTH_SHORT).show();
}
}
}
}
<file_sep>package com.example.zujianhuaapp.base;
/*
* 包名: com.example.zujianhuaapp.base
* Created by ASUS on 2018/2/15.
* 描述: TODO
*/
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.zujianhuaapp.utils.Constant;
public abstract class BaseFragment extends Fragment {
public Context mcontext;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mcontext=getActivity();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return initView();
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initData();
}
public void initData() {
}
public abstract View initView() ;
/**
* 申请指定的权限.
*/
public void requestPermission(int code, String... permissions) {
if (Build.VERSION.SDK_INT >= 23) {
requestPermissions(permissions, code);
}
}
/**
* 判断是否有指定的权限
*/
public boolean hasPermission(String... permissions) {
for (String permisson : permissions) {
if (ContextCompat.checkSelfPermission(getActivity(), permisson)
!= PackageManager.PERMISSION_GRANTED) {
return false;
}
}
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Constant.HARDWEAR_CAMERA_CODE:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
doOpenCamera();
}
break;
case Constant.WRITE_READ_EXTERNAL_CODE:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
doWriteSDCard();
}
break;
}
}
public void doOpenCamera() {
}
public void doWriteSDCard() {
}
}
<file_sep>package com.example.zujianhuaapp.module.mina;
import com.example.zujianhuaapp.module.BaseModel;
/**
* Created by renzhiqiang on 16/8/20.
*/
public class MinaModel extends BaseModel {
public int ecode;
public String emsg;
public MinaContent data;
}
<file_sep>package com.example.zujianhuaapp.module.recommand;
/*
* 包名: com.example.zujianhuaapp.module.recommand
* Created by ASUS on 2018/6/15.
* 描述: TODO
*/
public class home_data {
}
<file_sep>include ':app', ':shiping'
<file_sep>package com.example.zujianhuaapp.module.update;
import com.example.zujianhuaapp.module.BaseModel;
/**
* Created by renzhiqiang on 16/8/23.
*/
public class UpdateInfo extends BaseModel {
public int currentVersion;
}
<file_sep>apply plugin: 'com.android.application'
apply plugin: 'com.mob.sdk'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.example.zujianhuaapp"
minSdkVersion 16
targetSdkVersion 26
versionCode 1
versionName "1.0"
flavorDimensions "1"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true //突破应用方法数65535的一个限制
}
signingConfigs {
debug {}
//签名打包
release {
storeFile file("youdo.jks")
storePassword "<PASSWORD>"
keyAlias "qndroid"
keyPassword "<PASSWORD>"
}
}
buildTypes {
debug {
minifyEnabled false //这是关键的,我的问题就是出在这里
proguardFiles getDefaultProguardFile('proguard-android.txt')
signingConfig signingConfigs.release
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
/* //指定我们release包的输出文件名就是我们的渠道名字
applicationVariants.all { variant ->
variant.outputs.each { output ->
def outputFile = output.outputFile
if (outputFile != null && outputFile.name.endsWith(".apk")) {
def fileName = "${variant.productFlavors[0].name}" + ".apk"
output.outputFile = new File(outputFile.parent, fileName);
}
}
}*/
/* android.applicationVariants.all { variant ->
variant.outputs.all {
outputFileName = "${variant.productFlavors[0].name}.apk"
}
}*/
}
sourceSets {
main {
jniLibs.srcDirs = ['libs']
}
}
/* //真正的多渠道脚本支持
productFlavors {
xiaomi { manifestPlaceholders = [UMENG_CHANNEL_VALUE: "xiaomi"] }
}*/
/*为了简单可以用脚本去替换重复代码
productFlavors.all {
flavor -> flavor.manifestPlaceholders = [UMENG_CHANNEL_VALUE: name]*/
}
MobSDK {
appKey "<KEY>"
appSecret "a18f0704fd2a4536eb2a24a45d0db796"
ShareSDK {
//平台配置信息
devInfo {
Wechat {
appId "wx4868b35061f87885"
appSecret "64020361b8ec4c99936c0e3999a9f249"
bypassApproval true
enable true
}
WechatMoments {
appId "wx4868b35061f87885"
appSecret "64020361b8ec4c99936c0e3999a9f249"
bypassApproval true
enable true
}
QQ {
appId "100371282"
appKey "aed9b0303e3ed1e27bae87c33761161d"
}
QZone {
appId "100371282"
appKey "aed9b0303e3ed1e27bae87c33761161d"
shareByAppClient true
bypassApproval false
enable true
}
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'de.hdodenhof:circleimageview:2.1.0'
implementation 'com.readystatesoftware.systembartint:systembartint:1.0.3'
implementation 'com.squareup.okhttp3:okhttp:3.3.0'
//okttp依赖
implementation 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'
implementation('cn.trinea.android.view.autoscrollviewpager:android-auto-scroll-view-pager:1.1.2') {
exclude module: 'support-v4'
}
implementation 'com.github.chrisbanes:PhotoView:2.0.0'
compile project(path: ':shiping')
implementation files('libs/jcore-android-1.2.1.jar')
implementation files('libs/jpush-android-3.1.3.jar')
/*compile 'com.umeng.sdk:common:latest.integration'
compile 'com.umeng.sdk:analytics:latest.integration'*/
/*添加依赖*/
}
<file_sep>package com.example.zujianhuaapp.base;
/*
* 包名: com.example.zujianhuaapp.base
* Created by ASUS on 2018/6/14.
* 描述: TODO
*/
import android.app.Application;
import com.mob.MobSDK;
import cn.jpush.android.api.JPushInterface;
public class BaseApplication extends Application{
private static BaseApplication baseApplication;
@Override
public void onCreate() {
super.onCreate();
baseApplication=this;
MobSDK.init(this);
JPushInterface.setDebugMode(true);
JPushInterface.init(this);
/*
UMConfigure.init(this,UMConfigure.DEVICE_TYPE_PHONE, null);*/
}
public static BaseApplication getInstance(){
return baseApplication;
}
}
|
3cc0592d5d5953c5cb00011040a1619a56013384
|
[
"Java",
"Gradle"
] | 9
|
Java
|
bixingjun/zujiahuaapp
|
9ec87062c7cc151a017f6c2283acfc330e43950a
|
a4a0ea4c11ac8c7a2fc3b242c368825d76b91c21
|
refs/heads/master
|
<file_sep>package Pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindAll;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.FindBys;
import java.util.*;
public class CommonTabElements {
WebDriver driver;
@FindBy(xpath = "//*[contains(text(),'Color')]//parent::*[@class='layered_subtitle_heading']//following-sibling::*")
WebElement colorsTable;
@FindBy(css = "#layered_price_range")
WebElement priceRange;
@FindAll(@FindBy(css = ".right-block .price"))
List<WebElement> priceRanges;
@FindAll(@FindBy(css = ".color_pick"))
List<WebElement> colorPicks;
@FindAll(@FindBy(css = ".color-option"))
List<WebElement> colorOptions;
@FindAll(@FindBy(css = ".layered_color span"))
List<WebElement> countsWebElements;
public CommonTabElements(WebDriver driver) {
this.driver = driver;
}
public int getColorsCount(String color) {
String count = colorsTable
.findElement(By.xpath(
String.format("//a[text()='%s']//*",color)))
.getText();
count = count.replaceAll("[()]","");
return Integer.parseInt(count);
}
public List<Integer> getColorsCounts() {
List<Integer> counts = new ArrayList<>();
countsWebElements.forEach(element -> {
counts.add(
Integer.parseInt(
element.getAttribute("innerText")
.replaceAll("[()]", "").trim())
);
});
return counts;
}
public Dictionary<String,Integer> getColorsAndCounts(){
List<Integer> colorCounts = getColorsCounts();
Dictionary<String,Integer> colorsAndCounts = new Hashtable<>();
for(int i = 0; i<colorOptions.size();i++){
colorsAndCounts.put(colorOptions.get(i).getCssValue("background-color"),colorCounts.get(i));
}
return colorsAndCounts;
}
public List<WebElement> getColorPickList(String color){
List<WebElement> colorPicks = driver.findElements(By.cssSelector(
String.format(".color_pick[href$='%s']",color.toLowerCase())));
return colorPicks;
}
public Dictionary<String, Integer> getColorPicksAndCounts(){
Dictionary<String, Integer> colorPicksAndCounts= new Hashtable<>();
List<String> tmp = new ArrayList<>();
for (int i = 0; i < colorPicks.size(); i++) {
tmp.add(
colorPicks.get(i).getCssValue("background-color")
);
}
Collections.sort(tmp);
int counter = 1;
for (int i = 0; i < tmp.size(); i++) {
if(i==tmp.size()-1){
colorPicksAndCounts.put(tmp.get(i),counter);
break;
}
if(tmp.get(i).equals(tmp.get(i+1))){
counter++;
continue;
}
colorPicksAndCounts.put(tmp.get(i),counter);
counter=1;
}
return colorPicksAndCounts;
}
public List<String> getSliderPriceRange(){
String innerText = priceRange.getAttribute("innerText");
List<String> ranges = Arrays.asList(innerText.split(" - "));
ranges.replaceAll(e->e.replaceAll("\\$",""));
Collections.sort(ranges);
return ranges;
}
public List<String> getItemsPriceRange(){
List<String> prices = new ArrayList<>();
priceRanges.forEach(element-> {
prices.add(
element.getText()
.replaceAll("\\$","")
);
});
Collections.sort(prices);
return prices;
}
}
|
09bfcd635022ebb9261ea49ce789a1ffb718a1e9
|
[
"Java"
] | 1
|
Java
|
VladOstk/PageObjPageFact
|
cf6f55ba91f570090d2d172ac3ee745f564f2b3a
|
acd0952da37524dac6b939226b99eab0b5c29bed
|
refs/heads/master
|
<file_sep>//project 1 fullscreen
$(document).ready(function(){
$("figure[id='project1']").click(function(){
$("figure[id!='project1']").hide(); //hide all figure but project 1
$("info[id!='project1Info']").hide(); //hide all info but project info 1
$("#projectsContainer").css({"max-height":"100vv", "display":"flex", "flex-direction": "column", "align-items":"center"}); //making container flex
$(this).css({"height":"70%", "background-color":"rgba(196,219,224,1)"}); //changing figure style
$("#project1Info").append($("#project1")); //appending figure into info
$("#project1Info").animate({
height: "100%",
width: "80%",
padding: "2% 5%",
margin: "0",
"align-content": "space-between",
},"slow"); //enlarging info
$("#project1Info").prepend(exitButton); //adding the exit button
});
});
//project 2 fullscreen
$(document).ready(function(){
$("#project2").click(function(){
$("figure[id!='project2']").hide();
$("info[id!='project2Info']").hide();
$("#projectsContainer").attr({style: 'max-height:100vv; display:flex; flex-direction: column; align-items:center;'});
$(this).attr({style: "height:70%; background-color:rgba(196,219,224,1);"});
$("#project2Info").append($("#project2"));
$("#project2Info").animate({
height: "100%",
width: "80%",
padding: "2% 5%",
margin: "0",
"align-content": "space-between",
},"slow");
$("#project2Info").prepend(exitButton);
});
});
//project 3 fullscreen
$(document).ready(function(){
$("#project3").click(function(){
$("figure[id!='project3']").hide();
$("info[id!='project3Info']").hide();
$("#projectsContainer").attr({style: 'max-height:100vv; display:flex; flex-direction: column; align-items:center;'});
$(this).attr({style: "height:70%; background-color:rgba(196,219,224,1);"});
$("#project3Info").append($("#project3"));
$("#project3Info").animate({
height: "100%",
width: "80%",
padding: "2% 5%",
margin: "0",
"align-content": "space-between",
},"slow");
$("#project3Info").prepend(exitButton);
});
});
const exitButton = $("<button id='exitButton'></button>").text("X");
//made for only project 1 currently
$(document).ready(function(){
$(exitButton).click(function(){
$(this).hide();
$("figure[id!='project1']").toggle();
$("info[id!='project1Info']").toggle();
$("#project1").css({"background-color": "#00A8A8", "height": "auto"});
const project = $("#project1").clone();
// $(project).removeAttr("style");
$("#project1").hide();
$(project).prependTo("#projectsContainer");
$("#project1Info").removeAttr("style");
$("#project1Info").css({"background-color": "rgba(196,219,224,0.8)", "display": "block", "margin": "10% 10%", "border-radius": "10px", "padding": "5px", "z-index": "5", "grid-area": "3 / 2 / 4 / 5", "width":"auto", "height":"auto","align-content": "null"});
$("#projectsContainer").css({"width": "50%", "min-height" : "100%", "background-color" : "#2EB5E0", "text-align" : "center", "display" : "grid", "grid-template-areas" : "repeat(8, 1fr)/repeat(4, 1fr)", "grid-auto-flow" : "row", "overflow-y" : "scroll", "overflow-x" : "hidden", "max-height" :"null", "flex-direction": "null", "align-items": "null"});
});
});
|
0b78bb5790516cebe2fa16673778510f569cfeec
|
[
"JavaScript"
] | 1
|
JavaScript
|
krisbucz/portfolio-website
|
08330cf8df3f2190b7fc42ffa64fe28f34488b1a
|
a566e254a9141cd8580313dcfdcda265d2a70b4d
|
refs/heads/master
|
<repo_name>KnisterPeter/lcov-sourcemap<file_sep>/lib/cli.js
#!/usr/bin/env node
var minimist = require("minimist");
var glob = require("glob");
var lcovSourcemap = require("./index");
var path = require("path");
var args = minimist(process.argv.slice(2));
if (!args["lcov"] || !args["source-dir"] || !args["source-maps"]) {
usage();
}
if (!isArray(args["source-maps"])) {
args["source-maps"] = [args["source-maps"]];
}
var sourceMaps = Array.prototype.concat.apply([], args["source-maps"].map(function(dir) {
return glob.sync(dir);
})).reduce(function(map, file) {
map[file] = file;
return map;
}, {});
lcovSourcemap(args["lcov"], sourceMaps, args["source-dir"]).then(function (lcov) {
console.log(lcov);
});
function isArray(input) {
return Object.prototype.toString.call(input) == "[object Array]";
}
function usage() {
console.error("Usage: lcov-sourcemap --lcov <path/to/lcov-file> --source-dir <path/to/sources> --source-maps <glob/for/source-maps>");
console.error("\t--source-maps could be specified multiple times");
process.exit(1);
}
|
a6bb30fc716e78895ce4556bccc3f63d9605ed4e
|
[
"JavaScript"
] | 1
|
JavaScript
|
KnisterPeter/lcov-sourcemap
|
9dee7222dd1a79099c60124e31ed31e4fe014c0d
|
6b855b5f9897b05d633b41d549b105adb8568892
|
refs/heads/master
|
<file_sep>dofile( lfs.writedir() .. 'Scripts/MooseServer/Statistics.lua' )
<file_sep># MOOSE SERVER STATISTICS project
MOOSE Server Statistics project for DCS World servers beyond DCS 1.5 and DCS 2.0
HubJack: The MOOSE Server Statistics code is WIP and is not useful at the moment. Work is done on the code every day but running tests and debugging on private server. Master will be updated as soon as a new tested version is running stable on the private server. So for now please comment and contribute but be careful if you plan to use the master build.
The project aims to create a statistics central for flight logging based on each pilot’s flight time. The statistics will be collected for multiple server instances and can be used by all DCS World servers. By registering your server with MOOSE we will provide all the code to bring all your statistics over to the central server and implement it in the main statistics log. Statistics will by standard be focused on teamwork rather than individual performance but as a registered member of the MOOSE Server Statistics providers you can request PHP pages that individually view scores for your server. The MOOSE Server Statistics project will provide all code to locally create the needed .csv files so you can build your own webserver if you like. The webpage and MySQL setup is highly individual and will not be provided in the GitHub MOOSE Server project. If your team plan on setting up your own DCS World statistics page based on APACHE, MySQL(MariaDB), PHP and FTP we may give information on how to get started. Please contact us at Slack MOOSE.
MOOSE Server now writes logs to it's own directory for easy pickup and move to webserver. The directory is in the servers "Saved Games/DCS" folder and named "MooseLogs". The directory recreates itself when needed so you can rename it before moving. Please remember that DCS World must be stopped to rename the folder.
MOOSE SERVER DONE: Export of Mission data, player data and event data. Recording of player takeoff and landing
is now working (please se image "Server_settings_1.png" in main fileslist). Finished reading local server info. Solved problem with player "connect" and "disconnect" events. MOOSE Server Statistics now loggs a complete picture of the users events on the server. The codein will now turn more towards MySQL and transport of files to a sentral web server. Will edit the current script to add "Version 1.0" to the heading.
EXTEND ONE: To extend the statistics you can use the MOOSE statistics framework in your mission and get the recorded .csv file. This solution will provide extended statistics also including objective score.
EXTEND TWO: You can also use Tacview recored file by running the Tacview export commandline. Please see Tacview webpage for information on how to export the reecorded information to a .csv file.
MOOSE SERVER WIP: Error logging (if needed), programming past DCS bugs, May need to get the chat to go around DCS bugs on this one.
Need to implement version number on the file heading.
WEBSITE WIP: adjusting info export to .csv files, preparing file transport to webserver, testing MySQL server import, building MySQL views, creating simple stats webpage in PHP.
MOOSE SERVER FUTURE DEVELOPMENT priority list:
1. Collect MOOSE mission statistics file (.csv) that will enable kill and weapons usage together with optional scoring details.
2. Link public server play to the shared tacview file of each recorded round.
3. Personal player accounts on the MOOSE central statistics server to keep recordings of your local single player flights.
4. Make personal account admin for player to select which flights should be public statistics or private (test flights etc.).
5. To be decided...
Regards, HubJack
(this project is also a learning project for me to use GitHub's features. Thank you flightControl)
<file_sep>do -- start do loop (main)
local MooseCallBacks = {}
net.log('MOOSE Server Statistics logfile are loading...')
-- MOOSE Server Statistics version 1.0 - HubJack
-- TASK: Use functions LoGetObjectById and LoGetPlayerPlaneId to get players aircraft.
-- TASK: Use DCS.getUnitProperty(missionId, propertyId) with 4 as propertyId to get unittype returned
-- TASK: use net.get_server_id() to identify server admin user and get the server IP address. Use: net.get_player_info(playerID)
-- TASK: Current player list. Use net.get_player_list() -> array of playerID to Returns the list of currently connected players.
local MooseLogsDir = lfs.writedir() .. [[MooseLogs]]
local MooseConfigDir = lfs.writedir() ..[[Scripts/MooseServer]]
local t_serverConfig = {}
local owner_ownerID="1234"
local owner_serverIP="unknown IP"
local owner_serverName="unknown name"
local owner_serverUCID="unknown UCID"
-- !!!! global logging configuration START
moose_servlog = MooseLogsDir.."/MooseServerlog.log"
mooselogger, logerr = io.open(moose_servlog, "w")
if not mooselogger then
net.log("ERROR: Could not create MOOSE Server Statistics logfile. Error: ".. logerr)
else
net.log("MOOSE Server Statistics logfile: "..moose_servlog)
end
function log_write(str)
if nil==str then return end
if mooselogger then
mooselogger:write(os.date("%c") .. " : " .. str,"\r\n")
mooselogger:flush()
end
end
-- !!!! global logging configuration END
log_write("MOOSE logging enabled: FIRST LINE AFTER LOG CONFIG")
lfs.mkdir(MooseLogsDir)
local loadID = tostring(os.date("%Y%m%d%H%M%S"))
local loadDate = tostring(os.date("%Y-%m-%d"))
local loadTime = tostring(os.date("%H:%M:%S"))
local roundID = loadID
roundCount = 0
local function load_serverConfig() -- loads server config file with owner information.
log_write('moose:load_serverConfig: first line in function')
file = MooseConfigDir .. '/serverConfig.cfg'
local f = io.open(file, "r")
if f then
f:close()
log_write('moose:load_serverConfig: FILE exist. ')
else
log_write('moose:load_serverConfig: FILE does NOT exist. ')
end
local confFile, conferr = io.open(MooseConfigDir .. '/serverConfig.cfg', 'r')
-- log_write('moose: read config file lines to variables: start')
local lines = {}
if not confFile then
return
else
for line in io.lines(confFile) do
if line:match("ownerID=(.+)") ~= nil then
owner_ownerID = tostring(line:match("ownerID=(.+)"))
end
if line:match("serverIP=(.+)") ~= nil then
owner_serverIP = tostring(line:match("serverIP=(.+)"))
end
if line:match("serverName=(.+)") ~= nil then
owner_serverName = tostring(line:match("serverName=(.+)"))
end
if line:match("serverUCID=(.+)") ~= nil then
owner_serverUCID = tostring(line:match("serverUCID=(.+)"))
end
lines[#lines + 1] = line
end
end
-- log_write('moose: read config file lines to variables: finished')
end
function MooseCallBacks.onNetConnect(localPlayerID)
log_write('moose:onNetConnect: FIRST line in function')
local loadConfig = 0
if loadConfig >= 0 then
load_serverConfig()
loadConfig = 1
end
mlog = io.open(lfs.writedir() .. "MooseLogs/missioninfo_" .. loadID .. ".csv", "w")
mlog:write('serverIP, loadID, roundID, startTime, missionName\n')
plog = io.open(lfs.writedir() .. "MooseLogs/playerinfo_" .. loadID .. ".csv", "w")
plog:write( 'serverIP, loadID, roundID, playerTime, PlayerUCID, PlayerName, PlayerIP\n')
log_write('MOOSE:logging enabled: ' ..moose_servlog)
log_write('moose:onNetConnect: LAST line in function')
end
function MooseCallBacks.onNetMissionChanged(newMissionName)
log_write('moose:onNetMissionChanged: FIRST line in function')
-- Using this function to close round files and roll ower to new round info.
local missionName = tostring(newMissionName)
log_write('moose:onNetMissionChanged mission name: ' ..missionName)
roundID = tostring(os.date("%Y%m%d%H%M%S"))
local startTime = tostring(os.date("%Y-%m-%d %H:%M:%S"))
local simTime = DCS.getModelTime()
mlog:write( string.format( '"%s", "%s", "%s", "%s", "%s"\n', owner_serverIP, loadID, roundID, startTime, missionName))
if roundCount == 0 then
rlog = io.open(lfs.writedir() .. "MooseLogs/roundinfo_" .. loadID .. ".csv", "w")
rlog:write( "serverIP, loadID, roundID, playerTime, simTime, eventName, PlayerName\n")
roundCount = 1
else
rlog:close()
rlog = nil
rlog = io.open(lfs.writedir() .. "MooseLogs/roundinfo_" .. roundID .. ".csv", "w")
rlog:write( "serverIP, loadID, roundID, playerTime, simTime, eventName, PlayerName\n")
end
end
function MooseCallBacks.onNetDisconnect(reason_msg, err_code)
log_write('moose:onNetDisconnect: FIRST line in function')
-- closes opened files so they can be moved over to webserver
if rlog then
rlog:close() -- Closes round log if present.
rlog = nil
end
if mlog then
mlog:close() -- Closes mission log if present.
mlog = nil
end
if plog then
plog:close() -- Closes player log if present.
plog = nil
end
if mooselogger then
mooselogger:close() -- Closes player log if present.
mooselogger = nil
end
end
function MooseCallBacks.onPlayerTryConnect(addr, name, ucid, playerID)
-- don't use this function for anything at the moment, just keep it here.
return true -- allow the player to connect
end
function MooseCallBacks.onPlayerStart(id)
-- Not used at this time!!!!
end
function MooseCallBacks.onPlayerChangeSlot(id)
--a player successfully changed the slot. Not needed at the moment, just keep it here.
-- log_write('moose:onPlayerChangeSlot: FIRST line in function')
-- local PlayerName = net.get_player_info( id, "name" )
end
function MooseCallBacks.onPlayerConnect(id, name)
log_write('moose:onPlayerConnect: first line in function')
local playerTime = tostring(os.date("%Y-%m-%d %H:%M:%S"))
local PlayerName = net.get_player_info( id, 'name' )
local PlayerIP = net.get_player_info( id, 'ipaddr' )
local PlayerUCID = net.get_player_info( id, 'ucid' )
plog:write(string.format( '"%s", "%s", "%s", "%s", "%s", "%s", "%s"\n', owner_serverIP, loadID, roundID, playerTime, PlayerUCID, PlayerName, PlayerIP))
log_write('moose:onPlayerConnect: LAST line in function')
return
end
function MooseCallBacks.onSimulationStart()
-- log_write('moose:onSimulationStart: first line in function')
-- Not used at this time!!!!
end
function MooseCallBacks.onMissionLoadBegin()
-- log_write('moose:onMissionLoadBegin: first line in function')
-- Not used at this time!!!!
end
function MooseCallBacks.onMissionLoadEnd()
-- log_write('moose:onMissionLoadEnd: first line in function')
-- Not used at this time!!!!
end
function MooseCallBacks.onGameEvent( eventName, arg1, arg2, arg3, arg4 )
log_write('moose:onGameEvent: first line in function. Event: ' ..eventName)
--"friendly_fire", playerID, weaponName, victimPlayerID
--"mission_end", winner, msg
--"kill", killerPlayerID, killerUnitType, killerSide, victimPlayerID, victimUnitType, victimSide, weaponName
--"self_kill", playerID
--"change_slot", playerID, slotID, prevSide
--"connect", id, name
--"disconnect", ID_, name, playerSide
--"crash", playerID, unit_missionID
--"eject", playerID, unit_missionID
--"takeoff", playerID, unit_missionID, airdromeName
--"landing", playerID, unit_missionID, airdromeName
--"pilot_death", playerID, unit_missionID
-- net.log('moose_test_getUnitType: ' ..MooseCallBacks.getUnitType(missionId))
-- Use function onGameEvent(eventName,arg1,arg2,arg3,arg4) for disconnect event to log actual time on server.
-- "disconnect", ID_, name, playerSide, reason_code
-- eventName == "connect" or eventName == "disconnect"
if eventName == "self_kill" or eventName == "change_slot" or eventName == "crash" or eventName == "eject" or eventName == "takeoff" or eventName == "landing" or eventName == "pilot_death" then
local simTime = DCS.getModelTime()
local playerTime = tostring(os.date("%Y-%m-%d %H:%M:%S"))
local PlayerName = net.get_player_info( arg1, "name" )
rlog:write( string.format( '"%s", "%s", "%s", "%s", "%8f", "%s", "%s"\n', owner_serverIP, loadID, roundID, playerTime, simTime, eventName, PlayerName ) )
end
if eventName == "connect" or eventName == "disconnect" then
local simTime = DCS.getModelTime()
local playerTime = tostring(os.date("%Y-%m-%d %H:%M:%S"))
local PlayerName = tostring(arg2)
rlog:write( string.format( '"%s", "%s", "%s", "%s", "%8f", "%s", "%s"\n', owner_serverIP, loadID, roundID, playerTime, simTime, eventName, PlayerName ) )
end
-- log_write('moose:onGameEvent: LAST line in function. Event: ' ..eventName)
end
net.log('MOOSE:Server Statistics logfile was loaded successfully.')
DCS.setUserCallbacks( MooseCallBacks ) -- here we set our callbacks
log_write("MOOSE:logging enabled: LAST LINE IN DO LOOP - script file is now loaded")
end -- end do loop
|
00f3da2a8d24c4d2fed2e2da23606f9702d93d16
|
[
"Markdown",
"Lua"
] | 3
|
Lua
|
FlightControl-Master/MOOSE_SERVER
|
8d1da13696350ec34b3b0c8ff05e4100d05d529b
|
fbdd8968268e7c372983359ea2bc1109d0f4e5c3
|
refs/heads/main
|
<repo_name>SDonaldsonUSC/R-Code-Repository<file_sep>/MTMM Project/BuildingBlocks.Rmd
---
title: "Building Blocks of PERMA Beyond Self-Report Bias"
author: "<NAME>, Ph.D"
date: "6/18/2020"
output: html_document
---
#Data Management
```{r Data Manipulation and Cleaning, echo=FALSE}
#Upload packages
library(haven)
library(careless)
library(tidyverse)
library(psych)
library(Hmisc)
library(magrittr)
library(pastecs)
library(QuantPsyc)
#Import from SPSS
MTMM_Clean <- read_sav("MTMM.Clean.sav")
View(MTMM_Clean)
MTMM.ID <- MTMM_Clean %>% mutate(id = row_number())
Demos <- MTMM.ID[, c(82:100, 165:189, 259:277, 347:371, 383)]
#Remove careless responding
data.frame(colnames(MTMM.ID)) ##Keep track of all scale items for EMP1(C) and EMP1(C)
Final <- MTMM.ID[, c(11:81, 101:164, 190:258, 278:346, 383)]
##Mahal Distance (Across Pairs)
data.frame(colnames(Final))
MD <- mahad(Final, flag = TRUE, confidence = 0.999)
filter(MD, flagged == TRUE)
Final2 <- Final[-c(165), ]
##Longstring Invariant Responding
data.frame(colnames(Final2))
###EMP1 Lonstring
EMP1.L <- Final2[ , c(136:204, 274)]
longstring_EMP1 <- longstring(EMP1.L)
longstring_EMP1 <- as.data.frame(longstring_EMP1)
boxplot(longstring_EMP1)
quantile(longstring_EMP1$longstring_EMP1)
table(longstring_EMP1)
###EMP1C Longstring
EMP1C.L <- Final2[ , c(205:273)]
longstring_EMP1C <- longstring(EMP1C.L)
longstring_EMP1C <- as.data.frame(longstring_EMP1C)
boxplot(longstring_EMP1C)
quantile(longstring_EMP1C$longstring_EMP1C)
table(longstring_EMP1C)
#Clean up workspace
rm(list = "EMP1.L", "EMP1C.L", "EMP1.L", "EMP1C.L",
"Final", "longstring_EMP1" , "longstring_EMP1C",
"longstring_EMP1" , "longstring_EMP1C", "MD",
"MTMM_Clean", "MTMM.ID")
#Relational Data (Join the demos with ID variable)
##We want to join the scale data with Final.pairs to demographic data from MTMM_Clean
Final.Pairs2 <- Final2 %>% left_join(Demos, by = "id")
Final2 <- Final.Pairs2
rm(Final.Pairs2)
data.frame(colnames(Final2))
```
```{r Scaling PERMA+4 and SWLS for E1 + E2C}
ScaleData <- Final2
##EMP1 - PERMA+4 and SWB
ScaleData <- mutate(Final2,
PREL.Scale.E1 = (PREL_1_EMP1 + PREL_2_EMP1 + PREL_3_EMP1 +
PREL_4_EMP1)/4,
PE.Scale.E1 = (PE_1_EMP1 + PE_2_EMP1 + PE_3_EMP1)/3,
PMEAN.Scale.E1 = (PMEAN_1_EMP1 + PMEAN_2_EMP1 + PMEAN_3_EMP1)/3,
PACCOM.Scale.E1 = (PACCOM_1_EMP1 + PACCOM_2_EMP1 + PACCOM_3_EMP1)/3,
PEN.Scale.E1 = (PEN_1_EMP1 + PEN_2_EMP1 + PEN_3_EMP1)/3,
PECON.Scale.E1 = (PECON_1_EMP1 + PECON_2_EMP1 + PECON_3_EMP1)/3,
PMIND.Scale.E1 = (PMIND_1_EMP1 + PMIND_2_EMP1 + PMIND_3_EMP1)/3,
PHEALTH.Scale.E1 = (PPHealth_1_EMP1 + PPHealth_2_EMP1 + PPHealth_3_EMP1 +
PPHealth_4_EMP1)/4,
PPWE.Scale.E1 = (PPWE_1_EMP1 + PPWE_2_EMP1 + PPWE_3_EMP1)/3,
PF.W.Scale.E1 = (PREL.Scale.E1 + PE.Scale.E1 + PMEAN.Scale.E1 +
PACCOM.Scale.E1 + PEN.Scale.E1 + PECON.Scale.E1 +
PMIND.Scale.E1 + PHEALTH.Scale.E1 + PPWE.Scale.E1)/9,
SWLS.E1 = (SWL_1_EMP1 + SWL_2_EMP1 +SWL_3_EMP1 + SWL_4_EMP1 + SWL_5_EMP1)/5,
#Add coworker
PREL.Scale.E2C = (PREL_1_EMP2_C + PREL_2_EMP2_C + PREL_3_EMP2_C +
PREL_4_EMP2_C)/4,
PE.Scale.E2C = (PE_1_EMP2_C + PE_2_EMP2_C + PE_3_EMP2_C)/3,
PMEAN.Scale.E2C = (PMEAN_1_EMP2_C + PMEAN_2_EMP2_C + PMEAN_3_EMP2_C)/3,
PACCOM.Scale.E2C = (PACCOM_1_EMP2_C + PACCOM_2_EMP2_C + PACCOM_3_EMP2_C)/3,
PEN.Scale.E2C = (PEN_1_EMP2_C + PEN_2_EMP2_C + PACCOM_2_EMP2_C)/3,
PECON.Scale.E2C = (PECON_1_EMP2_C + PECON_2_EMP2_C + PECON_3_EMP2_C)/3,
PMIND.Scale.E2C = (PMIND_1__EMP2_C + PMIND_2_EMP2_C + PMIND_3_EMP2_C)/3,
PHEALTH.Scale.E2C = (PPHealth_1_EMP2_C + PPHealth_2_EMP2_C + PPHealth_3_EMP2_C +
PPHealth_4_EMP2_C)/4,
PPWE.Scale.E2C = (PPWE_1_EMP2_C + PPWE_2_EMP2_C + PPWE_3_EMP2_C)/3,
PF.W.Scale.E2C = (PREL.Scale.E2C + PE.Scale.E2C + PMEAN.Scale.E2C +
PACCOM.Scale.E2C + PEN.Scale.E2C + PECON.Scale.E2C +
PMIND.Scale.E2C + PHEALTH.Scale.E2C + PPWE.Scale.E2C)/9,
SWLS.E2C = (SWL_1__EMP2_C + SWL_2__EMP2_C +SWL_3__EMP2_C + SWL_4__EMP2_C +
SWL_5__EMP2_C)/5
)
```
```{r Employee 1 Demos}
##Subset only Scale Scores and Demographics
data.frame(colnames(ScaleData))
TidyData <- ScaleData[, c(274:293, 363:384)]
TidyData$Ethnicity_EMP1_2[TidyData$Ethnicity_EMP1_2 %in% 1] <- 2
TidyData$Ethnicity_EMP1_3[TidyData$Ethnicity_EMP1_3 %in% 1] <- 3
TidyData$Ethnicity_EMP1_4[TidyData$Ethnicity_EMP1_4 %in% 1] <- 4
TidyData$Ethnicity_EMP1_5[TidyData$Ethnicity_EMP1_5 %in% 1] <- 5
TidyData$Ethnicity_EMP1_6[TidyData$Ethnicity_EMP1_6 %in% 1] <- 6
TidyData$Ethnicity_EMP1_7[TidyData$Ethnicity_EMP1_7 %in% 1] <- 7
data.frame(colnames(TidyData))
#Unite Ethnicity into ETH.NUll and ETH.E2
TidyData <- unite(TidyData, ETH.E1, Ethnicity_EMP1_1, Ethnicity_EMP1_2, Ethnicity_EMP1_3, Ethnicity_EMP1_4, Ethnicity_EMP1_5, Ethnicity_EMP1_6, Ethnicity_EMP1_7, sep = "_", remove = FALSE, na.rm = TRUE)
data.frame(colnames(TidyData))
##Recode into factor variables for both employees (Etnicity, Degree, Industry, JobFunction, Income)
TidyData$ETH.E1 <- as.factor(as.character(TidyData$ETH.E1))
TidyData$Degree_EMP1 <- as.factor(as.character(TidyData$Degree_EMP1))
TidyData$Industry_EMP1 <- as.factor(as.character(TidyData$Industry_EMP1))
TidyData$JobFunction_EMP1 <- as.factor(as.character(TidyData$JobFunction_EMP1))
TidyData$Income_EMP1 <- as.factor(as.character(TidyData$Income_EMP1))
TidyData$Gender_EMP1 <- as.factor(as.character(TidyData$Gender_EMP1))
TidyData <- TidyData %>% mutate(Degree.E1 = fct_recode(Degree_EMP1,
"Associate" = "1",
"Bachelor" = "2" ,
"Master" = "3" ,
"Doctorate" = "4" ,
"Highschool or less" = "5"
))
TidyData <- TidyData %>% mutate(Industry.E1 = fct_recode(Industry_EMP1,
"Banking" = "1",
"Education" = "2" ,
"Food & Beverage" = "3" ,
"Government" = "4" ,
"Healthcare" = "5",
"Manufacturing" = "6",
"Media & Entertainment" = "7",
"Retail, Wholesale, & Distribution" = "8",
"Software & IT" = "9",
"Nonprofit" = "10",
"Other" = "11"
))
TidyData <- TidyData %>% mutate(JobFunction.E1 = fct_recode(JobFunction_EMP1,
"Accounting & Finance" = "1",
"Administrative" = "2" ,
"Arts & Design" = "3" ,
"Education" = "4" ,
"Engineering" = "5",
"IT" = "6",
"Marketing, Sales, & Business Dev." = "7",
"Management" = "8",
"Operations" = "9",
"Other" = "10"
))
TidyData <- TidyData %>% mutate(Income.E1 = fct_recode(Income_EMP1,
"Less than 25k" = "1",
"25-49k" = "2" ,
"50-75k" = "3" ,
"75-99k" = "4" ,
"100-150k" = "5",
"150+" ="6"
))
data.frame(colnames(TidyData))
#####
Employee1.Demos <- TidyData[, c(1, 2, 11, 12, 44:47)]
Employee1.Demos <-Employee1.Demos %>% mutate(Eth.Final.E1 = fct_recode(ETH.E1,
"Multiracial" = "1_2_3_4_5_6_NA",
"Multiracial" = "NA_NA_3_NA_NA_6_NA" ,
"Multiracial" = "NA_NA_NA_4_NA_6_NA",
"Multiracial" = "NA_NA_NA_NA_5_6_NA",
"Multiracial" = "1_NA_3_NA_5_6_NA",
"Multiracial" = "1_NA_NA_NA_5_NA_NA",
"Asian" = "NA_NA_3_NA_NA_NA_NA",
"Hispanic" = "NA_NA_NA_NA_5_NA_NA" ,
"White" = "NA_NA_NA_NA_NA_6_NA",
"Multiracial" = "NA_NA_NA_NA_NA_NA_7",
"Black" = "1_NA_NA_NA_NA_NA_NA",
"NHOPI" = "NA_NA_NA_4_NA_NA_NA",
"ANAI" = "NA_2_NA_NA_NA_NA_NA"))
Employee1.Demos <-Employee1.Demos %>% mutate(Degree.Final = fct_recode(Degree.E1,
"Associate" = "1",
"Bachelor" = "2" ,
"Master" = "3" ,
"Doctorate" = "4" ,
"Highschool or less" = "5"
))
Employee1.Demos <-Employee1.Demos %>% mutate(Gender.Final = fct_recode(Gender_EMP1,
"Male" = "1",
"Female" = "2" ,
"Other" = "3"
))
Employee1.Demos <-Employee1.Demos %>% mutate(Industry.Final = fct_recode(Industry.E1,
"Banking" = "1",
"Education" = "2" ,
"Food & Beverage" = "3" ,
"Government" = "4" ,
"Healthcare" = "5",
"Manufacturing" = "6",
"Media & Entertainment" = "7",
"Retail, Wholesale, & Distribution" = "8",
"Software & IT" = "9",
"Nonprofit" = "10",
"Other" = "11"
))
Employee1.Demos <-Employee1.Demos %>% mutate(JobFunction.Final = fct_recode(JobFunction.E1,
"Accounting & Finance" = "1",
"Administrative" = "2" ,
"Arts & Design" = "3" ,
"Education" = "4" ,
"Engineering" = "5",
"IT" = "6",
"Marketing, Sales, & Business Dev." = "7",
"Operations" = "8",
"Management" = "12",
"Other" = "11"
))
Employee1.Demos <-Employee1.Demos %>% mutate(Income.Final = fct_recode(Income.E1,
"Less than 25k" = "1",
"25-49k" = "3" ,
"50-75k" = "4" ,
"75-99k" = "5" ,
"100-150k" = "6",
"150+" ="7"
))
data.frame(colnames(Employee1.Demos))
Employee1.Demos <- Employee1.Demos[, c(3, 9:14)]
```
```{r Employee 2 Demos}
data.frame(colnames(ScaleData))
TidyData.E2 <- ScaleData[, c( 319:325, 327, 328, 330, 332, 334, 337)]
TidyData.E2$Ethnicity_EMP2_2[TidyData$Ethnicity_EMP2_2 %in% 1] <- 2
TidyData.E2$Ethnicity_EMP2_3[TidyData$Ethnicity_EMP2_3 %in% 1] <- 3
TidyData.E2$Ethnicity_EMP2_4[TidyData$Ethnicity_EMP2_4 %in% 1] <- 4
TidyData.E2$Ethnicity_EMP2_5[TidyData$Ethnicity_EMP2_5 %in% 1] <- 5
TidyData.E2$Ethnicity_EMP2_6[TidyData$Ethnicity_EMP2_6 %in% 1] <- 6
TidyData.E2$Ethnicity_EMP2_7[TidyData$Ethnicity_EMP2_7 %in% 1] <- 7
data.frame(colnames(TidyData))
attach(TidyData.E2)
#Unite Ethnicity into ETH.NUll and ETH.E2
TidyData.E2 <- unite(TidyData.E2, ETH.E2, Ethnicity_EMP2_1, Ethnicity_EMP2_2, Ethnicity_EMP2_3, Ethnicity_EMP2_4, Ethnicity_EMP2_5, Ethnicity_EMP2_6, Ethnicity_EMP2_7, sep = "_", remove = FALSE, na.rm = TRUE)
##Recode into factor variables for both employees (Etnicity, Degree, Industry, JobFunction, Income)
TidyData.E2$ETH.E2 <- as.factor(as.character(TidyData.E2$ETH.E2))
TidyData.E2$Degree_EMP2 <- as.factor(as.character(TidyData.E2$Degree_EMP2))
TidyData.E2$Industry_EMP2 <- as.factor(as.character(TidyData.E2$Industry_EMP2))
TidyData.E2$JobFunction_EMP2 <- as.factor(as.character(TidyData.E2$JobFunction_EMP2))
TidyData.E2$Income_EMP2 <- as.factor(as.character(TidyData.E2$Income_EMP2))
TidyData.E2$Gender_EMP2 <- as.factor(as.character(TidyData.E2$Gender_EMP2))
TidyData.E2$Age_EMP2 <- as.numeric(as.character(TidyData.E2$Age_EMP2))
TidyData.E2 <- TidyData.E2 %>% mutate(Degree.E2 = fct_recode(Degree_EMP2,
"Associate" = "1",
"Bachelor" = "2" ,
"Master" = "3" ,
"Doctorate" = "4" ,
"Highschool or less" = "5"
))
TidyData.E2 <- TidyData.E2 %>% mutate(Industry.E2 = fct_recode(Industry_EMP2,
"Banking" = "1",
"Education" = "2" ,
"Food & Beverage" = "3" ,
"Government" = "4" ,
"Healthcare" = "5",
"Manufacturing" = "6",
"Media & Entertainment" = "7",
"Retail, Wholesale, & Distribution" = "8",
"Software & IT" = "9",
"Nonprofit" = "10",
"Other" = "11"
))
TidyData.E2 <- TidyData.E2 %>% mutate(JobFunction.E2 = fct_recode(JobFunction_EMP2,
"Accounting & Finance" = "1",
"Administrative" = "2" ,
"Arts & Design" = "3" ,
"Education" = "4" ,
"Engineering" = "5",
"IT" = "6",
"Marketing, Sales, & Business Dev." = "7",
"Management" = "12",
"Operations" = "8",
"Other" = "11"
))
TidyData.E2 <- TidyData.E2 %>% mutate(Income.E2 = fct_recode(Income_EMP2,
"Less than 25k" = "1",
"25-49k" = "3" ,
"50-75k" = "4" ,
"75-99k" = "5" ,
"100-150k" = "6",
"150+" ="7"
))
data.frame(colnames(TidyData.E2))
#####
Employee2.Demos <- TidyData.E2[, c(1, 9, 10, 15:18)]
Employee2.Demos <-Employee2.Demos %>% mutate(Eth.Final.E2 = fct_recode(ETH.E2,
"Multiracial" = "1_1_1_1_1_1_NA",
"Multiracial" = "1_NA_1_NA_1_1_NA" ,
"Multiracial" = "1_NA_NA_NA_1_NA_NA",
"Black" = "1_NA_NA_NA_NA_NA_NA",
"AIAN" = "NA_1_NA_NA_NA_NA_NA",
"Multiracial" = "NA_NA_1_NA_NA_1_NA",
"Asian" = "NA_NA_1_NA_NA_NA_NA",
"NHPI" = "NA_NA_NA_1_NA_NA_NA",
"Multiracial" = "NA_NA_NA_NA_1_1_NA",
"Hispanic" = "NA_NA_NA_NA_1_NA_NA" ,
"White" = "NA_NA_NA_NA_NA_1_NA"
))
Employee2.Demos <-Employee2.Demos %>% mutate(Degree.Final = fct_recode(Degree.E2,
"Associate" = "1",
"Bachelor" = "2" ,
"Master" = "3" ,
"Doctorate" = "4" ,
"Highschool or less" = "5"
))
Employee2.Demos <-Employee2.Demos %>% mutate(Gender.Final = fct_recode(Gender_EMP2,
"Male" = "1",
"Female" = "2" ,
"Other" = "3"
))
Employee2.Demos <-Employee2.Demos %>% mutate(Industry.Final = fct_recode(Industry.E2,
"Banking" = "1",
"Education" = "2" ,
"Food & Beverage" = "3" ,
"Government" = "4" ,
"Healthcare" = "5",
"Manufacturing" = "6",
"Media & Entertainment" = "7",
"Retail, Wholesale, & Distribution" = "8",
"Software & IT" = "9",
"Nonprofit" = "10",
"Other" = "11"
))
Employee2.Demos <-Employee2.Demos %>% mutate(JobFunction.Final = fct_recode(JobFunction.E2,
"Accounting & Finance" = "1",
"Administrative" = "2" ,
"Arts & Design" = "3" ,
"Education" = "4" ,
"Engineering" = "5",
"IT" = "6",
"Marketing, Sales, & Business Dev." = "7",
"Operations" = "8",
"Management" = "12",
"Other" = "11"
))
Employee2.Demos <-Employee2.Demos %>% mutate(Income.Final = fct_recode(Income.E2,
"Less than 25k" = "1",
"25-49k" = "3" ,
"50-75k" = "4" ,
"75-99k" = "5" ,
"100-150k" = "6",
"150+" ="7"
))
data.frame(colnames(Employee2.Demos))
Employee2.Demos <- Employee2.Demos[, c(2,8:13)]
```
```{r Master DATASET - Merge Demographics and Scale Data, echo=FALSE}
#Create dataset for PERMA(4) and SWLS
data.frame(colnames(ScaleData))
Scale.Final <- ScaleData[, c(363:384)]
Employee1.Scales <- Scale.Final
###Score PERMA and PF Aggregated Scales
attach(Scale.Final)
Employee1.Scales <- mutate(Employee1.Scales,
PERMA.Self = c(PE.Scale.E1 + PREL.Scale.E1 + PEN.Scale.E1 +
PMEAN.Scale.E1 + PACCOM.Scale.E1)/5,
PF.Self = c(PE.Scale.E1 + PREL.Scale.E1 + PEN.Scale.E1 +
PMEAN.Scale.E1 + PACCOM.Scale.E1
+ PMIND.Scale.E1 + PECON.Scale.E1 + PHEALTH.Scale.E1
+ PPWE.Scale.E1)/9,
PERMA.C = c(PE.Scale.E2C + PREL.Scale.E2C + PEN.Scale.E2C +
PMEAN.Scale.E2C + PACCOM.Scale.E2C)/5,
PF.C = c(PE.Scale.E2C + PREL.Scale.E2C + PEN.Scale.E2C +
PMEAN.Scale.E2C + PACCOM.Scale.E2C +
PMIND.Scale.E2C + PECON.Scale.E2C + PHEALTH.Scale.E2C
+ PPWE.Scale.E2C)/9
)
##Merge Master.Scale andEmployee1.Demos into THEMASTER
Employee1.Demos$ID.Final <- seq.int(nrow(Employee1.Demos))
Employee1.Scales$ID.Final <- seq.int(nrow(Employee1.Scales))
THE.MASTER <- left_join(Employee1.Scales, Employee1.Demos, by = "ID.Final")
rm(TidyData, ScaleData, Scale.Final, Final2, Employee1.Scales, Employee1.Demos, Demos)
```
#Statistics
```{r Method Section}
#Age
mean(THE.MASTER$Age_EMP1, na.rm = TRUE)
sd(THE.MASTER$Age_EMP1, na.rm = TRUE)
#Gender
freqdist::freqdist(THE.MASTER$Gender.Final)
#Degree
freqdist::freqdist(THE.MASTER$Degree.Final)
#Ethnicity
freqdist::freqdist(THE.MASTER$Eth.Final.E1)
#Industry
freqdist::freqdist(THE.MASTER$Industry.Final)
#Income
freqdist::freqdist(THE.MASTER$Income.Final)
```
```{r Table 1 - Summary and Convergence Matrix for PERMA, PF, and SWLS}
The.Master.matrix <- as.matrix(THE.MASTER)
data.frame(colnames(The.Master.matrix))
#Means and SDs for all variables
sapply(THE.MASTER[, c(1:26)], mean, na.rm=TRUE)
sapply(THE.MASTER[, c(1:26)], sd, na.rm=TRUE)
##Convergence of PERMA and SWB
rcorr(The.Master.matrix[, c(1, 12)], type = "pearson") #PREL
rcorr(The.Master.matrix[, c(2, 13)], type = "pearson") #PE
rcorr(The.Master.matrix[, c(3, 14)], type = "pearson") #PMEAN
rcorr(The.Master.matrix[, c(4, 15)], type = "pearson") #PACCOM
rcorr(The.Master.matrix[, c(5, 16)], type = "pearson") #PEN
rcorr(The.Master.matrix[, c(6, 17)], type = "pearson") #PECON
rcorr(The.Master.matrix[, c(7, 18)], type = "pearson") #PMIND
rcorr(The.Master.matrix[, c(8, 19)], type = "pearson") #PHEALTH
rcorr(The.Master.matrix[, c(9, 20)], type = "pearson") #PPWE
rcorr(The.Master.matrix[, c(10, 21)], type = "pearson") #PF
rcorr(The.Master.matrix[, c(11, 22)], type = "pearson") #SWB
rcorr(The.Master.matrix[, c(11, 22, 23, 25)], type = "pearson")
```
```{r Table 2 - PERMA, PF, and Self and Collateral SWB}
##Convergence between PERMA self reports and SWB self and collateral
The.SWB.matrix <- as.matrix(THE.MASTER[, c(1:11, 22, 23, 24)])
rcorr(The.SWB.matrix, type = "pearson")
```
```{r Constrast Codes for Regression Tables}
##Create dummy variables for gender, income, and age
###Gender
contrasts(THE.MASTER$Gender.Final) <- contr.treatment(2, base = 2)
Male.vs.Female <- c(1, 0)
contrasts(THE.MASTER$Gender.Final) <- cbind(Male.vs.Female)
###Income
contrasts(THE.MASTER$Income.Final) <- contr.treatment(5, base = 2)
MLess25k.vs.50_75k <- c(1, 0, 0, 0, 0)
M75_99k.vs.50_75k <- c(0, 0, 1, 0, 0)
M100_150k.vs.50_75k <- c(0, 0, 0, 1, 0)
M150k.vs.25_50k <- c(0, 0, 0, 0, 1)
contrasts(THE.MASTER$Income.Final) <- cbind(MLess25k.vs.50_75k, M75_99k.vs.50_75k,
M100_150k.vs.50_75k, M150k.vs.25_50k)
```
```{r Table 3 - Regression for S-PERMA Predicting SWB}
#SWB Self-Reports
attach(THE.MASTER)
##Model 1
Model1 <- lm(SWLS.E1 ~ PERMA.Self + Gender.Final + Age_EMP1 + Income.Final)
summary(Model1)
confint.lm(Model1)
##Assumption set
standardized <- rstudent(Model1) #Standardized residuals
Fitted <- scale(Model1$fitted.values) #Predicted scores
##Normality
hist(standardized)
##Linearity
qqnorm(standardized)
##Homogeniety and homoscedascitiy
plot(Fitted, standardized)
##Model 2
Model2 <- lm(SWLS.E2C ~ PERMA.Self + Gender.Final + Age_EMP1 + Income.Final)
summary(Model2)
confint.lm(Model2)
```
```{r Table 4 - Regression for S-PF Predicting SWB}
##Model 1
Model3 <- lm(SWLS.E1 ~ PF.W.Scale.E1 + Gender.Final + Age_EMP1 + Income.Final)
summary(Model3)
confint.lm(Model3)
##Assumption set
standardized <- rstudent(Model1) #Standardized residuals
Fitted <- scale(Model1$fitted.values) #Predicted scores
##Normality
hist(standardized)
##Linearity
qqnorm(standardized)
##Homogeniety and homoscedascitiy
plot(Fitted, standardized)
##Model 2
Model4 <- lm(SWLS.E2C ~ PF.W.Scale.E1 + Gender.Final + Age_EMP1 + Income.Final)
summary(Model4)
confint.lm(Model4)
```
```{r Table 5 - Regression for Elements of S-PERMA and S-PF Predicting SWB}
##Model 5
Model5 <- lm(SWLS.E1 ~ PE.Scale.E1 + PEN.Scale.E1 + PREL.Scale.E1 + PMEAN.Scale.E1 +
PACCOM.Scale.E1 + PMIND.Scale.E1 + PECON.Scale.E1 + PHEALTH.Scale.E1 +
PPWE.Scale.E1 + Gender.Final + Age_EMP1 + Income.Final)
summary(Model5)
confint.lm(Model5)
##Assumption set
standardized <- rstudent(Model1) #Standardized residuals
Fitted <- scale(Model1$fitted.values) #Predicted scores
##Normality
hist(standardized)
##Linearity
qqnorm(standardized)
##Homogeniety and homoscedascitiy
plot(Fitted, standardized)
##Model 6
Model6 <- lm(SWLS.E2C ~ PE.Scale.E1 + PEN.Scale.E1 + PREL.Scale.E1 + PMEAN.Scale.E1 +
PACCOM.Scale.E1 + PMIND.Scale.E1 + PECON.Scale.E1 + PHEALTH.Scale.E1 +
PPWE.Scale.E1 + Gender.Final + Age_EMP1 + Income.Final)
summary(Model6)
confint.lm(Model6)
```
```{r Table 6 - Regression for C-PERMA Predicting SWB}
#SWB Self-Reports
attach(THE.MASTER)
##Model 7
Model7 <- lm(SWLS.E1 ~ PERMA.C + Gender.Final + Age_EMP1 + Income.Final)
summary(Model7)
confint.lm(Model7)
##Assumption set
standardized <- rstudent(Model7) #Standardized residuals
Fitted <- scale(Model7$fitted.values) #Predicted scores
##Normality
hist(standardized)
##Linearity
qqnorm(standardized)
##Homogeniety and homoscedascitiy
plot(Fitted, standardized)
##Model 8
Model8 <- lm(SWLS.E2C ~ PERMA.C + Gender.Final + Age_EMP1 + Income.Final)
summary(Model8)
confint.lm(Model8)
```
```{r Table 7 - Regression for C-PF Predicting SWB}
##Model 9
attach(THE.MASTER)
Model9 <- lm(SWLS.E1 ~ PF.W.Scale.E2C + Gender.Final + Age_EMP1 + Income.Final)
summary(Model9)
confint.lm(Model9)
##Assumption set
standardized <- rstudent(Model9) #Standardized residuals
Fitted <- scale(Model9$fitted.values) #Predicted scores
##Normality
hist(standardized)
##Linearity
qqnorm(standardized)
##Homogeniety and homoscedascitiy
plot(Fitted, standardized)
##Model 10
Model10 <- lm(SWLS.E2C ~ PF.W.Scale.E2C + Gender.Final + Age_EMP1 + Income.Final)
summary(Model10)
confint.lm(Model10)
```
```{r Table 8 - Regression for Elements of C-PERMA and S-PF Predicting SWB}
##Model 5
Model11 <- lm(SWLS.E1 ~ PE.Scale.E2C + PEN.Scale.E2C + PREL.Scale.E2C + PMEAN.Scale.E2C +
PACCOM.Scale.E2C + PMIND.Scale.E2C + PECON.Scale.E2C + PHEALTH.Scale.E2C +
PPWE.Scale.E2C + Gender.Final + Age_EMP1 + Income.Final)
summary(Model11)
confint.lm(Model11)
##Assumption set
standardized <- rstudent(Model11) #Standardized residuals
Fitted <- scale(Model11$fitted.values) #Predicted scores
##Normality
hist(standardized)
##Linearity
qqnorm(standardized)
##Homogeniety and homoscedascitiy
plot(Fitted, standardized)
##Model 12
Model12 <- (SWLS.E2C ~ PE.Scale.E2C + PEN.Scale.E2C + PREL.Scale.E2C + PMEAN.Scale.E2C +
PACCOM.Scale.E2C + PMIND.Scale.E2C + PECON.Scale.E2C + PHEALTH.Scale.E2C +
PPWE.Scale.E2C + Gender.Final + Age_EMP1 + Income.Final)
summary(Model12)
confint.lm(Model12)
```
```{r Hypothesis 7 PF Above and Beyond PERMA}
anova(Model1, Model3) #Self and self
anova(Model2, Model4) #Self and Collateral
```
```{r Method Section Revised to Include}
#Age
attach(Employee2.Demos)
mean(Employee2.Demos$Age_EMP2, na.rm = TRUE)
sd(Employee2.Demos$Age_EMP2, na.rm = TRUE)
#Gender
freqdist::freqdist(Employee2.Demos$Gender.Final)
#Degree
freqdist::freqdist(Employee2.Demos$Degree.Final)
#Ethnicity
freqdist::freqdist(Employee2.Demos$Eth.Final.E2)
#Industry
freqdist::freqdist(Employee2.Demos$Industry.Final)
#Income
freqdist::freqdist(Employee2.Demos$Income.Final)
```
<file_sep>/TUPEDashboards/CDE.Dashboard.Rmd
---
title: "Tobacco-Use Prevention Education Program: Statewide Dashboard"
output:
flexdashboard::flex_dashboard:
theme: cerulean
orientation: rows
vertical_layout: fill
source_code: embed
social: menu
---
```{r Data Management}
library(flexdashboard)
library(knitr)
library(DT)
library(rpivotTable)
library(ggplot2)
library(plotly)
library(plyr)
library(dplyr)
library(readxl)
library(tidyverse)
library(crosstalk)
library(leaflet)
library(htmltools)
library(rgdal)
library(geojsonio)
library(rjson)
library(scatterD3)
library(scales)
library(formattable)
Master <- read_excel("~/Desktop/UCSD/TUPE/Evaluation/Dashboard/CDE.ComprehensiveData.xlsx",
sheet = "Master")
ReachStats <- read_excel("~/Desktop/UCSD/TUPE/Evaluation/Dashboard/CDE.ComprehensiveData.xlsx",
sheet = "ReachStatistics")
Datasources <- read_excel("~/Desktop/UCSD/TUPE/Evaluation/Dashboard/CDE.EvaluationData.xlsx",
sheet = "Method")
Master$Agency <- as.factor(Master$Agency)
Master$Region <- as.factor(Master$Region)
Master$Location <- as.factor(Master$Location)
Master$ReportingFrequency <- as.factor(Master$ReportingFrequency)
Master$ExternalEvaluator <- as.factor(Master$ExternalEvaluator)
Master$TotalBudget <- as.numeric(Master$TotalBudget)
Master$EvaluationBudget <- as.numeric(Master$EvaluationBudget)
Master$ADA <- as.numeric(Master$ADA)
Master$County <- as.factor(Master$County)
#ReachStatistics
ReachStats$Agency <- as.factor(ReachStats$Agency)
ReachStats$ProgramArea <- as.factor(ReachStats$ProgramArea)
ReachStats$SchoolParents <- as.numeric(ReachStats$SchoolParents)
ReachStats$AvgDoseMin <- as.numeric(ReachStats$AvgDoseMin)
ReachStats$TotalDoseMin <- as.numeric(ReachStats$TotalDoseMin)
ReachStats$Sessions <- as.numeric(ReachStats$Sessions)
ReachStats$Years <- as.numeric(ReachStats$Years )
#Data sources
Datasources$Grantee <- as.factor(Datasources$Grantee)
Datasources$Attendance <- as.numeric(Datasources$Attendance)
Datasources$`Process Log` <- as.numeric(Datasources$`Process Log`)
Datasources$`Meeting Notes` <- as.numeric(Datasources$`Meeting Notes`)
```
Map
===========================================
```{r Cholorpleth Map}
Cali_CT <- Master[, c(1:4, 28)]
coordinates(Cali_CT) = c("Lng","Lat")
crs.geo1 = CRS("+proj=longlat")
proj4string(Cali_CT) = crs.geo1
plot(Cali_CT, pch = 20, col = "steelblue")
Cali <- geojsonio::geojson_read("/Users/ScottDonaldson/Desktop/UCSD/TUPE/Evaluation/Dashboard/TUPEDashboards/Files/Cali.json",
what = "sp")
proj4string(Cali) = crs.geo1
cali_agg <- aggregate(x=Cali_CT["TotalReach"], by=Cali, FUN=sum)
bins <- c(0, 13000, 33000, 150000, 400000, 800000)
pal <- colorBin("Dark2", domain = Cali_CT$County, bins = bins)
labels <- sprintf(
"<strong>%s</strong>",
prettyNum(cali_agg$TotalReach, big.mark = ",")
) %>% lapply(htmltools::HTML)
TUPEMAP <- leaflet(cali_agg) %>%
addTiles() %>%
addMarkers(lng = Master$Lng,
lat = Master$Lat,
label = Master$Agency,
labelOptions = (textsize = "50px")) %>%
setView(-119.2321, 36.9859, zoom = 6.7) %>%
addProviderTiles(providers$Esri.NatGeoWorldMap) %>%
addPolygons(stroke = TRUE,opacity = 1,
fillOpacity = 0.5,
smoothFactor = 0.5,
color="black",
fillColor = ~pal(TotalReach),
weight = 1,
label = labels,
labelOptions = labelOptions(style = list("font-weight" = "normal",
padding = "3px 8px"),
textsize = "15px",
direction = "auto")) %>%
addLegend(values=~TotalReach,
pal=pal,
title="Projected County-Level Reach",
position = "bottomleft",
na.label = "NA = Non-TUPE County")
TUPEMAP
```
Demographics
===========================================
Row {data-height=75}
-------------------------------------------
### Projected Statewide Reach
```{r}
gauge(sum(Master$TotalReach),
min = 0,
max = 4000000)
```
### School Districts
```{r}
valueBox(prettyNum(sum(Master$Districts),
big.mark = ","),
icon = 'fa-school',
color = "orange")
```
### Schools
```{r}
valueBox(sum(Master$Schools),
icon = 'fa-pencil-alt',
color = "#60E62E")
```
### Projected Statewide TUPE Activities
```{r}
valueBox(sum(Master$TotalActivities),
icon = 'fa-globe',
color = "#E6642E")
```
Row {.tabset}
----------------------------------------------------------------
### Demographics Table {data-height=100}
```{r}
attach(Master)
Pivot <- Master[, c(1,2, 5:9)]
rpivotTable(Pivot,
rows = "Location",
cols = "Region",
rendererName = "Horizontal Stacked Bar Chart")
```
Activities
===========================================
### Program Activities Profile
```{r Activities Profile, fig.height=1000, fig.width=500}
Activities <- as.data.frame(Master[, c(1,2,27,12,14,18,22,25:26)])
PA <- formatter("span",
style = x ~ style(color = ifelse(x > 10, "green",
ifelse(x < 4, "red",
"black"))))
as.datatable(
formattable(Activities,
list(PartnerAgencies = PA,
TotalActivities = color_bar(color = "#2EE6E2"),
Prevention = proportion_bar(color = "lightgray"),
Intervention = proportion_bar(color = "lightgray"),
Cessation = proportion_bar(color = "lightgray"),
Staff = color_tile("transparent",
"lightpink"),
Family = color_tile("gray",
"purple"))),
rownames = FALSE,
extensions= 'Buttons',
style="bootstrap",
class='hover cell-border stripe',
filter = "top",
editable = 'cell',
width=1000,
height = 500,
options=list(
deferRender=TRUE,
dom='Bfrtip',
order =list(2, 'desc'),
scrollY=300,
scroller=TRUE,
buttons = c('csv', 'excel', 'print')))
```
Reach Profile
===========================================
Row {.tabset}
-------------------------------------
### Student Services
```{r Students Reach, fig.height=800, fig.width=1000}
StudentReach <- pivot_longer(ReachStats,
cols = c(5:35),
names_to = "Target_Population",
values_to = "Count",
values_drop_na = TRUE)
StudentReach <- StudentReach[which(
StudentReach$ProgramArea=='NeedsAssessment' |
StudentReach$ProgramArea=='Prevention' |
StudentReach$ProgramArea=='PreventionIntervention' |
StudentReach$ProgramArea=='PreventionInterventionYD' |
StudentReach$ProgramArea=='PreventionYD' |
StudentReach$ProgramArea=='PreventionInterventionCessation' |
StudentReach$ProgramArea=='Intervention' |
StudentReach$ProgramArea=='InterventionYD' |
StudentReach$ProgramArea=='InterventionCessation' |
StudentReach$ProgramArea=='InterventionYD' |
StudentReach$ProgramArea=='Cessation' |
StudentReach$ProgramArea=='CessationYD' |
StudentReach$ProgramArea=='YouthDevelopment'),
c(1,3,4,24:27, 34:36)
]
Student_reach <- SharedData$new(StudentReach, ~ActivityName)
bscols(widths = c(2,10),
filter_select("AG",
"Agency",
Student_reach,
~Agency),
ggplotly(ggplot(data=Student_reach,
aes(x= reorder(ProgramArea, -Count, FUN = sum),
y=Count,
fill=Target_Population,
na.rm = TRUE)) +
geom_bar(stat="identity",
position = "stack") +
scale_y_continuous(limits = c(0, 150000),
breaks = c(2000,
10000,
20000,
50000,
100000,
150000
)) +
theme_classic() +
labs(title = "Student Reach Profile",
x = "Program Area",
y = "#Students") +
guides(fill=FALSE) +
scale_x_discrete(labels=c("Prev",
"PrevYD",
"Cess",
"Int",
"IntYD",
"YD",
"PrevInt",
"PrevIntCess",
"CessYD",
"PrevIntYD",
"IntCess",
"Needs")),
width = 1200,
height = 500)
)
```
```{r Student Datatable}
formatRound(datatable(Student_reach,
extensions= c('Buttons', 'Scroller'),
style="bootstrap",
class='hover cell-border stripe',
filter = "top",
editable = 'cell',
width=1000,
height = 500,
options=list(
deferRender=TRUE,
dom='Bfrtip',
scroller = TRUE,
buttons = c('csv', 'excel', 'print'))),
mark =",",
digits = 1,
columns = c(5:10)
)
```
### Family and Community
```{r Family Reach, fig.height=800, fig.width=1000}
ParentReach <- pivot_longer(ReachStats,
cols = c(36:54),
names_to = "Target_Population",
values_to = "Count")
ParentReach <- ParentReach[which(ParentReach$ProgramArea=="Family"),
c(1,3,4,36:39, 46:48)]
Family_reach <- SharedData$new(ParentReach, ~ActivityName)
bscols(widths = c(2,10),
filter_select("AG",
"Agency",
Family_reach,
~Agency),
ggplotly(ggplot(data=Family_reach,
aes(x=Target_Population,
y=Count,
fill=Agency,
na.rm = TRUE)) +
geom_bar(stat="identity",
position = "stack") +
scale_y_continuous(limits = c(0, 100000),
breaks = c(0,
2000,
10000,
20000,
30000,
40000,
50000,
75000,
100000),
labels = comma) +
scale_x_discrete(labels=c("AA",
"Armenian",
"Asian",
"Cont",
"Fost.",
"FRPM",
"Pub.",
"Girls",
"Hisp.",
"Home.",
"LGTBQ",
"LowSes",
"Military",
"NA",
"New",
"NH/PI",
"NT",
"Parents",
"Users")) +
guides(fill=FALSE) +
theme_classic() +
labs(title = "Parents Reach Profile",
x = "Target Population",
y = "#Participants"),
width = 1400,
height = 600)
)
```
```{r Family Datatable}
formatRound(datatable(Family_reach,
extensions= c('Buttons', 'Scroller'),
style="bootstrap",
class='hover cell-border stripe',
filter = "top",
editable = 'cell',
width=1000,
height = 500,
options=list(
deferRender=TRUE,
dom='Bfrtip',
scroller = TRUE,
buttons = c('csv', 'excel', 'print'))),
mark =",",
digits = 1,
columns = c(5:10)
)
```
### Staff Professional Development
```{r Staff Reach, fig.height=800, fig.width=1000}
StaffReach <- pivot_longer(ReachStats,
cols = c(61:64),
names_to = "Target_Population",
values_to = "Count")
StaffReach <- StaffReach[which(StaffReach$ProgramArea=="Staff"),
c(1,3,4,55:63)]
staff_reach <- SharedData$new(StaffReach, ~ActivityName)
bscols(widths = c(2,10),
filter_select("AG",
"Agency",
staff_reach,
~Agency),
ggplotly(ggplot(data=staff_reach,
aes(x=Target_Population,
y=Count,
fill=Agency,
na.rm = TRUE)) +
geom_bar(stat="identity",
position = "stack") +
scale_y_continuous(limits = c(0, 40000),
breaks = seq(0, 40000, 5000)) +
scale_x_discrete(labels=c("Non-TUPE Certified",
"Non-TUPE Classified",
"TUPE Certified",
"TUPE Classified")) +
guides(fill=FALSE) +
theme_classic() +
labs(title = "Staff Reach Profile",
x = "Target Population",
y = "#Participants"),
width = 1000,
height = 600)
)
```
```{r Staff Datatable}
formatRound(datatable(staff_reach,
extensions= c('Buttons', 'Scroller'),
style="bootstrap",
class='hover cell-border stripe',
filter = "top",
editable = 'cell',
width=1000,
height = 500,
options=list(
deferRender=TRUE,
dom='Bfrtip',
scroller = TRUE,
buttons = c('csv', 'excel', 'print'))),
mark =",",
digits = 1,
columns = c(5:10)
)
```
Evaluation {data-orientation=columns}
===========================================
Column {data-width=500}
-------------------------------------
### Continuous Quality Improvement Rubric
```{r, out.width="750px", out.height="750px"}
knitr::include_graphics("/Users/ScottDonaldson/Desktop/UCSD/TUPE/Evaluation/Dashboard/TUPEDashboards/FIles/Rubric.pdf")
```
Column {.tabset data-width=500}
-------------------------------------
### Data Sources {data-height=200}
```{r Datamethods Crosstalk}
attach(Datasources)
DS <- pivot_longer(Datasources,
cols = c(2:27),
names_to = "DataSource",
values_to = "Count",
values_drop_na = TRUE)
DS$TOTAL.GRANTEE <- round(DS$TOTAL.GRANTEE, digits = 1)
DS$Count <- round(DS$Count, digits = 1)
DS <- DS[c(1:284), ]
DataSources_shared <- SharedData$new(DS, ~Grantee)
bscols(ggplotly(ggplot(data=DataSources_shared,
aes(x= reorder(Grantee, -TOTAL.GRANTEE, FUN = sum),
y=Count,
fill=DataSource,
na.rm = TRUE)) +
geom_bar(stat="identity",
position = "stack") +
scale_y_continuous(limits = c(0, 10),
breaks = c(0,
2,
4,
6,
8,
10)) +
scale_x_discrete(labels=c()) +
guides(fill=FALSE) +
theme_classic() +
labs(x = "Agency",
y = "#Methods"),
width = 1000,
height = 600)
)
```
```{r Data Methods Table}
formatRound(datatable(DataSources_shared,
extensions= c('Buttons', 'Scroller'),
style="bootstrap",
class='hover cell-border stripe',
filter = "top",
editable = 'cell',
width=1000,
height = 500,
options=list(
deferRender=TRUE,
dom='Bfrtip',
scroller = TRUE,
buttons = c('csv', 'excel', 'print'))),
mark =",",
digits = 1,
columns = c(5:10)
)
```
### Continuous Quality Improvement Scores
```{r QI Scores}
QI <- ggplotly(ggplot(Master,
aes(x=Agency,
y=QIScore,
fill=Agency)) +
geom_col() +
theme_classic() +
theme(axis.ticks = element_blank(), axis.text.x = element_blank()) +
labs(x = "Local Educational Agency",
y = "Quality Improvement Score") +
guides(fill=FALSE)
)
QI
```
### Evaluation Reporting
```{r Reporting, fig.width=300}
Reporting <- plot_ly(Master,
labels = ~ReportingFrequency,
type = 'pie')
Reporting <- Reporting %>% layout(title =
'Evaluation Reporting Frequency',
xaxis = list(showgrid = FALSE,
zeroline = FALSE,
showticklabels = FALSE),
yaxis = list(showgrid = FALSE,
zeroline = FALSE,
showticklabels = FALSE))
Reporting
```
### External
```{r External by QI Scores}
ggplot(Master, aes(x=ExternalEvaluator,
y=QIScore)) +
geom_bar(position="dodge", stat="identity")
```
Summary {data-orientation=columns}
===========================================
Column
-------------------------------------
### __Pilot Technical Assistance Summary (2020)__
1. Grantee Kick-Off Presentations
- Coding and analysis of 10 grantee project plans
- Scheduled and completed one hour Kick-Off presentations with each grantee
- Presentations included information about background characteristics, local needs, organizational structure, reach profile based on ADA, and UCSD’s comprehensive evaluation approach
2. Grantee Project Plan Summaries
-Each grantee was provided an Excel file that outlined each of their proposed activities:
Program area
- Type of activity
- Year in the grant cycle
- Average minutes per activity
- Total dosage in hours
- Average participants
- Total participants
- Agency partners
- TA activities
- Measurable objectives
- Assessment tools
- Evaluation goals
- Process and outcome measures
- Best practices
- Reach statistics profile based on target recipients
- Total reach for each activity
- Reach as a function of ADA
- Six charts to help visualize their program plan
3. Brief Report Summaries
4. SMART Template
-For each planned activity and through a process and outcome evaluation lens, we organized five critiera based on the SMART (e.g., specific, measurable, actionable, revelant, and timely) template:
-State the measurable objective
-e.g. Student will receive the Stanford TPT
-Standards of performance
-e.g. Stanford TPT will be implemented in 8/10 school sites in District X
-Evaluation tools
-e.g. Monthly activity report
-Quality improvement strategy
-Check monthly activity report to hold site coordinators accountable
-Incentivize and reward performance for high-perfoming coordinators
-Time
-e.g., monthly check-ins
-Met with a select few grantees and moderated the SMART process
5. Developed a Process Tracking Tool
6. Performance Indicator Metrics Library
- Family Feedback Tool
- Grantee Satisfaction Tool
- School Connectedness Scale
- Staff Feedback Tool
- TUPE Site Coordinator Tool
- TUPE pre/post Student Assessment
- TUPE Student Well-Being Tool
- Youth Development Tool
Column
-------------------------------------
### __Comprehensive Review of Project Plans__
Data collection for the comprehensive review and recommendations of TUPE project plans was divided into three sections: demographics, implementation/activity/reach profiles, and evaluation. The UCSD Evaluation Team coded each grant application for relevant information in each section, such as region, location, ADA, # of activities across student service areas, among others. In terms of evaluation, the UCSD Evaluation Team created a TUPE-specific Quality Improvement Rubric with criteria and scores for each grantee. We hope this tool provides a useful conceptual map of the TUPE program across important areas of evaluation, design, and measurement.
1. _Map_
-Page 1 includes a cholorpleth map of grantee by county by projected county-level reach. It is important to note that reach numbers were calculated based on the unduplicated total within activities, and projected reach statistics are aggreated at the county-level.
2. _Demographics_
-Page 2 shows an interactive demographics table and program activitie profile. The HTML widgets allow for flexible pivoting of included variables and several visualizations types.
3. _Reach Profile_
-Page 3 contains a reach statistics profile for student services, family and community, and staff professional development. The plots allow for subsetting of indivudal grantees' either in the fiter tab or by selecting rows in the data table feature. In addition, reach is visuzalized by target population and program area (these are abbreviated on the x axis).
4. _Evaluation_
-Page 4 displays the continuous quality improvement rubric that was used to score grantees. The tabset charts on the right column show the scores in addition to data sources that were used at each local educational agency. The final two tabs display pie charts of evaluation reporting frequency and external evaluators.
Please reach out to <NAME> (<EMAIL>) with any questions about the data visualization dashboard.
Sincerely,
UCSD Evaluation Team
```{r UCSD Team, out.width="500px", out.height="500px"}
include_graphics(knitr::include_graphics("/Users/ScottDonaldson/Desktop/UCSD/TUPE/Evaluation/Dashboard/TUPEDashboards/FIles/Scott.pdf"))
```
<file_sep>/Journal of Well-Being/JWA.Regressions.Rmd
---
title: "JWA Regressions"
output: html_notebook
---
```{r Set up}
setwd("~/Documents/JWA/R")
library(haven)
library(psych)
library(AutoModel)
library(lm.beta)
library(MBESS)
library(sjstats)
FINALDATA8K <- read_sav("FINALDATA8K.sav")
FINALDATA9K <- FINALDATA8K
```
```{r JAWS NE}
attach(FINALDATA9K)
PERMA.JAWS <- lm(JAWS_NE_Scale ~
PE_Scale +
PEN_Scale +
PREL_Scale +
PMEAN_Scale +
PACCOM_Scale)
summary(PERMA.JAWS)
lm.beta::lm.beta(PERMA.JAWS)
std_beta(PERMA.JAWS)
PFW.JAWS <- lm(JAWS_NE_Scale ~
PE_Scale +
PEN_Scale +
PREL_Scale +
PMEAN_Scale +
PACCOM_Scale +
PHEALTH_Scale +
PMIND_Scale +
PPWE_Scale +
PECON_Scale
)
summary(PFW.JAWS)
lm.beta::lm.beta(PFW.JAWS)
std_beta(PFW.JAWS)
```
```{r Turnover Intentions}
attach(FINALDATA9K)
PERMA.TI <- lm(TURNOVER_Scale ~
PE_Scale +
PEN_Scale +
PREL_Scale +
PMEAN_Scale +
PACCOM_Scale)
summary(PERMA.TI)
lm.beta::lm.beta(PERMA.TI)
std_beta(PERMA.TI)
PFW.TI <- lm(TURNOVER_Scale ~
PE_Scale +
PEN_Scale +
PREL_Scale +
PMEAN_Scale +
PACCOM_Scale +
PHEALTH_Scale +
PMIND_Scale +
PPWE_Scale +
PECON_Scale
)
summary(PFW.TI)
lm.beta::lm.beta(PFW.TI)
std_beta(PFW.TI)
```
```{r IADAPT}
attach(FINALDATA9K)
PERMA.IA <- lm(IADAPT_Scale ~
PE_Scale +
PEN_Scale +
PREL_Scale +
PMEAN_Scale +
PACCOM_Scale)
summary(PERMA.IA)
lm.beta::lm.beta(PERMA.IA)
std_beta(PERMA.IA)
PFW.IA <- lm(IADAPT_Scale ~
PE_Scale +
PEN_Scale +
PREL_Scale +
PMEAN_Scale +
PACCOM_Scale +
PHEALTH_Scale +
PMIND_Scale +
PPWE_Scale +
PECON_Scale
)
summary(PFW.IA)
lm.beta::lm.beta(PFW.IA)
std_beta(PFW.IA)
```
```{r OADAPT}
attach(FINALDATA9K)
PERMA.OA <- lm(OADAPT_Scale ~
PE_Scale +
PEN_Scale +
PREL_Scale +
PMEAN_Scale +
PACCOM_Scale)
summary(PERMA.OA)
lm.beta::lm.beta(PERMA.OA)
std_beta(PERMA.OA)
PFW.OA <- lm(OADAPT_Scale ~
PE_Scale +
PEN_Scale +
PREL_Scale +
PMEAN_Scale +
PACCOM_Scale +
PHEALTH_Scale +
PMIND_Scale +
PPWE_Scale +
PECON_Scale
)
summary(PFW.OA)
lm.beta::lm.beta(PFW.OA)
std_beta(PFW.OA)
```
```{r Predictive Validity Turnover}
attach(FINALDATA9K)
Model1 <- lm(TURNOVER_Scale ~
SWLS_Scale +
PSYCAP_Scale)
summary(Model1)
lm.beta::lm.beta(Model1)
std_beta(Model1)
Model2 <- lm(TURNOVER_Scale ~
SWLS_Scale +
PSYCAP_Scale +
DPF_Scale)
summary(Model2)
lm.beta::lm.beta(Model2)
std_beta(Model2)
```
```{r Predictive I<T<O Adaptivity}
attach(FINALDATA9K)
Model1 <- lm(IADAPT_Scale ~
SWLS_Scale +
PSYCAP_Scale)
Model1 <- lm(TADAPT_Scale ~
SWLS_Scale +
PSYCAP_Scale)
Model1 <- lm(OADAPT_Scale ~
SWLS_Scale +
PSYCAP_Scale)
summary(Model1)
lm.beta::lm.beta(Model1)
std_beta(Model1)
Model2 <- lm(IADAPT_Scale ~
SWLS_Scale +
PSYCAP_Scale +
DPF_Scale)
Model2 <- lm(TADAPT_Scale ~
SWLS_Scale +
PSYCAP_Scale +
DPF_Scale)
Model2 <- lm(OADAPT_Scale ~
SWLS_Scale +
PSYCAP_Scale +
DPF_Scale)
summary(Model2)
lm.beta::lm.beta(Model2)
std_beta(Model2)
```
```{r Predictive Validity Organizational Prof}
attach(FINALDATA9K)
Model1 <- lm(OPROF_Scale ~
SWLS_Scale +
PSYCAP_Scale)
summary(Model1)
lm.beta::lm.beta(Model1)
std_beta(Model1)
Model2 <- lm(OPROF_Scale ~
SWLS_Scale +
PSYCAP_Scale +
DPF_Scale)
summary(Model2)
lm.beta::lm.beta(Model2)
std_beta(Model2)
```
```{r Predictive I<T<O Proactivity}
attach(FINALDATA9K)
Model1 <- lm(IPROACT_Scale ~
SWLS_Scale +
PSYCAP_Scale)
Model1 <- lm(TPROACT_Scale ~
SWLS_Scale +
PSYCAP_Scale)
Model1 <- lm(OPROACT_Scale ~
SWLS_Scale +
PSYCAP_Scale)
summary(Model1)
lm.beta::lm.beta(Model1)
std_beta(Model1)
Model2 <- lm(IPROACT_Scale ~
SWLS_Scale +
PSYCAP_Scale +
DPF_Scale)
Model2 <- lm(TPROACT_Scale ~
SWLS_Scale +
PSYCAP_Scale +
DPF_Scale)
Model2 <- lm(OPROACT_Scale ~
SWLS_Scale +
PSYCAP_Scale +
DPF_Scale)
summary(Model2)
lm.beta::lm.beta(Model2)
std_beta(Model2)
```
<file_sep>/Scott'sRCheatSheet/Scott's.R.Cheatsheet.Rmd
---
title: "Data Science Cheatsheet"
author: "<NAME>, PhD"
date: "6/6/2020"
output: html_document
---
#Data Management
```{r Packages}
library(tidyverse)
```
```{r Importing and Exporting Data}
#Excel
## read in the first worksheet from the workbook myexcel.xlsx
## first row contains variable names
library(xlsx)
mydata <- read.xlsx("c:/myexcel.xlsx", 1)
## read in the worksheet named mysheet
mydata <- read.xlsx("c:/myexcel.xlsx", sheetName = "mysheet")
##Exporting data
library(xlsx)
write.xlsx(mydata, "c:/mydata.xlsx")
#SPSS
library(haven)
dataset <- read_sav(NULL)
View(dataset)
##Exporting data in SPSS
# write out text datafile and an SPSS program to read it
library(foreign)
write.foreign(mydata, "c:/mydata.xlsd", "c:/mydata.sav", package="SPSS")
```
```{r Data Cleaning and Transformation}
#Viewing Data
names(mydata) ## list the variables in mydata
str(mydata) ## list the structure of mydata
levels(mydata$v1) ## list levels of factor v1 in mydata
#Value Labels for Nominal variables
## variable v1 is coded 1, 2 or 3
## we want to attach value labels 1=red, 2=blue, 3=green
mydata$v1 <- factor(mydata$v1,
levels = c(1,2,3),
labels = c("red", "blue", "green"))
#Rename a variable
rename(mydata, newname=oldname)
#Recode Values in a variable
mydata$v1[mydata$v1==99] <- NA #It was 99 and now it is NA
#Missing Data
is.na(x) # returns TRUE of x is missing
na.rm=TRUE #exclude from analyses
mydata[!complete.cases(mydata),] # list rows of data that have missing values
newdata <- na.omit(mydata) # create new dataset without missing data
#Recoding Variables
mydata$agecat <- ifelse(mydata$age > 70,
c("older"), c("younger"))
mydata$agecat[age > 75] <- "Elder"
mydata$agecat[age > 45 & age <= 75] <- "Middle Aged"
mydata$agecat[age <= 45] <- "Young"
detach(mydata)
#Generate a sequence
seq(from , to, by)
#Filter Rows
filter(mydata, PERMA==2)
#Arrange
arrange(mydata, variable, variable)
arrange(mydata, desc(variable))
#Select
select(mydata, variable, variable)
select(mydata, variable, -variable) #Drop a variable
#Add New Variables
mutate(mydata,
newvariable = (Scott + Donaldson)) #Use transmute if you only want to keep the new variables
```
#Statistics
```{r Descriptives}
#Basic
range()
sum()
min() max()
#Central Tendency
mean()
sd()
median()
```
```{r EFA and CFA}
```
```{r IRT}
```
#Data Visualization
```{r Data Visualizations}
```
<file_sep>/TUPEDashboards/PlotsforDash.Rmd
---
title: "PlotsforDash"
author: "<NAME>, PhD"
date: "12/7/2020"
output: html_document
---
```{r Data Management}
library(flexdashboard)
library(knitr)
library(DT)
library(rpivotTable)
library(ggplot2)
library(plotly)
library(plyr)
library(dplyr)
library(readxl)
library(tidyverse)
library(crosstalk)
library(leaflet)
library(htmltools)
library(rgdal)
library(geojsonio)
library(rjson)
library(scatterD3)
Master <- read_excel("~/Desktop/CDE.ComprehensiveData.xlsx",
sheet = "Master")
ReachStats <- read_excel("~/Desktop/CDE.ComprehensiveData.xlsx",
sheet = "ReachStatistics")
Master$Agency <- as.factor(Master$Agency)
Master$Region <- as.factor(Master$Region)
Master$Location <- as.factor(Master$Location)
Master$ReportingFrequency <- as.factor(Master$ReportingFrequency)
Master$ExternalEvaluator <- as.factor(Master$ExternalEvaluator)
Master$TotalBudget <- as.numeric(Master$TotalBudget)
Master$EvaluationBudget <- as.numeric(Master$EvaluationBudget)
Master$ADA <- as.numeric(Master$ADA)
Master$County <- as.factor(Master$County)
#ReachStatistics
ReachStats$Agency <- as.factor(ReachStats$Agency)
ReachStats$ProgramArea <- as.factor(ReachStats$ProgramArea)
ReachStats$SchoolParents <- as.numeric(ReachStats$SchoolParents)
ReachStats$AvgDoseMin <- as.numeric(ReachStats$AvgDoseMin)
```
```{r Cholorpleth Map}
attach(Master)
Cali <- geojsonio::geojson_read("/Users/ScottDonaldson/Desktop/Cali.json",
what = "sp")
bins <- c(0, 13000, 33000, 150000, Inf)
pal <- colorBin("Dark2", domain = Master$TotalReach, bins = bins)
TUPEMAP <- leaflet(Cali) %>%
addTiles() %>%
addMarkers(lng = Master$Lng,
lat = Master$Lat,
label = Master$Agency,
labelOptions = (textsize = "50px")) %>%
setView(-119.2321, 36.9859, zoom = 5.9) %>%
addProviderTiles(providers$Esri.NatGeoWorldMap) %>%
addPolygons(stroke = TRUE,
opacity = 1,
fillOpacity = 0.5,
smoothFactor = 0.5,
color="black",
fillColor = ~pal(Master$TotalReach),
weight = 1,
highlightOptions = TRUE) %>%
addLegend(values=~Master$TotalReach,
pal=pal,
title="Proposed Project Reach",
position = "topright")
TUPEMAP
```
```{r Student Crosstalk}
StudentReach <- pivot_longer(ReachStats,
cols = c(5:35),
names_to = "Target_Population",
values_to = "Count",
values_drop_na = TRUE)
StudentReach <- StudentReach[which(
StudentReach$ProgramArea=='NeedsAssessment' |
StudentReach$ProgramArea=='Prevention' |
StudentReach$ProgramArea=='PreventionIntervention' |
StudentReach$ProgramArea=='PreventionInterventionYD' |
StudentReach$ProgramArea=='PreventionYD' |
StudentReach$ProgramArea=='PreventionInterventionCessation' |
StudentReach$ProgramArea=='Intervention' |
StudentReach$ProgramArea=='InterventionYD' |
StudentReach$ProgramArea=='InterventionCessation' |
StudentReach$ProgramArea=='InterventionYD' |
StudentReach$ProgramArea=='Cessation' |
StudentReach$ProgramArea=='CessationYD' |
StudentReach$ProgramArea=='YouthDevelopment'),
c(1,3,4,24:27, 34:36)
]
Student_reach <- SharedData$new(StudentReach, ~ActivityName)
bscols(widths = c(2,10),
filter_select("AG",
"Agency",
Student_reach,
~Agency),
ggplotly(ggplot(data=Student_reach,
aes(x= reorder(ProgramArea, -Count, FUN = sum),
y=Count,
fill=Target_Population,
na.rm = TRUE)) +
geom_bar(stat="identity",
position = "stack") +
scale_y_continuous(limits = c(0, 150000),
breaks = c(2000,
10000,
20000,
50000,
100000,
150000
)) +
theme_classic() +
labs(title = "Student Reach Profile",
x = "Program Area",
y = "#Students") +
guides(fill=FALSE) +
scale_x_discrete(labels=c("Prev",
"PrevYD",
"Cess",
"Int",
"IntYD",
"YD",
"PrevInt",
"PrevIntCess",
"CessYD",
"PrevIntYD",
"IntCess",
"Needs")),
width = 1200,
height = 500)
)
```
```{r Parents Crosstalk}
ParentReach <- pivot_longer(ReachStats,
cols = c(36:54),
names_to = "Target_Population",
values_to = "Count")
ParentReach <- ParentReach[which(ParentReach$ProgramArea=="Family"),
c(1,3,4,36:39, 46:48)]
Family_reach <- SharedData$new(ParentReach, ~ActivityName)
bscols(widths = c(2,10),
filter_select("AG",
"Agency",
Family_reach,
~Agency),
ggplotly(ggplot(data=Family_reach,
aes(x=Target_Population,
y=Count,
fill=Agency,
na.rm = TRUE)) +
geom_bar(stat="identity",
position = "stack") +
scale_y_continuous(limits = c(0, 100000),
breaks = seq(0, 100000, 20000)) +
scale_x_discrete(labels=c("AA",
"Armenian",
"Asian",
"Cont",
"Fost.",
"FRPM",
"Pub.",
"Girls",
"Hisp.",
"Home.",
"LGTBQ",
"LowSes",
"Military",
"NA",
"New",
"NH/PI",
"NT",
"Parents",
"Users")) +
guides(fill=FALSE) +
theme_classic() +
labs(title = "Parents Reach",
x = "Target Population",
y = "#Participants"),
width = 1400,
height = 600)
)
```
```{r Parents Dattable}
#Parents Datatable
datatable(Family_reach,
extensions="Scroller",
style="bootstrap",
class="compact",
width=1000,
height = 500,
options=list(deferRender=TRUE,
scrollY=300,
scroller=TRUE))
```
```{r Staff Crosstalk }
StaffReach <- pivot_longer(ReachStats,
cols = c(61:64),
names_to = "Target_Population",
values_to = "Count")
StaffReach <- StaffReach[which(StaffReach$ProgramArea=="Staff"),
c(1,3,4,55:63)]
staff_reach <- SharedData$new(StaffReach, ~ActivityName)
bscols(widths = c(2,10),
filter_select("AG",
"Agency",
staff_reach,
~Agency),
ggplotly(ggplot(data=staff_reach,
aes(x=Target_Population,
y=Count,
fill=Agency,
na.rm = TRUE)) +
geom_bar(stat="identity",
position = "stack") +
scale_y_continuous(limits = c(0, 40000),
breaks = seq(0, 40000, 5000)) +
scale_x_discrete(labels=c("Non-TUPE Certified",
"Non-TUPE Classified",
"TUPE Certified",
"TUPE Classified")) +
guides(fill=FALSE) +
theme_classic() +
labs(title = "Staff Reach",
x = "Target Population",
y = "#Participants"),
width = 1000,
height = 600)
)
#Parents Datatable
datatable(staff_reach,
extensions="Scroller",
style="bootstrap",
class="compact",
width=1000,
height = 500,
options=list(deferRender=TRUE,
scrollY=300,
scroller=TRUE))
```
```{r Evaluation Plots}
#Upload the Rubric
include_graphics(path = "/Users/ScottDonaldson/Desktop/UCSD/TUPE/Evaluation/Dashboard/TUPEDashboards/FIles/Rubric.pdf")
#Bar Chart of QI Scores
attach(Master)
ggplotly(ggplot(Master,
aes(x=Agency,
y=QIScore,
fill=County)) +
geom_col() +
theme_classic() +
theme(axis.ticks = element_blank(), axis.text.x = element_blank())
)
#Pie Chart with Reporting Frequency
Reporting <- plot_ly(Master,
labels = ~ReportingFrequency,
type = 'pie')
Reporting <- Reporting %>% layout(title = 'Evaluation Reporting Frequency')
Reporting
#Pie Chart with External Evaluators
External <- plot_ly(Master,
labels = ~ExternalEvaluator,
type = 'pie')
External <- External %>% layout(title = 'External Evaluator')
External
#Data Sources
```
```{r Data Methods Crosstalk}
attach(Datasources)
DS <- pivot_longer(Datasources,
cols = c(2:27),
names_to = "DataSource",
values_to = "Count")
DS$TOTAL.GRANTEE <- round(DS$TOTAL.GRANTEE, digits = 1)
DS$Count <- round(DS$Count, digits = 1)
DataSources_shared <- SharedData$new(DS, ~Grantee)
bscols(ggplotly(ggplot(data=DataSources_shared,
aes(x= reorder(Grantee, -TOTAL.GRANTEE, FUN = sum),
y=Count,
fill=DataSource,
na.rm = TRUE)) +
geom_bar(stat="identity",
position = "stack") +
scale_y_continuous(limits = c(0, 10),
breaks = c(0,
2,
4,
6,
8,
10)) +
scale_x_discrete(labels=c()) +
guides(fill=FALSE) +
theme_classic() +
labs(x = "Agency",
y = "#Methods"),
width = 1000,
height = 600)
)
```
```{r Data Methods Table}
datatable(Datasources,
extensions="Scroller",
style="bootstrap",
class="compact",
width=1000,
height = 500,
options=list(deferRender=TRUE,
scrollY=300,
scroller=TRUE)
)
```
```{r Format Table}
```
<file_sep>/MTMM Project/PsyCap.12.22.Rmd
---
title: "PsyCap MTMM"
author: "<NAME>, PhD"
date: "12/22/2020"
output: html_document
---
#Data Manipulation and Management
```{r echo=TRUE, message=FALSE, warning=FALSE}
#Setup
knitr::opts_chunk$set(
echo = FALSE,
message = FALSE,
warning = FALSE
)
#Upload packages
library(haven)
library(careless)
library(tidyverse)
library(psych)
library(Hmisc)
library(magrittr)
library(pastecs)
library(QuantPsyc)
library(ppcor)
library(GPArotation)
library(gmodels)
#Import from SPSS
MTMM_Clean <- read_sav("MTMM.Clean.sav")
MTMM.ID <- MTMM_Clean %>% mutate(id = row_number())
Demos <- MTMM.ID[, c(82:100, 165:189, 259:277, 347:371, 383)]
#Remove careless responding
##Keep track of all scale items for EMP1(C) and EMP1(C)
Final <- MTMM.ID[, c(11:81, 101:164, 190:258, 278:346, 383)]
##Mahal Distance (Across Pairs)
data.frame(colnames(Final))
MD <- mahad(Final, flag = TRUE, confidence = 0.999)
filter(MD, flagged == TRUE)
Final2 <- Final[-c(165), ]
##Longstring Invariant Responding
###EMP1 Lonstring
EMP1.L <- Final2[ , c(136:204, 274)]
longstring_EMP1 <- longstring(EMP1.L)
longstring_EMP1 <- as.data.frame(longstring_EMP1)
boxplot(longstring_EMP1)
quantile(longstring_EMP1$longstring_EMP1)
table(longstring_EMP1)
###EMP1C Longstring
EMP1C.L <- Final2[ , c(205:273)]
longstring_EMP1C <- longstring(EMP1C.L)
longstring_EMP1C <- as.data.frame(longstring_EMP1C)
boxplot(longstring_EMP1C)
quantile(longstring_EMP1C$longstring_EMP1C)
table(longstring_EMP1C)
#Clean up workspace
rm(list = "EMP1.L", "EMP1C.L", "EMP1.L", "EMP1C.L",
"Final", "longstring_EMP1" , "longstring_EMP1C",
"longstring_EMP1" , "longstring_EMP1C", "MD",
"MTMM_Clean", "MTMM.ID")
#Relational Data (Join the demos with ID variable)
##We want to join the scale data with Final.pairs to demographic data from MTMM_Clean
Final.Pairs2 <- Final2 %>% left_join(Demos, by = "id")
Final2 <- Final.Pairs2
rm(Final.Pairs2)
ScaleData <- Final2
##E1
ScaleData <- mutate(ScaleData,
PREL.Scale.E1 = (PREL_1_EMP1 + PREL_2_EMP1 + PREL_3_EMP1 +
PREL_4_EMP1)/4,
PE.Scale.E1 = (PE_1_EMP1 + PE_2_EMP1 + PE_3_EMP1)/3,
PMEAN.Scale.E1 = (PMEAN_1_EMP1 + PMEAN_2_EMP1 + PMEAN_3_EMP1)/3,
PACCOM.Scale.E1 = (PACCOM_1_EMP1 + PACCOM_2_EMP1 + PACCOM_3_EMP1)/3,
PEN.Scale.E1 = (PEN_1_EMP1 + PEN_2_EMP1 + PEN_3_EMP1)/3,
PECON.Scale.E1 = (PECON_1_EMP1 + PECON_2_EMP1 + PECON_3_EMP1)/3,
PMIND.Scale.E1 = (PMIND_1_EMP1 + PMIND_2_EMP1 + PMIND_3_EMP1)/3,
PHEALTH.Scale.E1 = (PPHealth_1_EMP1 + PPHealth_2_EMP1 + PPHealth_3_EMP1 +
PPHealth_4_EMP1)/4,
PPWE.Scale.E1 = (PPWE_1_EMP1 + PPWE_2_EMP1 + PPWE_3_EMP1)/3,
PERMA.E1 = (PREL.Scale.E1 + PE.Scale.E1 + PMEAN.Scale.E1 +
PACCOM.Scale.E1 + PEN.Scale.E1)/5,
PF.W.Scale.E1 = (PREL.Scale.E1 + PE.Scale.E1 + PMEAN.Scale.E1 +
PACCOM.Scale.E1 + PEN.Scale.E1 + PECON.Scale.E1 +
PMIND.Scale.E1 + PHEALTH.Scale.E1 + PPWE.Scale.E1)/9,
#E2C
PREL.Scale.E2C = (PREL_1_EMP1C + PREL_2_EMP1C + PREL_3_EMP1C +
PREL_4_EMP1C)/4,
PE.Scale.E2C = (PE_1_EMP2_C + PE_2_EMP2_C + PE_3_EMP2_C)/3,
PMEAN.Scale.E2C = (PMEAN_1_EMP2_C + PMEAN_2_EMP2_C + PMEAN_3_EMP2_C)/3,
PACCOM.Scale.E2C = (PACCOM_1_EMP2_C + PACCOM_2_EMP2_C + PACCOM_3_EMP2_C)/3,
PEN.Scale.E2C = (PEN_1_EMP2_C + PEN_2_EMP2_C + PEN_3_EMP2_C)/3,
PECON.Scale.E2C = (PECON_1_EMP2_C + PECON_2_EMP2_C + PECON_3_EMP2_C)/3,
PMIND.Scale.E2C = (PMIND_1__EMP2_C + PMIND_2_EMP2_C + PMIND_3_EMP2_C)/3,
PHEALTH.Scale.E2C= (PPHealth_1_EMP2_C + PPHealth_2_EMP2_C + PPHealth_3_EMP2_C +
PPHealth_4_EMP2_C)/4,
PPWE.Scale.E2C = (PPWE_1_EMP2_C + PPWE_2_EMP2_C + PPWE_3_EMP2_C)/3,
PERMA.E2C = (PREL.Scale.E2C + PE.Scale.E2C + PMEAN.Scale.E2C +
PACCOM.Scale.E2C + PEN.Scale.E2C)/5,
PF.W.Scale.E2C = (PREL.Scale.E2C + PE.Scale.E2C + PMEAN.Scale.E2C +
PACCOM.Scale.E2C + PEN.Scale.E2C + PECON.Scale.E2C +
PMIND.Scale.E2C + PHEALTH.Scale.E2C + PPWE.Scale.E2C)/9)
#Scoring PERMA and PF-W for E2 and E1C
##EMP1
ScaleData <- mutate(ScaleData,
PREL.Scale.E2 = (PREL_1_EMP2 + PREL_2_EMP2 + PREL_3_EMP2 +
PREL_4_EMP2)/4,
PE.Scale.E2 = (PE_1_EMP2 + PE_2_EMP2 + PE_3_EMP2)/3,
PMEAN.Scale.E2 = (PMEAN_1_EMP2 + PMEAN_2_EMP2 + PMEAN_3_EMP2)/3,
PACCOM.Scale.E2 = (PACCOM_1_EMP2 + PACCOM_2_EMP2 + PACCOM_3_EMP2)/3,
PEN.Scale.E2 = (PEN_1_EMP2 + PEN_2_EMP2 + PEN_3_EMP2)/3,
PECON.Scale.E2 = (PECON_1_EMP2 + PECON_2_EMP2 + PECON_3_EMP2)/3,
PMIND.Scale.E2 = (PMIND_1_EMP2 + PMIND_2_EMP2 + PMIND_3_EMP2)/3,
PHEALTH.Scale.E2 = (PPHealth_1_EMP2 + PPHealth_2_EMP2 + PPHealth_3_EMP2 +
PPHealth_4_EMP2)/4,
PPWE.Scale.E2 = (PPWE_1_EMP2 + PPWE_2_EMP2 + PPWE_3_EMP2)/3,
PERMA.E2 = (PREL.Scale.E2 + PE.Scale.E2 + PMEAN.Scale.E2 +
PACCOM.Scale.E2 + PEN.Scale.E2)/5,
PF.W.Scale.E2 = (PREL.Scale.E2 + PE.Scale.E2 + PMEAN.Scale.E2 +
PACCOM.Scale.E2 + PEN.Scale.E2 + PECON.Scale.E2 +
PMIND.Scale.E2 + PHEALTH.Scale.E2 + PPWE.Scale.E2)/9,
#Add coworker
PREL.Scale.E1C = (PREL_1_EMP1C + PREL_2_EMP1C + PREL_3_EMP1C +
PREL_4_EMP1C)/4,
PE.Scale.E1C = (PE_1_EMP1C + PE_2_EMP1C + PE_3_EMP1C)/3,
PMEAN.Scale.E1C = (PMEAN_1_EMP1C + PMEAN_2_EMP1C + PMEAN_3_EMP1C)/3,
PACCOM.Scale.E1C = (PACCOM_1_EMP1C + PACCOM_2_EMP1C + PACCOM_3_EMP1C)/3,
PEN.Scale.E1C = (PEN_1_EMP1C + PEN_2_EMP1C + PEN_3_EMP1C)/3,
PECON.Scale.E1C = (PECON_1_EMP1C + PECON_2_EMP1C + PECON_3_EMP1C)/3,
PMIND.Scale.E1C = (PMIND_1_EMP1C + PMIND_2_EMP1C + PMIND_3_EMP1C)/3,
PHEALTH.Scale.E1C= (PPHealth_1_EMP1C + PPHealth_2_EMP1C + PPHealth_3_EMP1C +
PPHealth_4_EMP1C)/4,
PPWE.Scale.E1C = (PPWE_1_EMP1C + PPWE_2_EMP1C + PPWE_3_EMP1C)/3,
PERMA.E1C = (PREL.Scale.E1C + PE.Scale.E1C + PMEAN.Scale.E1C +
PACCOM.Scale.E1C + PEN.Scale.E1C)/5,
PF.W.Scale.E1C = (PREL.Scale.E1C + PE.Scale.E1C + PMEAN.Scale.E1C +
PACCOM.Scale.E1C + PEN.Scale.E1C + PECON.Scale.E1C +
PMIND.Scale.E1C + PHEALTH.Scale.E1C + PPWE.Scale.E1C)/9
)
#Scoring for PsyCap E1 and E2
ScaleData <- mutate(ScaleData,
PsyCap.Hope.E1 = (Psy_H_1_EMP1 + Psy_H_2_EMP1)/2,
PsyCap.SE.E1 = (Psy_SE_1_EMP1 + Psy_SE_2_EMP1)/2,
PsyCap.Res.E1 = (Psy_R_1_EMP1 + Psy_R_2_EMP1)/2,
PsyCap.O.E1 = (Psy_0_1_EMP1 + Psy_O_2_EMP1)/2,
PsyCap.E1 = (Psy_H_1_EMP1 + Psy_H_2_EMP1 +
Psy_SE_1_EMP1 + Psy_SE_2_EMP1 +
Psy_R_1_EMP1 + Psy_R_2_EMP1 +
Psy_0_1_EMP1 + Psy_O_2_EMP1)/8,
PsyCap.Hope.E2C = (Psy_H_1_EMP2_C + Psy_H_2_EMP2_C)/2,
PsyCap.SE.E2C = (Psy_SE_1_EMP2_C + Psy_SE_2_EMP2_C)/2,
PsyCap.Res.E2C = (Psy_R_1_EMP2_C + Psy_R_2_EMP2_C)/2,
PsyCap.O.E2C = (Psy_0_1_EMP2_C + Psy_O_2_EMP2_C)/2,
PsyCap.E2C = (Psy_H_1_EMP2_C + Psy_H_2_EMP2_C +
Psy_SE_1_EMP2_C + Psy_SE_2_EMP2_C +
Psy_R_1_EMP2_C + Psy_R_2_EMP2_C +
Psy_0_1_EMP2_C + Psy_O_2_EMP2_C)/8)
#Scoring PsyCap E2 and E1C
ScaleData <- mutate(ScaleData,
PsyCap.Hope.E2 = (Psy_H_1_EMP2 + Psy_H_2_EMP2)/2,
PsyCap.SE.E2 = (Psy_SE_1_EMP2 + Psy_SE_1_EMP2)/2,
PsyCap.Res.E2 = (Psy_R_1_EMP2 + Psy_R_1_EMP2)/2,
PsyCap.O.E2 = (Psy_0_1_EMP2 + Psy_O_2_EMP2)/2,
PsyCap.E2 = (Psy_H_1_EMP2 + Psy_H_2_EMP2 +
Psy_SE_1_EMP2 + Psy_SE_1_EMP2 +
Psy_R_1_EMP2 + Psy_R_2_EMP2 +
Psy_0_1_EMP2 + Psy_O_2_EMP2)/8,
PsyCap.Hope.E1C = (Psy_H_1_EMP1C + Psy_H_2_EMP1C)/2,
PsyCap.SE.E1C = (Psy_SE_1_EMP1C + Psy_SE_1_EMP1C)/2,
PsyCap.Res.E1C = (Psy_R_1_EMP1C + Psy_R_1_EMP1C)/2,
PsyCap.O.E1C = (Psy_0_1_EMP1C + Psy_O_2_EMP2_C)/2,
PsyCap.E1C = (Psy_H_1_EMP1C + Psy_H_2_EMP1C +
Psy_SE_1_EMP1C + Psy_SE_1_EMP1C +
Psy_R_1_EMP1C + Psy_R_2_EMP1C +
Psy_0_1_EMP1C + Psy_O_2_EMP1C)/8)
#Scoring for SWL E1 and E2C
ScaleData <- mutate(ScaleData,
SWLS.E1 = (SWL_1_EMP1 + SWL_2_EMP1 +SWL_3_EMP1 + SWL_4_EMP1 +
SWL_5_EMP1)/5,
SWLS.E2C = (SWL_1__EMP2_C + SWL_2__EMP2_C +SWL_3__EMP2_C +
SWL_4__EMP2_C + SWL_5__EMP2_C)/5)
#Scoring PWB for E1 and E2C
ScaleData <-
mutate(ScaleData,
OPRO.E1 = (PRO1_EMP1 + PRO2_EMP1 + PRO3_EMP1)/3,
OADAPT.E1 = (ADAPT1_EMP1 + ADAPT2_EMP1 + ADAPT3_EMP1)/3,
OPROF.E1 = (PROF1_EMP1 + PROF2_EMP1 + PROF3_EMP1)/3,
OPRO.E2C = (OPRO1_EMP2_C + OPRO2_EMP2_C + OPROF3_EMP2_C)/3,
OADAPT.E2C= (OADAPT1_EMP2_C + OADAPT2_EMP2_C + OADAPT3_EMP2_C)/3,
OPROF.E2C = (OPROF1_EMP2_C + OPROF2_EMP2_C + OPROF3_EMP2_C)/3)
#Scoring PWB for E2 and E1C
ScaleData <-
mutate(ScaleData,
OPRO.E2 = (PRO1_EMP2 + PRO2_EMP2 + PRO3_EMP2)/3,
OADAPT.E2 = (ADAPT1_EMP2 + ADAPT2_EMP2 + ADAPT3_EMP2)/3,
OPROF.E2 = (PROF1_EMP2 + PROF2_EMP2 + PROF3_EMP2)/3,
OPRO.E1C = (OPRO1_EMP1C + OPRO2_EMP1C + OPRO3_EMP1C)/3,
OADAPT.E1C= (OADAPT1_EMP1C + OADAPT2_EMP1C + OADAPT3_EMP1C)/3,
OPROF.E1C = (OPROF1_EMP1C + OPROF2_EMP1C + OPROF3_EMP1C)/3,
#Scoring JAWS
JAWS.PE.E1 = (J1_EMP1 + J2_EMP1 + J3_EMP1 + J4_EMP1 + J5_EMP1 +
J6_EMP1 + J7_EMP1 + J8_EMP1 + J9_EMP1 + J10_EMP1)/10,
JAWS.PE.E2C= (J1_EMP2_C + J2_EMP2_C + J3_EMP2_C + J4_EMP2_C + J5_EMP2_C +
J6_EMP2_C + J7_EMP2_C + J8_EMP2_C + J9_EMP2_C + J10_EMP2_C)/10,
JAWS.PE.E2 = (J1_EMP2 + J2_EMP2 + J3_EMP2 + J4_EMP2 + J5_EMP2 +
J6_EMP2 + J7_EMP2 + J8_EMP2 + J9_EMP2 + J10_EMP2)/10,
JAWS.PE.E1C= (J1_EMP1C + J2_EMP1C + J3_EMP1C + J4_EMP1C + J5_EMP1C +
J6_EMP1C + J7_EMP1C + J8_EMP1C + J9_EMP1C + J10_EMP1C)/10)
#Scoring Turnover for all, echo=false}
##EMP1
ScaleData$Turnover_1_EMP1 <- as.numeric(ScaleData$Turnover_1_EMP1)
ScaleData$Turnover_2_EMP1 <- as.numeric(ScaleData$Turnover_2_EMP1)
ScaleData$Turnover_3_EMP1 <- as.numeric(ScaleData$Turnover_3_EMP1)
ScaleData$Turnover_4_R_EMP1 <- as.numeric(ScaleData$Turnover_4_R_EMP1)
ScaleData$Turnover_5_EMP1 <- as.numeric(ScaleData$Turnover_5_EMP1)
##EMP2C
ScaleData$Turnover_1_EMP2_C <- as.numeric(ScaleData$Turnover_1_EMP2_C)
ScaleData$Turnover_2_EMP2_C <- as.numeric(ScaleData$Turnover_2_EMP2_C)
ScaleData$Turnover_3_EMP2_C <- as.numeric(ScaleData$Turnover_3_EMP2_C)
ScaleData$Turnover_4_R_EMP2_C <- as.numeric(ScaleData$Turnover_4_R_EMP2_C)
ScaleData$Turnover_5_EMP2_C <- as.numeric(ScaleData$Turnover_3_EMP2_C)
##EMP2
ScaleData$Turnover_1_EMP2 <- as.numeric(ScaleData$Turnover_1_EMP2)
ScaleData$Turnover_2_EMP2 <- as.numeric(ScaleData$Turnover_2_EMP2)
ScaleData$Turnover_3_EMP2 <- as.numeric(ScaleData$Turnover_3_EMP2)
ScaleData$Turnover_4_R_EMP2 <- as.numeric(ScaleData$Turnover_4_R_EMP2)
ScaleData$Turnover_5_EMP2 <- as.numeric(ScaleData$Turnover_3_EMP2)
##EMP1C
ScaleData$Turnover_1_EMP1C <- as.numeric(ScaleData$Turnover_1_EMP1C)
ScaleData$Turnover_2_EMP1C <- as.numeric(ScaleData$Turnover_2_EMP1C)
ScaleData$Turnover_3_EMP1C <- as.numeric(ScaleData$Turnover_3_EMP1C)
ScaleData$Turnover_4_R_EMP1C <- as.numeric(ScaleData$Turnover_4_R_EMP1C)
ScaleData$Turnover_5_EMP1C <- as.numeric(ScaleData$Turnover_3_EMP1C)
#Recode Turnover and Reverse the 4th and 5th Item
##EMP1
ScaleData$Turnover_1_EMP1 <- recode(ScaleData$Turnover_1_EMP1,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_2_EMP1 <- recode(ScaleData$Turnover_2_EMP1,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_3_EMP1 <- recode(ScaleData$Turnover_3_EMP1,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_4_R_EMP1 <- recode(ScaleData$Turnover_4_R_EMP1,
'20' = 5,
'21' = 4,
'22' = 3,
'23' = 2,
'24' = 1)
ScaleData$Turnover_5_EMP1 <- recode(ScaleData$Turnover_5_EMP1,
'20' = 5,
'21' = 4,
'22' = 3,
'23' = 2,
'24' = 1)
##EMP2C
ScaleData$Turnover_1_EMP2_C <- recode(ScaleData$Turnover_1_EMP2_C,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_2_EMP2_C <- recode(ScaleData$Turnover_2_EMP2_C,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_3_EMP2_C <- recode(ScaleData$Turnover_3_EMP2_C,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_4_R_EMP2_C <- recode(ScaleData$Turnover_4_R_EMP2_C,
'20' = 5,
'21' = 4,
'22' = 3,
'23' = 2,
'24' = 1)
ScaleData$Turnover_5_EMP2_C <- recode(ScaleData$Turnover_5_EMP2_C,
'20' = 5,
'21' = 4,
'22' = 3,
'23' = 2,
'24' = 1)
##EMP2
ScaleData$Turnover_1_EMP2 <- recode(ScaleData$Turnover_1_EMP2,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_2_EMP2 <- recode(ScaleData$Turnover_2_EMP2,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_3_EMP2 <- recode(ScaleData$Turnover_3_EMP2,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_4_R_EMP2 <- recode(ScaleData$Turnover_4_R_EMP2,
'20' = 5,
'21' = 4,
'22' = 3,
'23' = 2,
'24' = 1)
ScaleData$Turnover_5_EMP2 <- recode(ScaleData$Turnover_5_EMP2,
'20' = 5,
'21' = 4,
'22' = 3,
'23' = 2,
'24' = 1)
##EMP1C
ScaleData$Turnover_1_EMP1C <- recode(ScaleData$Turnover_1_EMP1C,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_2_EMP1C <- recode(ScaleData$Turnover_2_EMP1C,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_3_EMP1C <- recode(ScaleData$Turnover_3_EMP1C,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_4_R_EMP1C <- recode(ScaleData$Turnover_4_R_EMP1C,
'20' = 5,
'21' = 4,
'22' = 3,
'23' = 2,
'24' = 1)
ScaleData$Turnover_5_EMP1C <- recode(ScaleData$Turnover_5_EMP1C,
'20' = 5,
'21' = 4,
'22' = 3,
'23' = 2,
'24' = 1)
#Scoring Turnover E1 and E2C
ScaleData <-
mutate(ScaleData,
Turnover.E1 = (Turnover_1_EMP1 + Turnover_2_EMP1 + Turnover_3_EMP1 + Turnover_4_R_EMP1 +
Turnover_5_EMP1)/5,
Turnover.E2C = (Turnover_1_EMP2_C + Turnover_2_EMP2_C + Turnover_3_EMP2_C +
Turnover_4_R_EMP2_C + Turnover_5_EMP2_C)/5)
#Scoring Turnover E2 and E1C
ScaleData <-
mutate(ScaleData,
Turnover.E2 = (Turnover_1_EMP2 + Turnover_2_EMP2 + Turnover_3_EMP2 + Turnover_4_R_EMP2 +
Turnover_5_EMP2)/5,
Turnover.E1C = (Turnover_1_EMP1C + Turnover_2_EMP1C + Turnover_3_EMP1C + Turnover_4_R_EMP1C +
Turnover_5_EMP1C)/5)
#Demographics Scoring
##Employee 1 Demos
###Subset only Scale Scores and Demographics
TidyData <- ScaleData[, c(274:293, 363:384)]
TidyData$Ethnicity_EMP1_2[TidyData$Ethnicity_EMP1_2 %in% 1] <- 2
TidyData$Ethnicity_EMP1_3[TidyData$Ethnicity_EMP1_3 %in% 1] <- 3
TidyData$Ethnicity_EMP1_4[TidyData$Ethnicity_EMP1_4 %in% 1] <- 4
TidyData$Ethnicity_EMP1_5[TidyData$Ethnicity_EMP1_5 %in% 1] <- 5
TidyData$Ethnicity_EMP1_6[TidyData$Ethnicity_EMP1_6 %in% 1] <- 6
TidyData$Ethnicity_EMP1_7[TidyData$Ethnicity_EMP1_7 %in% 1] <- 7
#Unite Ethnicity into ETH.NUll and ETH.E2
TidyData <- unite(TidyData, ETH.E1, Ethnicity_EMP1_1, Ethnicity_EMP1_2, Ethnicity_EMP1_3, Ethnicity_EMP1_4, Ethnicity_EMP1_5, Ethnicity_EMP1_6, Ethnicity_EMP1_7, sep = "_", remove = FALSE, na.rm = TRUE)
##Recode into factor variables for both employees (Etnicity, Degree, Industry, JobFunction, Income)
TidyData$ETH.E1 <- as.factor(as.character(TidyData$ETH.E1))
TidyData$Degree_EMP1 <- as.factor(as.character(TidyData$Degree_EMP1))
TidyData$Industry_EMP1 <- as.factor(as.character(TidyData$Industry_EMP1))
TidyData$JobFunction_EMP1 <- as.factor(as.character(TidyData$JobFunction_EMP1))
TidyData$Income_EMP1 <- as.factor(as.character(TidyData$Income_EMP1))
TidyData$Gender_EMP1 <- as.factor(as.character(TidyData$Gender_EMP1))
TidyData <- TidyData %>% mutate(Degree.E1 = fct_recode(Degree_EMP1,
"Associate" = "1",
"Bachelor" = "2" ,
"Master" = "3" ,
"Doctorate" = "4" ,
"Highschool or less" = "5"
))
TidyData <- TidyData %>% mutate(Industry.E1 = fct_recode(Industry_EMP1,
"Banking" = "1",
"Education" = "2" ,
"Food & Beverage" = "3" ,
"Government" = "4" ,
"Healthcare" = "5",
"Manufacturing" = "6",
"Media & Entertainment" = "7",
"Retail, Wholesale, & Distribution" = "8",
"Software & IT" = "9",
"Nonprofit" = "10",
"Other" = "11"
))
TidyData <- TidyData %>% mutate(JobFunction.E1 = fct_recode(JobFunction_EMP1,
"Accounting & Finance" = "1",
"Administrative" = "2" ,
"Arts & Design" = "3" ,
"Education" = "4" ,
"Engineering" = "5",
"IT" = "6",
"Marketing, Sales, & Business Dev." = "7",
"Management" = "8",
"Operations" = "9",
"Other" = "10"
))
TidyData <- TidyData %>% mutate(Income.E1 = fct_recode(Income_EMP1,
"Less than 25k" = "1",
"25-49k" = "2" ,
"50-75k" = "3" ,
"75-99k" = "4" ,
"100-150k" = "5",
"150+" ="6"
))
data.frame(colnames(TidyData))
#####
Employee1.Demos <- TidyData[, c(1, 2, 11, 12, 44:47)]
Employee1.Demos <-Employee1.Demos %>% mutate(Eth.Final.E1 = fct_recode(ETH.E1,
"Multiracial" = "1_2_3_4_5_6_NA",
"Multiracial" = "NA_NA_3_NA_NA_6_NA" ,
"Multiracial" = "NA_NA_NA_4_NA_6_NA",
"Multiracial" = "NA_NA_NA_NA_5_6_NA",
"Multiracial" = "1_NA_3_NA_5_6_NA",
"Multiracial" = "1_NA_NA_NA_5_NA_NA",
"Asian" = "NA_NA_3_NA_NA_NA_NA",
"Hispanic" = "NA_NA_NA_NA_5_NA_NA" ,
"White" = "NA_NA_NA_NA_NA_6_NA",
"Multiracial" = "NA_NA_NA_NA_NA_NA_7",
"Black" = "1_NA_NA_NA_NA_NA_NA",
"NHOPI" = "NA_NA_NA_4_NA_NA_NA",
"ANAI" = "NA_2_NA_NA_NA_NA_NA"))
Employee1.Demos <-Employee1.Demos %>% mutate(Degree.Final = fct_recode(Degree.E1,
"Associate" = "1",
"Bachelor" = "2" ,
"Master" = "3" ,
"Doctorate" = "4" ,
"Highschool or less" = "5"
))
Employee1.Demos <-Employee1.Demos %>% mutate(Gender.Final = fct_recode(Gender_EMP1,
"Male" = "1",
"Female" = "2" ,
"Other" = "3"
))
Employee1.Demos <-Employee1.Demos %>% mutate(Industry.Final = fct_recode(Industry.E1,
"Banking" = "1",
"Education" = "2" ,
"Food & Beverage" = "3" ,
"Government" = "4" ,
"Healthcare" = "5",
"Manufacturing" = "6",
"Media & Entertainment" = "7",
"Retail, Wholesale, & Distribution" = "8",
"Software & IT" = "9",
"Nonprofit" = "10",
"Other" = "11"
))
Employee1.Demos <-Employee1.Demos %>% mutate(JobFunction.Final = fct_recode(JobFunction.E1,
"Accounting & Finance" = "1",
"Administrative" = "2" ,
"Arts & Design" = "3" ,
"Education" = "4" ,
"Engineering" = "5",
"IT" = "6",
"Marketing, Sales, & Business Dev." = "7",
"Operations" = "8",
"Management" = "12",
"Other" = "11"
))
Employee1.Demos <-Employee1.Demos %>% mutate(Income.Final = fct_recode(Income.E1,
"Less than 25k" = "1",
"25-49k" = "3" ,
"50-75k" = "4" ,
"75-99k" = "5" ,
"100-150k" = "6",
"150+" ="7"
))
Employee1.Demos <- Employee1.Demos[, c(3, 9:14)]
#Employee 2 Demos
TidyData.E2 <- ScaleData[, c( 319:325, 327, 328, 330, 332, 334, 337)]
TidyData.E2$Ethnicity_EMP2_2[TidyData$Ethnicity_EMP2_2 %in% 1] <- 2
TidyData.E2$Ethnicity_EMP2_3[TidyData$Ethnicity_EMP2_3 %in% 1] <- 3
TidyData.E2$Ethnicity_EMP2_4[TidyData$Ethnicity_EMP2_4 %in% 1] <- 4
TidyData.E2$Ethnicity_EMP2_5[TidyData$Ethnicity_EMP2_5 %in% 1] <- 5
TidyData.E2$Ethnicity_EMP2_6[TidyData$Ethnicity_EMP2_6 %in% 1] <- 6
TidyData.E2$Ethnicity_EMP2_7[TidyData$Ethnicity_EMP2_7 %in% 1] <- 7
attach(TidyData.E2)
#Unite Ethnicity into ETH.NUll and ETH.E2
TidyData.E2 <- unite(TidyData.E2, ETH.E2, Ethnicity_EMP2_1, Ethnicity_EMP2_2, Ethnicity_EMP2_3, Ethnicity_EMP2_4, Ethnicity_EMP2_5, Ethnicity_EMP2_6, Ethnicity_EMP2_7, sep = "_", remove = FALSE, na.rm = TRUE)
##Recode into factor variables for both employees (Etnicity, Degree, Industry, JobFunction, Income)
TidyData.E2$ETH.E2 <- as.factor(as.character(TidyData.E2$ETH.E2))
TidyData.E2$Degree_EMP2 <- as.factor(as.character(TidyData.E2$Degree_EMP2))
TidyData.E2$Industry_EMP2 <- as.factor(as.character(TidyData.E2$Industry_EMP2))
TidyData.E2$JobFunction_EMP2 <- as.factor(as.character(TidyData.E2$JobFunction_EMP2))
TidyData.E2$Income_EMP2 <- as.factor(as.character(TidyData.E2$Income_EMP2))
TidyData.E2$Gender_EMP2 <- as.factor(as.character(TidyData.E2$Gender_EMP2))
TidyData.E2$Age_EMP2 <- as.numeric(as.character(TidyData.E2$Age_EMP2))
TidyData.E2 <- TidyData.E2 %>% mutate(Degree.E2 = fct_recode(Degree_EMP2,
"Associate" = "1",
"Bachelor" = "2" ,
"Master" = "3" ,
"Doctorate" = "4" ,
"Highschool or less" = "5"
))
TidyData.E2 <- TidyData.E2 %>% mutate(Industry.E2 = fct_recode(Industry_EMP2,
"Banking" = "1",
"Education" = "2" ,
"Food & Beverage" = "3" ,
"Government" = "4" ,
"Healthcare" = "5",
"Manufacturing" = "6",
"Media & Entertainment" = "7",
"Retail, Wholesale, & Distribution" = "8",
"Software & IT" = "9",
"Nonprofit" = "10",
"Other" = "11"
))
TidyData.E2 <- TidyData.E2 %>% mutate(JobFunction.E2 = fct_recode(JobFunction_EMP2,
"Accounting & Finance" = "1",
"Administrative" = "2" ,
"Arts & Design" = "3" ,
"Education" = "4" ,
"Engineering" = "5",
"IT" = "6",
"Marketing, Sales, & Business Dev." = "7",
"Management" = "12",
"Operations" = "8",
"Other" = "11"
))
TidyData.E2 <- TidyData.E2 %>% mutate(Income.E2 = fct_recode(Income_EMP2,
"Less than 25k" = "1",
"25-49k" = "3" ,
"50-75k" = "4" ,
"75-99k" = "5" ,
"100-150k" = "6",
"150+" = "7"
))
data.frame(colnames(TidyData.E2))
#####
Employee2.Demos <- TidyData.E2[, c(1, 9, 10, 15:18)]
Employee2.Demos <-Employee2.Demos %>% mutate(Eth.Final.E2 = fct_recode(ETH.E2,
"Multiracial" = "1_1_1_1_1_1_NA",
"Multiracial" = "1_NA_1_NA_1_1_NA" ,
"Multiracial" = "1_NA_NA_NA_1_NA_NA",
"Black" = "1_NA_NA_NA_NA_NA_NA",
"AIAN" = "NA_1_NA_NA_NA_NA_NA",
"Multiracial" = "NA_NA_1_NA_NA_1_NA",
"Asian" = "NA_NA_1_NA_NA_NA_NA",
"NHPI" = "NA_NA_NA_1_NA_NA_NA",
"Multiracial" = "NA_NA_NA_NA_1_1_NA",
"Hispanic" = "NA_NA_NA_NA_1_NA_NA" ,
"White" = "NA_NA_NA_NA_NA_1_NA"
))
Employee2.Demos <-Employee2.Demos %>% mutate(Degree.Final = fct_recode(Degree.E2,
"Associate" = "1",
"Bachelor" = "2" ,
"Master" = "3" ,
"Doctorate" = "4" ,
"Highschool or less" = "5"
))
Employee2.Demos <-Employee2.Demos %>% mutate(Gender.Final = fct_recode(Gender_EMP2,
"Male" = "1",
"Female" = "2" ,
"Other" = "3"
))
Employee2.Demos <-Employee2.Demos %>% mutate(Industry.Final = fct_recode(Industry.E2,
"Banking" = "1",
"Education" = "2" ,
"Food & Beverage" = "3" ,
"Government" = "4" ,
"Healthcare" = "5",
"Manufacturing" = "6",
"Media & Entertainment" = "7",
"Retail, Wholesale, & Distribution" = "8",
"Software & IT" = "9",
"Nonprofit" = "10",
"Other" = "11"
))
Employee2.Demos <-Employee2.Demos %>% mutate(JobFunction.Final = fct_recode(JobFunction.E2,
"Accounting & Finance" = "1",
"Administrative" = "2" ,
"Arts & Design" = "3" ,
"Education" = "4" ,
"Engineering" = "5",
"IT" = "6",
"Marketing, Sales, & Business Dev."= "7",
"Operations" = "8",
"Management" = "12",
"Other" = "11"
))
Employee2.Demos <-Employee2.Demos %>% mutate(Income.Final = fct_recode(Income.E2,
"Less than 25k" = "1",
"25-49k" = "3" ,
"50-75k" = "4" ,
"75-99k" = "5" ,
"100-150k" = "6",
"150+" ="7"
))
Employee2.Demos <- Employee2.Demos[, c(2,8:13)]
attach(ScaleData)
#E1 get rid of Haven label
ScaleData$Bias_EMP1_1 <- as.numeric(ScaleData$Bias_EMP1_1)
ScaleData$Bias_EMP1_2 <- as.numeric(ScaleData$Bias_EMP1_2)
ScaleData$Bias_EMP1_3 <- as.numeric(ScaleData$Bias_EMP1_3)
ScaleData$Bias_EMP1_4 <- as.numeric(ScaleData$Bias_EMP1_4)
ScaleData$Bias_EMP1_5 <- as.numeric(ScaleData$Bias_EMP1_5)
ScaleData$Bias_EMP1_6 <- as.numeric(ScaleData$Bias_EMP1_6)
#E1
ScaleData$Bias_EMP1_1 <- recode(ScaleData$Bias_EMP1_1,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$Bias_EMP1_2 <- recode(ScaleData$Bias_EMP1_2,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$Bias_EMP1_3 <- recode(ScaleData$Bias_EMP1_3,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$Bias_EMP1_4 <- recode(ScaleData$Bias_EMP1_4,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$Bias_EMP1_5 <- recode(ScaleData$Bias_EMP1_5,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$Bias_EMP1_6 <- recode(ScaleData$Bias_EMP1_6,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
#E2 get rid of Haven label
ScaleData$BIAS_EMP2_C_1 <- as.numeric(ScaleData$BIAS_EMP2_C_1)
ScaleData$BIAS_EMP2_C_2 <- as.numeric(ScaleData$BIAS_EMP2_C_2)
ScaleData$BIAS_EMP2_C_3 <- as.numeric(ScaleData$BIAS_EMP2_C_3)
ScaleData$BIAS_EMP2_C_4 <- as.numeric(ScaleData$BIAS_EMP2_C_4)
ScaleData$BIAS_EMP2_C_5 <- as.numeric(ScaleData$BIAS_EMP2_C_5)
ScaleData$BIAS_EMP2_C_6 <- as.numeric(ScaleData$BIAS_EMP2_C_6)
#E2
ScaleData$BIAS_EMP2_C_1 <- recode(ScaleData$BIAS_EMP2_C_1,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$BIAS_EMP2_C_2 <- recode(ScaleData$BIAS_EMP2_C_2,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$BIAS_EMP2_C_3 <- recode(ScaleData$BIAS_EMP2_C_3,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$BIAS_EMP2_C_4 <- recode(ScaleData$BIAS_EMP2_C_4,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$BIAS_EMP2_C_5 <- recode(ScaleData$BIAS_EMP2_C_5,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$BIAS_EMP2_C_6 <- recode(ScaleData$BIAS_EMP2_C_6,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData <- mutate(ScaleData,
Knowledge.1.C = (Bias_EMP1_1 + BIAS_EMP2_C_1)/2,
Knowledge.2.C = (Bias_EMP1_2 + BIAS_EMP2_C_2)/2,
Confident.C = (Bias_EMP1_3 + BIAS_EMP2_C_3)/2,
Confident.Self = (Bias_EMP1_4 + BIAS_EMP2_C_4)/2,
Admission.Self = (Bias_EMP1_5 + BIAS_EMP2_C_5)/2,
Fear.Reprisal.Self = (Bias_EMP1_6 + BIAS_EMP2_C_6)/2
)
#Reverse Code Admission and Fear of Reprisal (5 and 6)
##Admission Self
ScaleData$Admission.Self.R <- recode(ScaleData$Admission.Self,
'1' = 7,
'1.5' = 6.5,
'2' = 6,
'2.5' = 5.5,
'3' = 5,
'3.5' = 4.5,
'4' = 4.0,
'4.5' = 3.5,
'5' = 3.0,
'5.5' = 2.5,
'6' = 2.0,
'6.5' = 1.5,
'7.0' = 1.0
)
##Fear of Reprisal Self
ScaleData$Fear.Reprisal.Self.R <- recode(ScaleData$Fear.Reprisal.Self,
'1' = 7,
'1.5' = 6.5,
'2' = 6,
'2.5' = 5.5,
'3' = 5,
'3.5' = 4.5,
'4' = 4.0,
'4.5' = 3.5,
'5' = 3.0,
'5.5' = 2.5,
'6' = 2.0,
'6.5' = 1.5,
'7.0' = 1.0
)
#Create dataset for PERMA(4) and SWLS
Scale.Final <- ScaleData[, c(363:456)]
###Score Aggregated PERMA and PF
attach(Scale.Final)
Scale.Final$Empty <- seq(NA)
Scale.Final$Empty <- NA
Master <- data.frame(
PERMA.Self = c(Scale.Final$PERMA.E1, Scale.Final$PERMA.E2),
PF.Self = c(Scale.Final$PF.W.Scale.E1 , Scale.Final$PF.W.Scale.E2),
PERMA.C = c(Scale.Final$PERMA.E1C , Scale.Final$PERMA.E2C),
PF.C = c(Scale.Final$PF.W.Scale.E1C , Scale.Final$PF.W.Scale.E2C),
SWB.Self = c(Scale.Final$SWLS.E1, Scale.Final$Empty),
SWB.C = c(Scale.Final$SWLS.E2C, Scale.Final$Empty),
###Score Aggregated for PWB
OPRO.Self = c(Scale.Final$OPRO.E1 , Scale.Final$OPRO.E2),
OADAPT.Self = c(Scale.Final$OADAPT.E1 , Scale.Final$OADAPT.E2),
OPROF.Self = c(Scale.Final$OPROF.E1 , Scale.Final$OPROF.E2),
OPRO.C = c(Scale.Final$OPRO.E1C ,Scale.Final$OPRO.E2C),
OADAPT.C = c(Scale.Final$OADAPT.E1C , Scale.Final$OADAPT.E2C),
OPROF.C = c(Scale.Final$OPROF.E1C , Scale.Final$OPROF.E2C),
###JAWS
JAWS.PE.Self = c(Scale.Final$JAWS.PE.E1 , Scale.Final$JAWS.PE.E2),
JAWS.PE.C = c(Scale.Final$JAWS.PE.E1C , Scale.Final$JAWS.PE.E2C),
###Turnover
Turnover.Self = c(Scale.Final$Turnover.E1,
Scale.Final$Turnover.E2),
Turnover.C = c(Scale.Final$Turnover.E1C,
Scale.Final$Turnover.E2C),
###PsyCap
PsyCap.Self = c(Scale.Final$PsyCap.E1 , Scale.Final$PsyCap.E2),
PsyCap.C = c(Scale.Final$PsyCap.E1C , Scale.Final$PsyCap.E2C),
PsyCap.Self.H = c(Scale.Final$PsyCap.Hope.E1,
Scale.Final$PsyCap.Hope.E2),
PsyCap.Self.SE = c(Scale.Final$PsyCap.SE.E1,
Scale.Final$PsyCap.SE.E2),
PsyCap.Self.R = c(Scale.Final$PsyCap.Res.E1,
Scale.Final$PsyCap.Res.E2),
PsyCap.Self.O = c(Scale.Final$PsyCap.O.E1,
Scale.Final$PsyCap.O.E2),
PsyCap.Co.H = c(Scale.Final$PsyCap.Hope.E1C,
Scale.Final$PsyCap.Hope.E2C),
PsyCap.Co.SE = c(Scale.Final$PsyCap.SE.E1C,
Scale.Final$PsyCap.SE.E2C),
PsyCap.Co.R = c(Scale.Final$PsyCap.Res.E1C,
Scale.Final$PsyCap.Res.E2C),
PsyCap.Co.O = c(Scale.Final$PsyCap.O.E1C,
Scale.Final$PsyCap.O.E2C),
#Bias
Accuracy.Co = (Scale.Final$Knowledge.1.C +
Scale.Final$Knowledge.2.C +
Scale.Final$Confident.C)/3,
Accuracy.Self = (Scale.Final$Admission.Self.R +
Scale.Final$Fear.Reprisal.Self.R)/2)
#Concatenate DEMOS
Demos.Final <- data.frame(
Age = c(Employee1.Demos$Age_EMP1,
Employee2.Demos$Age_EMP2),
Race = str_c(Employee1.Demos$Eth.Final.E1,
Employee2.Demos$Eth.Final.E2),
Gender = c(Employee1.Demos$Gender.Final,
Employee2.Demos$Gender.Final),
Income = c(Employee1.Demos$Income.Final,
Employee2.Demos$Income.Final),
Industry = c(Employee1.Demos$Industry.Final,
Employee2.Demos$Industry.Final),
JobFunction = c(Employee1.Demos$JobFunction.Final,
Employee2.Demos$JobFunction.Final),
Degree = c(Employee1.Demos$Degree.Final,
Employee2.Demos$Degree.Final)
)
##Final Merge
Demos.Final$ID.Final <- seq.int(nrow(Demos.Final))
Master$ID.Final <- seq.int(nrow(Master))
THE.MASTER <- left_join(Master, Demos.Final, by = "ID.Final")
#Gender
THE.MASTER$Gender <- as.factor(THE.MASTER$Gender)
THE.MASTER$Gender <- recode_factor(THE.MASTER$Gender,
'1' ="Male",
'2' = "Female",
'3' = "Other")
#Race
THE.MASTER$Race <- as.factor(THE.MASTER$Race)
THE.MASTER$Race <- recode_factor(THE.MASTER$Race,
'1' ="Black",
'2' = "ANAI",
'3' = "Asian",
'4' ="NHPI",
'5' = "Hispanic",
'6' = "White",
'7' = "Other")
#Income
THE.MASTER$Income <- as.factor(THE.MASTER$Income)
THE.MASTER$Income <- recode_factor(THE.MASTER$Income,
'1' ="<25k",
'2' = "25-49k",
'3' = "50-74k",
'4' ="75-99k",
'5' = "100-150k",
'6' = "150k+")
#Industry
THE.MASTER$Industry <- as.factor(THE.MASTER$Industry)
THE.MASTER$Industry <- recode_factor(THE.MASTER$Industry,
'1' ="Banking & Financial Services",
'2' = "Education",
'3' = "Food & Beverage",
'4' ="Government",
'5' = "Healthcare",
'6' = "Manufacturing",
'7' = "Media & Entertainment",
'8' = "Retail, Wholesale, & Distribution",
'9' = "Software & IT Services",
'10'= "Non-Profit",
'11'= "Other")
#Job Function
THE.MASTER$JobFunction <- as.factor(THE.MASTER$JobFunction)
THE.MASTER$JobFunction <- recode_factor(THE.MASTER$JobFunction,
'1' ="Accounting & Finance",
'2' = "Administrative",
'3' = "Arts & Design",
'4' ="Education",
'5' = "Engineering",
'6' = "Information Technology",
'7' = "Marketing, Sales, & Business Development",
'8' = "Management",
'9' = "Operations",
'10' = "Other")
#Degree
THE.MASTER$Degree <- as.factor(THE.MASTER$Degree)
THE.MASTER$Degree <- recode_factor(THE.MASTER$Degree,
'1' ="Associate",
'2' = "Bachelor",
'3' = "Master",
'4' ="Doctorate",
'5' = "Other")
#Recode into Three categories
##Accuracy Self
THE.MASTER$Accuracy.Self.NEW[THE.MASTER$Accuracy.Self < 4] <- "Inaccurate"
THE.MASTER$Accuracy.Self.NEW[THE.MASTER$Accuracy.Self > 4] <- "Accurate"
##Accuracy Coworker
THE.MASTER$Accuracy.Co.NEW[THE.MASTER$Accuracy.Co < 4] <- "Inaccurate"
THE.MASTER$Accuracy.Co.NEW[THE.MASTER$Accuracy.Co > 4] <- "Accurate"
TheMaster.matrix <- as.matrix(THE.MASTER[, c(7:38)])
```
#Table 1 Demographics
```{r Table 1 Demographics, warning=FALSE}
#Age
mean(THE.MASTER$Age, na.rm = TRUE)
sd(THE.MASTER$Age, na.rm = TRUE)
#GENDER
freqdist::freqdist(THE.MASTER$Gender)
#Degree
freqdist::freqdist(THE.MASTER$Degree)
#Ethnicity
freqdist::freqdist(THE.MASTER$Race)
#Industry
freqdist::freqdist(THE.MASTER$Industry)
#INCOME
freqdist::freqdist(THE.MASTER$Income)
```
#Table 2 HERO Correlations
```{r HERO Correlations}
#PsyCap.Self
rcorr(TheMaster.matrix[, c(11, 7)], type = "pearson")
rcorr(TheMaster.matrix[, c(11, 2)], type = "pearson")
rcorr(TheMaster.matrix[, c(11, 1)], type = "pearson")
rcorr(TheMaster.matrix[, c(11, 3)], type = "pearson")
#PsyCap.C
rcorr(TheMaster.matrix[, c(11, 8)], type = "pearson")
rcorr(TheMaster.matrix[, c(11, 5)], type = "pearson")
rcorr(TheMaster.matrix[, c(11, 4)], type = "pearson")
rcorr(TheMaster.matrix[, c(11, 6)], type = "pearson")
#Hope.Self
rcorr(TheMaster.matrix[, c(13, 7)], type = "pearson")
rcorr(TheMaster.matrix[, c(13, 2)], type = "pearson")
rcorr(TheMaster.matrix[, c(13, 1)], type = "pearson")
rcorr(TheMaster.matrix[, c(13, 3)], type = "pearson")
#Hope.C
rcorr(TheMaster.matrix[, c(13, 8)], type = "pearson")
rcorr(TheMaster.matrix[, c(13, 5)], type = "pearson")
rcorr(TheMaster.matrix[, c(13, 4)], type = "pearson")
rcorr(TheMaster.matrix[, c(13, 6)], type = "pearson")
#SE.Self
rcorr(TheMaster.matrix[, c(14, 7)], type = "pearson")
rcorr(TheMaster.matrix[, c(14, 2)], type = "pearson")
rcorr(TheMaster.matrix[, c(14, 1)], type = "pearson")
rcorr(TheMaster.matrix[, c(14, 3)], type = "pearson")
#SE.C
rcorr(TheMaster.matrix[, c(14, 8)], type = "pearson")
rcorr(TheMaster.matrix[, c(14, 5)], type = "pearson")
rcorr(TheMaster.matrix[, c(14, 4)], type = "pearson")
rcorr(TheMaster.matrix[, c(14, 6)], type = "pearson")
#Resilience.Self
rcorr(TheMaster.matrix[, c(15, 7)], type = "pearson")
rcorr(TheMaster.matrix[, c(15, 2)], type = "pearson")
rcorr(TheMaster.matrix[, c(15, 1)], type = "pearson")
rcorr(TheMaster.matrix[, c(15, 3)], type = "pearson")
#Resilience.C
rcorr(TheMaster.matrix[, c(15, 8)], type = "pearson")
rcorr(TheMaster.matrix[, c(15, 5)], type = "pearson")
rcorr(TheMaster.matrix[, c(15, 4)], type = "pearson")
rcorr(TheMaster.matrix[, c(15, 6)], type = "pearson")
#Optimism.Self
rcorr(TheMaster.matrix[, c(16, 7)], type = "pearson")
rcorr(TheMaster.matrix[, c(16, 2)], type = "pearson")
rcorr(TheMaster.matrix[, c(16, 1)], type = "pearson")
rcorr(TheMaster.matrix[, c(16, 3)], type = "pearson")
#Optimism.C
rcorr(TheMaster.matrix[, c(16, 8)], type = "pearson")
rcorr(TheMaster.matrix[, c(16, 5)], type = "pearson")
rcorr(TheMaster.matrix[, c(16, 4)], type = "pearson")
rcorr(TheMaster.matrix[, c(16, 6)], type = "pearson")
```
#Table 3 Means, Sds, and Convergence
```{r Table 2 - Means, Sds, and Convergence}
#Means and SDs for all variables
mean(THE.MASTER[, 17], na.rm = TRUE) #PSYCAP
sd(THE.MASTER[, 17], na.rm = TRUE)
mean(THE.MASTER[, 18], na.rm = TRUE) #PSYCAP.C
sd(THE.MASTER[, 18], na.rm = TRUE)
mean(THE.MASTER[, 19], na.rm = TRUE) #PSYCAP.H.Self
sd(THE.MASTER[, 19], na.rm = TRUE)
mean(THE.MASTER[, 23], na.rm = TRUE) #PSYCAP.H.CO
sd(THE.MASTER[, 23], na.rm = TRUE)
mean(THE.MASTER[, 20], na.rm = TRUE) #PSYCAP.SE.Self
sd(THE.MASTER[, 20], na.rm = TRUE)
mean(THE.MASTER[, 24], na.rm = TRUE) #PSYCAP.SE.CO
sd(THE.MASTER[, 24], na.rm = TRUE)
mean(THE.MASTER[, 21], na.rm = TRUE) #PSYCAP.R.Self
sd(THE.MASTER[, 21], na.rm = TRUE)
mean(THE.MASTER[, 25], na.rm = TRUE) #PSYCAP.R.CO
sd(THE.MASTER[, 25], na.rm = TRUE)
mean(THE.MASTER[, 22], na.rm = TRUE) #PSYCAP.O.Self
sd(THE.MASTER[, 22], na.rm = TRUE)
mean(THE.MASTER[, 26], na.rm = TRUE) #PSYCAP.O.CO
sd(THE.MASTER[, 26], na.rm = TRUE)
mean(THE.MASTER[, 13], na.rm = TRUE) #JAWS.Self
sd(THE.MASTER[, 13], na.rm = TRUE)
mean(THE.MASTER[, 14], na.rm = TRUE) #JAWS.CO
sd(THE.MASTER[, 14], na.rm = TRUE)
mean(THE.MASTER[, 8], na.rm = TRUE) #Adapt.Self
sd(THE.MASTER[, 8], na.rm = TRUE)
mean(THE.MASTER[, 11], na.rm = TRUE) #Adapt.Co
sd(THE.MASTER[, 11], na.rm = TRUE)
mean(THE.MASTER[, 7], na.rm = TRUE) #Proa.Self
sd(THE.MASTER[, 7], na.rm = TRUE)
mean(THE.MASTER[, 10], na.rm = TRUE) #Proa.Co
sd(THE.MASTER[, 10], na.rm = TRUE)
mean(THE.MASTER[, 9], na.rm = TRUE) #Prof.Self
sd(THE.MASTER[, 9], na.rm = TRUE)
mean(THE.MASTER[, 12], na.rm = TRUE) #Prof.Co
sd(THE.MASTER[, 12], na.rm = TRUE)
mean(THE.MASTER[, 9], na.rm = TRUE) #TO.Self
sd(THE.MASTER[, 9], na.rm = TRUE)
##Convergence
rcorr(TheMaster.matrix[, c(11, 12)], type = "pearson") #PSYCAP
rcorr(TheMaster.matrix[, c(13, 17)], type = "pearson") #PSY_H
rcorr(TheMaster.matrix[, c(14, 18)], type = "pearson") #PSY_SE
rcorr(TheMaster.matrix[, c(15, 19)], type = "pearson") #PSY_R
rcorr(TheMaster.matrix[, c(16, 20)], type = "pearson") #PSY_O
rcorr(TheMaster.matrix[, c(7, 8)], type = "pearson") #JAWS
rcorr(TheMaster.matrix[, c(2, 5)], type = "pearson") #ADAPT
rcorr(TheMaster.matrix[, c(1, 4)], type = "pearson") #PROA
rcorr(TheMaster.matrix[, c(3, 6)], type = "pearson") #PROF
```
#Table 4 MTMM Matrix
```{r Reliability Diagonals Self/Self}
#Create Reliability Dataset
#Self-Reported
##PsyCap
PsyC_Alpha <- Scale.Final[, c(45:48,55:58)]
alpha(PsyC_Alpha)
##JAWS
JAWS_Alpha <- ScaleData[, c(44:53,177:186)]
alpha(JAWS_Alpha)
##OADAPT
OADAPT_Alpha <- ScaleData[, c(38:40, 171:173)]
alpha(OADAPT_Alpha)
##OPRO
OPRO_Alpha <- ScaleData[, c(41:43, 174:176)]
alpha(OPRO_Alpha)
##OPROF
OPROF_Alpha <- ScaleData[, c(35:37, 168:170)]
alpha(OPROF_Alpha)
##TI
TI_Alpha <- ScaleData[, c(54:58, 187:191)]
alpha(TI_Alpha)
```
```{r Reliability Diagonals Co-Co}
#Create Reliability Dataset
#Self-Reported
##PsyCap
PsyCap.C <- Scale.Final[, c(16:19, 35:38)]
alpha(PsyCap.C)
##JAWS
JAWS.C <- ScaleData[, c(113:122, 246:255)]
alpha(JAWS.C)
##OADAPT
OADAPT_Alpha.C <- ScaleData[, c(107:109, 240:242)]
alpha(OADAPT_Alpha.C)
##OPRO
OPRO_Alpha.C <- ScaleData[, c(110:112, 243:245)]
alpha(OPRO_Alpha.C)
##OPROF
OPROF_Alpha.C <- ScaleData[, c(237:239, 104:106)]
alpha(OPROF_Alpha.C)
##Turnover Intentions
TI_Alpha.C <- ScaleData[, c(123:127, 256:260)]
alpha(TI_Alpha.C)
```
```{r MonoMethod Block Self-Self}
#SelfReport
##PsyCap
rcorr(TheMaster.matrix[, c(11, 7)], type = "pearson")
rcorr(TheMaster.matrix[, c(11, 2)], type = "pearson")
rcorr(TheMaster.matrix[, c(11, 1)], type = "pearson")
rcorr(TheMaster.matrix[, c(11, 3)], type = "pearson")
##JAWS
rcorr(TheMaster.matrix[, c(7, 2)], type = "pearson")
rcorr(TheMaster.matrix[, c(7, 1)], type = "pearson")
rcorr(TheMaster.matrix[, c(7, 3)], type = "pearson")
##OADAPT
rcorr(TheMaster.matrix[, c(2, 1)], type = "pearson")
rcorr(TheMaster.matrix[, c(2, 3)], type = "pearson")
##OPRO
rcorr(TheMaster.matrix[, c(1, 3)], type = "pearson")
```
```{r MonoMethod Block Co-Co}
#Collateral Report
##PsyCap
rcorr(TheMaster.matrix[, c(12, 8)], type = "pearson")
rcorr(TheMaster.matrix[, c(12, 5)], type = "pearson")
rcorr(TheMaster.matrix[, c(12, 4)], type = "pearson")
rcorr(TheMaster.matrix[, c(12, 6)], type = "pearson")
##JAWS
rcorr(TheMaster.matrix[, c(8, 5)], type = "pearson")
rcorr(TheMaster.matrix[, c(8, 4)], type = "pearson")
rcorr(TheMaster.matrix[, c(8, 6)], type = "pearson")
##OADAPT
rcorr(TheMaster.matrix[, c(5, 4)], type = "pearson")
rcorr(TheMaster.matrix[, c(5, 6)], type = "pearson")
##OPRO
rcorr(TheMaster.matrix[, c(4, 6)], type = "pearson")
```
```{r Validity Diagonals}
##PsyCap
rcorr(TheMaster.matrix[, c(19,20)], type = "pearson")
##JAWS
rcorr(TheMaster.matrix[, c(4,13)], type = "pearson")
##OADAPT
rcorr(TheMaster.matrix[, c(2, 11)], type = "pearson")
##OPRO
rcorr(TheMaster.matrix[, c(3, 12)], type = "pearson")
##OPROF
rcorr(TheMaster.matrix[, c(1, 10)], type = "pearson")
```
```{r HeteroTrait HeteroMethod Triangle}
#PsyCap
rcorr(TheMaster.matrix[, c(19, 13)], type = "pearson")
rcorr(TheMaster.matrix[, c(19, 11)], type = "pearson")
rcorr(TheMaster.matrix[, c(19, 12)], type = "pearson")
rcorr(TheMaster.matrix[, c(19, 10)], type = "pearson")
#JAWS
rcorr(TheMaster.matrix[, c(4, 20)], type = "pearson")
rcorr(TheMaster.matrix[, c(4, 11)], type = "pearson")
rcorr(TheMaster.matrix[, c(4, 12)], type = "pearson")
rcorr(TheMaster.matrix[, c(4, 10)], type = "pearson")
##ODAPT
rcorr(TheMaster.matrix[, c(2, 20)], type = "pearson")
rcorr(TheMaster.matrix[, c(2, 13)], type = "pearson")
rcorr(TheMaster.matrix[, c(2, 12)], type = "pearson")
rcorr(TheMaster.matrix[, c(2, 12)], type = "pearson")
##OPROF
rcorr(TheMaster.matrix[, c(3, 20)], type = "pearson")
rcorr(TheMaster.matrix[, c(3, 13)], type = "pearson")
rcorr(TheMaster.matrix[, c(3, 11)], type = "pearson")
rcorr(TheMaster.matrix[, c(3, 10)], type = "pearson")
##OPROF
rcorr(TheMaster.matrix[, c(1, 20)], type = "pearson")
rcorr(TheMaster.matrix[, c(1, 13)], type = "pearson")
rcorr(TheMaster.matrix[, c(1, 11)], type = "pearson")
rcorr(TheMaster.matrix[, c(1, 12)], type = "pearson")
```
#Table 5 Self-Reported Predicting Work Outcomes
```{r Self-Reported PsyCap Predicting Self-Reported and Collateral-Reported Work Outcomes}
attach(THE.MASTER)
#Self-Self Overall
Reg.PC.S <- lm(OPRO.Self ~
PsyCap.Self)
summary(Reg.PC.S)
confint.lm(Reg.PC.S)
#Self-Self Bias Correction
Adjusted <- THE.MASTER %>% filter(Accuracy.Self.NEW == "Accurate")
attach(Adjusted)
Reg.PC.AC <- lm(OPROF.Self ~
PsyCap.Self)
summary(Reg.PC.AC)
confint.lm(Reg.PC.AC)
#Collateral-Report
attach(THE.MASTER)
Reg.PF.C <- lm(OPROF.C ~
PsyCap.Self)
summary(Reg.PF.C)
confint.lm(Reg.PF.C)
```
#Table 6 Collateral-Reported Predicting Work Outcomes
```{r message=FALSE, warning=FALSE, include=FALSE}
attach(THE.MASTER)
#Co-Co Overall
Reg.PC.Co <- lm(OPROF.C~
PsyCap.C)
summary(Reg.PC.Co)
confint.lm(Reg.PC.Co)
#Co-Co Bias Correction
Adjusted.C <- THE.MASTER %>% filter(Accuracy.Co.NEW == "Accurate")
attach(Adjusted.C)
Reg.PC.C.AC <- lm(OPROF.C~
PsyCap.C)
summary(Reg.PC.C.AC)
confint.lm(Reg.PC.C.AC)
#Co-Self Overall
attach(THE.MASTER)
Reg.PC.C.S <- lm(OPROF.Self~
PsyCap.C)
summary(Reg.PC.C.S)
confint.lm(Reg.PC.C.S)
```
<file_sep>/Journal of Well-Being/JWA.Plots.R
####JWA Plots####
setwd("~/Desktop/JWA/R")
#Download Packages
library(lavaan)
library(semPlot)
library(psych)
library(haven)
#Upload Data
DPF_Criterion <- read_sav("DPF_Criterion3.sav")
attach(DPF_Criterion)
data = DPF_Criterion
#CFA MODEL Testing#
#Mahal Outlier Test
library(mice)
data2 = data[, -c(1:139)]
names(data2)
Mahal = mahalanobis(data2, colMeans(data2, na.rm = TRUE), cov(data2, use = "pairwise.complete.obs"))
summary(Mahal)
cuttoff = qchisq(.999, ncol(data2))
summary(Mahal < cuttoff)
FinalData = data[Mahal < cuttoff , ]
-----------------
attach(FinalData)
#FirstOrder model
First.Order <- '
P =~ PE_1 + PE_2 + PE_3
E =~ PEN_1 + PEN_2 + PEN_3
R =~ PREL_1 + PREL_2 + PREL_3 + PREL_4
M =~ PMEAN_1 + PMEAN_2 + PMEAN_3
A =~ PACCOM_1 + PACCOM_2 + PACCOM_3
Health =~ PPHealth_1 + PPHealth_2 + PPHealth_3 + PPHealth_4
Mind =~ PMIND_1 + PMIND_2 + PMIND_3
Enviro =~ PPWE_1 + PPWE_2 + PPWE_3
Econ =~ PECON_1 + PECON_2 + PECON_3
'
Higher.Order <-
'
P =~ PE_1 + PE_2 + PE_3
E =~ PEN_1 + PEN_2 + PEN_3
R =~ PREL_1 + PREL_2 + PREL_3 + PREL_4
M =~ PMEAN_1 + PMEAN_2 + PMEAN_3
A =~ PACCOM_1 + PACCOM_2 + PACCOM_3
Health =~ PPHealth_1 + PPHealth_2 + PPHealth_3 + PPHealth_4
Mind =~ PMIND_1 + PMIND_2 + PMIND_3
Enviro =~ PPWE_1 + PPWE_2 + PPWE_3
Econ =~ PECON_1 + PECON_2 + PECON_3
global =~ P + E + R + M + A + Health + Mind + Enviro + Econ
'
BiFactor <-
'
P =~ b*PE_1 + b*PE_2 + b*PE_3
E =~ c*PEN_1 + c*PEN_2 + c*PEN_3
R =~ a*PREL_1 + a*PREL_2 + a*PREL_3 + a*PREL_4
M =~ d*PMEAN_1 + d*PMEAN_2 + d*PMEAN_3
A =~ e*PACCOM_1 + e*PACCOM_2 + e*PACCOM_3
Health =~ g*PPHealth_1 + g*PPHealth_2 + g*PPHealth_3 + g*PPHealth_4
Mind =~ h*PMIND_1 + h*PMIND_2 + h*PMIND_3
Enviro =~ i*PPWE_1 + i*PPWE_2 + i*PPWE_3
Econ =~ f*PECON_1 + f*PECON_2 + f*PECON_3
PFW =~ b*PE_1 + b*PE_2 + b*PE_3 + c*PEN_1 + c*PEN_2 + c*PEN_3 + a*PREL_1 + a*PREL_2 + a*PREL_3 + a*PREL_4 + d*PMEAN_1 + d*PMEAN_2 + d*PMEAN_3 + e*PACCOM_1 + e*PACCOM_2 + e*PACCOM_3 + g*PPHealth_1 + g*PPHealth_2 + g*PPHealth_3 + g*PPHealth_4 + h*PMIND_1 + h*PMIND_2 + h*PMIND_3 + i*PPWE_1 + i*PPWE_2 + i*PPWE_3 + f*PECON_1 + f*PECON_2 + f*PECON_3
'
OneFactor <-
'
Global =~ PREL_1 + PREL_2 + PREL_3 + PREL_4 + PE_1 + PE_2 + PE_3 + PEN_1 + PEN_2 + PEN_3 + PMEAN_1 + PMEAN_2 + PMEAN_3 + PACCOM_1 + PACCOM_2 + PACCOM_3 + PECON_1 + PECON_2 + PECON_3 + PPHealth_1 + PPHealth_2 + PPHealth_3 + PPHealth_4 + PMIND_1 + PMIND_2 + PMIND_3 + PPWE_1 + PPWE_2 + PPWE_3
'
#Fit First Order CFA
first.fit <- cfa(First.Order, data = FinalData)
Higher.Order.fit <- cfa(Higher.Order, data = FinalData)
Bifactor.fit <- cfa(BiFactor, data = FinalData, estimator = "ML", orthogonal=TRUE)
OneFactor.fit <- cfa(OneFactor, data = FinalData)
#Create Pictures
library(semPlot)
#First Order Plot
semPaths(first.fit, whatLabels = "std" , layout = "tree")
PFlabels <- c("P1" , "P2" , "P3",
"E1", "E1", "E3",
"R1", "R2", "R3", "R4",
"M1" , "M2", "M3",
"A1","A2", "A3",
"H1", "H2", "H3", "H4",
"MI1", "MI2", "MI3",
"EN1", "EN2", "EN3",
"EC1", "EC2", "EC3",
"P" , "E", "R", "M","A", "Health", "Mind", "Enviro", "Econ")
semPaths(first.fit, nodeLabels = PFlabels, style = "lisrel", curve = 0.8, nCharNodes = 0,
sizeLat = 5, sizeLat2 = 5, sizeMan = 3.5, title = TRUE, mar = c(10,1,10,1), edge.label.cex = 0.5, exoVar = FALSE,
covAtResiduals = FALSE, exoCov = TRUE)
#Higher-Order Plot
PFlabels <- c("P1" , "P2" , "P3",
"E1", "E1", "E3",
"R1", "R2", "R3", "R4",
"M1" , "M2", "M3",
"A1","A2", "A3",
"H1", "H2", "H3", "H4",
"MI1", "MI2", "MI3",
"EN1", "EN2", "EN3",
"EC1", "EC2", "EC3",
"P" , "E", "R", "M","A", "Health", "Mind", "Enviro", "Econ", "PF-W")
semPaths(Higher.Order.fit, layout = "tree", nodeLabels = PFlabels, style = "lisrel", curve = 0.8, nCharNodes = 0,
sizeLat = 7, sizeLat2 = 5, sizeMan = 3.5, title = TRUE, mar = c(10,1,10,1), edge.label.cex = 0.5, exoVar = FALSE,
covAtResiduals = FALSE, exoCov = FALSE)
#Bifactor Plot
PFlabels <- c("P1" , "P2" , "P3",
"E1", "E1", "E3",
"R1", "R2", "R3", "R4",
"M1" , "M2", "M3",
"A1","A2", "A3",
"H1", "H2", "H3", "H4",
"MI1", "MI2", "MI3",
"EN1", "EN2", "EN3",
"EC1", "EC2", "EC3",
"P" , "E", "R", "M","A", "Health", "Mind", "Enviro", "Econ", "PFW")
semPaths(Bifactor.fit, layout = "tree2", nodeLabels = PFlabels, style = "lisrel", curve = 0.8, nCharNodes = 0, sizeLat = 5, sizeLat2 = 4, sizeMan = 3, title = TRUE, mar = c(10,1,10,1), edge.label.cex = 0.5, exoVar = FALSE, covAtResiduals = FALSE, exoCov = FALSE, bifactor = "PFW", rotation = 1)
#One-Factor Plot
PFlabels <- c("P1" , "P2" , "P3",
"E1", "E1", "E3",
"R1", "R2", "R3", "R4",
"M1" , "M2", "M3",
"A1","A2", "A3",
"H1", "H2", "H3", "H4",
"MI1", "MI2", "MI3",
"EN1", "EN2", "EN3",
"EC1", "EC2", "EC3",
"PF-W")
semPaths(OneFactor.fit, layout = "tree", nodeLabels = PFlabels, style = "lisrel", curve = 0.8, nCharNodes = 0,
sizeLat = 7, sizeLat2 = 5, sizeMan = 3, title = TRUE, mar = c(10,1,10,1), edge.label.cex = 0.5, exoVar = FALSE, covAtResiduals = FALSE, exoCov = TRUE)
<file_sep>/Imposter Phenomenon/IP.FactorAnalysis.Rmd
---
title: "IP.FactorAnalysis"
output: html_document
---
```{r Upload and Subset Data}
setwd("~/Documents/CGU/ImposterPhen./Stats")
#Upload the SPSS File
library(haven)
library(psych)
library(GPArotation)
library(tidyverse)
library(ltm)
library(nFactors)
library(Hmisc)
#Subset the Data by EvaluatorIP not Original
IP_Evaluator_Survey <- read_sav("~/Desktop/IP_ Evaluator Survey.sav")
View(IP_Evaluator_Survey)
Final <- IP_Evaluator_Survey[IP_Evaluator_Survey$MeasureType==1, names(IP_Evaluator_Survey)]
#Creates a dataframe of the variables we want to FA
data.frame(colnames(IP_Evaluator_Survey))
Final2 <- Final[,c(5:26)]
sum(is.na(Final2))
Final3 <- na.omit(Final2)
data.frame(colnames(Final3))
Final4 <- Final3[, c(3:5, 8, 9:13, 15, 21:22, 16:18)]
```
```{r Descriptives and PA}
##Descriptives for the variables
describe(Final3)
cor(Final3)
##Horn's Parallel Analysis
parallel <- fa.parallel(Final3, fm = 'minres', fa = 'fa')
```
```{r EFA Procedure }
#-The PA suggests two factors
#-Based on the research we will test a two factor, three, and four factor model.
EFA.2 = fa(Final3, nfactors = 2, rotate = "oblimin" , cor = "poly")
print(EFA.2)
EFA.3 = fa(Final3, nfactors = 3, rotate = "oblimin" , cor = "poly")
print(EFA.3)
EFA.4 <- fa(Final3, nfactors = 4, rotate = "oblimin" , cor = "poly")
print(EFA.4)
anova(EFA.2, EFA.3)
anova(EFA.3, EFA.4)
EFA.5.final = fa(Final4, nfactors = 3, rotate = "oblimin" , cor = "poly")
print(EFA.5.final)
#Residual sum of squares in better in the model with four factors than three or two factors
EV <- eigen(cor(Final3)) #Eigenvalues suggest five
print(EV)
ap <- parallel(subject=nrow(Final3),var=ncol(Final3),
rep=100,cent=.05)
nS <- nScree(x=EV$values, aparallel=ap$eigen$qEVpea)
plotnScree(nS) #Scree plot
```
```{r Scaling }
data.frame(colnames(Final4))
ten.item <- as.data.frame(Final4[, c(5:6, 7:12, 14:15)])
cronbach.alpha(ten.item)
#Create new dataset with subscales
SCALES <- mutate(ten.item,
Discount = (ten.item$Discount_19 + ten.item$Discount_23 + ten.item$Luck_12 + ten.item$Luck_13)/4,
Luck = (ten.item$Luck_1 + ten.item$Luck_6 + ten.item$Luck_7)/3,
Fake = (ten.item$Luck_3 + ten.item$Luck_4 + ten.item$Luck_8)/3,
totalscore = (ten.item$Discount_19 + ten.item$Discount_23 + ten.item$Luck_12 + ten.item$Luck_13 + ten.item$Luck_1 + ten.item$Luck_6 + ten.item$Luck_7 + ten.item$Luck_3 + ten.item$Luck_4 + ten.item$Luck_8)/10
)
head(SCALES)
#Cronbachs Alpha for subscales
data.frame(colnames(SCALES))
CA.Discount <- SCALES[, c(7:10)]
cronbach.alpha(CA.Discount)
CA.Fake <- SCALES[, c(1:3)]
cronbach.alpha(CA.Fake)
CA.Luck <- SCALES[, c(4:6)]
cronbach.alpha(CA.Luck)
#Descriptive
describe(SCALES$totalscore)
describe(SCALES$Luck)
describe(SCALES$Discount)
describe(SCALES$Fake)
#Correlations
cor.data <- as.matrix(SCALES[, c(11:13)])
rcorr(cor.data, type="pearson")
##Subset for age analyses
Age <- IP_Evaluator_Survey[IP_Evaluator_Survey$MeasureType==1, names(IP_Evaluator_Survey)]
data.frame(colnames(Age))
Age2 <- Age[,c(5:26, 68, 73, 75)]
sum(is.na(Age2))
Age3 <- na.omit(Age2)
sum(is.na(Age3))
Age4 <- mutate(Age2,
Discount = (Age2$Discount_19 + Age2$Discount_23 + Age2$Luck_12 + Age2$Luck_13)/4,
Luck = (Age2$Luck_1 + Age2$Luck_6 + Age2$Luck_7)/3,
Fake = (Age2$Luck_3 + Age2$Luck_4 + Age2$Luck_8)/3,
totalscore = (Age2$Discount_19 + Age2$Discount_23 + Age2$Luck_12 + Age2$Luck_13 + Age2$Luck_1 + Age2$Luck_6 + Age2$Luck_7 + Age2$Luck_3 + Age2$Luck_4 + Age2$Luck_8)/10)
sum(is.na(Age4))
Age5 <- na.omit(Age4)
sum(is.na(Age5))
##Correlation with age
as.data.frame(colnames(Age5))
age.data <- as.matrix(Age5[, c(23, 26:29)])
rcorr(age.data, type="pearson")
#ANOVA with educational background
Age5$Education <- as.factor(as.character(Age5$Education))
edu.discount <- aov(Luck ~ Education, data = Age5)
summary(edu.discount)
TukeyHSD(edu.discount)
```
<file_sep>/IRT/BriefScreener.FinalCode_SCOTT.Rmd
---
title: "Brief Measure of Problematic Smartphone Use"
output: html_document
---
#Data manipulation
```{r Load Packages and Subset}
setwd("~/Desktop/UCSD/IRTProject")
#Load useful packages
library(ggplot2)
library(mokken)
library(KernSmoothIRT)
library(psych)
library(mirt)
library(nFactors)
library(GPArotation)
library(jtools)
library(RDS)
library(haven)
library(freqdist)
library(REdaS)
library(pROC)
library(randomForest)
library(readxl)
library(tidyverse)
library(survey)
library(WeMix)
library(effects)
library(Hmisc)
```
```{r Upload CSTS Data and Subset the variables of interest}
csts1718_cr <- read_excel("csts1718_cr.xlsm")
CSTS1718 <- csts1718_cr[, c(2, 6, 5, 372:378,
441, 406, 11,
400, 401)]
CSTS1718 <- rename(CSTS1718, c("Smartphone" = "Q107",
"SP_Sleep" = "Q108",
"SP_Work" = "Q109",
"SP_Soc_Awk" = "Q110",
"SP_Uncomfort" = "Q111a",
"SP_Constant" = "Q111b",
"SP_Parent" = "Q111c",
"Weight" = "WGT1718_cr",
"Gender" = "Q132a",
"Race" = "RACE_M",
"Grade" = "Q5",
"Loneliness" = "Q126",
"Depression" = "Q127",
"SCHOOLID" = "SCHOOLID",
"REGION" = "REGION"
))
#How many have smartphones
freqdist(CSTS1718$Smartphone)
SP <- table(CSTS1718$Smartphone)
freqCI(SP, level = 0.95)
#Subset high school students with smartphones
nomiss = CSTS1718[which(CSTS1718$Smartphone < 2 &
CSTS1718$Grade > 1 &
CSTS1718$SP_Sleep < 98 &
CSTS1718$SP_Work < 98 &
CSTS1718$SP_Soc_Awk < 98 &
CSTS1718$SP_Uncomfort < 98 &
CSTS1718$SP_Constant < 98 &
CSTS1718$SP_Parent < 98 &
CSTS1718$Gender < 98 &
CSTS1718$Loneliness < 98 &
CSTS1718$Depression < 98), ]
Final <- nomiss
#Set factors and numeric variables
Final$PSU.Score <- (Final$SP_Uncomfort + Final$SP_Constant + Final$SP_Parent)/3
Final$Gender <- as.factor(Final$Gender)
Final$Grade <- as.factor(Final$Grade)
Final$Race <- as.factor(Final$Race)
Final$Depression <- as.factor(Final$Depression)
#Distribution of PSU Scale
describe(Final$PSU.Score)
hist(Final$PSU.Score)
```
#Demographic Section
```{r Table 1 - Demographic Section}
#Students who own a smartphone
Smart.Demos <- CSTS1718[which(CSTS1718$Smartphone < 2 &
CSTS1718$Grade > 1), ]
#Gender
freqdist::freqdist(Smart.Demos$Gender)
freqCI(Smart.Demos$Gender)
#Race
freqdist::freqdist(Smart.Demos$Race)
freqCI(Smart.Demos$Race)
#Grade
freqdist::freqdist(Smart.Demos$Grade)
freqCI(Smart.Demos$Grade)
####Students with no smartphones
No.Smart = CSTS1718[which(CSTS1718$Grade > 1 &
CSTS1718$Smartphone == 2), ]
#Gender
freqdist::freqdist(No.Smart$Gender)
freqCI(No.Smart$Gender)
#Race
freqdist::freqdist(No.Smart$Race)
freqCI(No.Smart$Race)
#Grade
freqdist::freqdist(No.Smart$Grade)
freqCI(No.Smart$Grade)
```
#Distribution of PSU
```{r Figure 1}
attach(Final)
freqdist(Final$PSU.Score)
Hist <- ggplot(Final, aes(Final$PSU.Score))
Hist +
geom_histogram(color = "black", binwidth = .35) +
theme_classic() +
xlab("Problematic Smartphone Use Score") +
ylab("Frequency") +
ylim(0, 17000)
+
scale_x_continuous(breaks = c(1, 1.33, 1.66, 2, 2.33, 2.66, 3, 3.33, 3.66, 4))
```
#Exploratory Factor Analysis and Parametric IRT
```{r Table 2 - EFA Unweighted}
#EFA Procedure Unweighted
describe(Final[5:10])
parallel <- fa.parallel(Final[5:10], fm = 'minres', fa = 'fa')
EFA.Final = fa(Final[5:10], nfactors = 2, rotate = "oblimin" ,cor = "poly")
print(EFA.Final)
EV <- eigen(cor(Final[5:10]))
print(EV)
```
```{r Table 2 - Parametric Modeling}
#Parametric Model PSU
fit.mirt.PSU <-mirt(PSU, model=1,
itemtype = 'graded',
#method = "MHRM",
technical= list(removeEmptyRows=TRUE),
SE = TRUE,
survey.weights = PSU$Weight)
coef(fit.mirt.PSU, simplify=TRUE, IRTpars=TRUE)
#check local dependence
residuals(fit.mirt.PSU)
# plot expected total score
plot(fit.mirt.PSU, type='score')
# plot test information function
plot(fit.mirt.PSU, type='info', MI = 100)
# plot test standard error across range of scores
plot(fit.mirt.PSU, type='SE', MI = 100)
# plot item characteristic curves
plot(fit.mirt.PSU, type='itemscore')
# plot option characteristic curves
plot(fit.mirt.PSU, type='trace')
#Check item fit
item.fit.1 <- itemfit(fit.mirt.PSU)
item.fit.1
#plot empirical item plot of residuals vs predicted curve
item.fit.psu1 <- itemfit(fit.mirt.PSU, group.bins=15,
empirical.plot = 1, method = 'ML') #empirical item plot with 15 points
item.fit.psu1
item.fit.psu2 <- itemfit(fit.mirt.PSU, group.bins=15,
empirical.plot = 2, method = 'ML') #empirical item plot with 15 points
item.fit.psu2
item.fit.psu3 <- itemfit(fit.mirt.PSU, group.bins=15,
empirical.plot = 3, method = 'ML') #empirical item plot with 15 points
item.fit.psu3
```
```{r EFA Weighted}
## Add Survey weights to the model
EFA.Final.weighted.uni <- mirt(Final[5:10], model=1,
itemtype = "graded",
survey.weights = Final$Weight,
se=TRUE)
EFA.Final.weighted.multi <- mirt(Final[5:10], model=2,
itemtype = "graded",
survey.weights = Final$Weight,
se=TRUE)
#compare unidimensional and multidimensional models [two fits better than one]
anova(EFA.Final.weighted.uni,EFA.Final.weighted.multi)
#Get fit estimates
EFA.Final.weighted.multi
summary(EFA.Final.weighted.multi, rotate = "oblimin", suppress = 0.25)
coef(EFA.Final.weighted.multi, simplify=TRUE)
residuals(EFA.Final.weighted.multi)
#The mirt model for 2 factors is fit with survey weights
- #A graded response model is used for these categorical indicators
- #The factor loadings and h2 are estimated as in the unweighted model
- #The residuals function looks for violations of assumptions of local independence,
- #Above the upper diagonal elements represent the standardized residuals in the form of signed Cramers V coefficients. Cramer V are interpreted like correlations. These are all pretty low.
```
```{r EFA with new Soc_AWK}
### Rescale SocAwk item to check impact on EFA
#- may increase local dependence a bit but gives a better fit by AIC, BIC, and Likelihood Ratio
#- SocAwk item had lower cross loading (.13 -> 0.07)
### In EFA looks like SP_Soc_Awk has lowest h2 @0.268 and lowest loading on the second factor. If you push it to three factors, it jumps off factor 2 and regains h2 of .588, and 'factor' is low correlation with other 2 @.43-.47 so nonredundant. Whereas SP_Parent which also has low h2, stays with factor 1 and no new gain in h2... model fail with 3 factors out of 6 items because too few observed variables (need 3+ per factor...may want to separate the awkward item...look to mokken for guidance..
---
final <- Final
final[,'SP_Soc_Awk'] <- ifelse(final[,'SP_Soc_Awk'] < 4, 1, 2)
EFA.Final.weighted.multi.recode <- mirt(final[1:6], model=2,
itemtype = "graded",
survey.weights = final$Weight,
se=TRUE)
anova(EFA.Final.weighted.multi,EFA.Final.weighted.multi.recode)
EFA.Final.weighted.multi.recode
summary(EFA.Final.weighted.multi.recode)
coef(EFA.Final.weighted.multi.recode, simplify=TRUE)
residuals(EFA.Final.weighted.multi.recode)
```
#Non-Parametric IRT with Plots
```{r Mokken Scaling - PSU}
#Mokken Scaling Tools
##Get some reliability estimates (internal consistency)
PSU <- as.data.frame(Final[ ,c(8:10)])
PSC <- as.data.frame(Final[ ,c(5:7)])
check.reliability(PSU)
##Scalability Coefficients
coefH(PSU)
coefH(PSC)
##Check Latent Monotonicity
monotonicity.PSU <- check.monotonicity(PSU)
summary(monotonicity.PSU)
plot(monotonicity.PSU)
##Items placed on same scale (Automated Item Selection Procedure)
aisp(PSU)
```
```{r Fit Kernal Smoothing - PSU}
#Kern Smooth IRT - Problematic Smartphone Use
par(ask=FALSE)
fit.kern.PSU <- ksIRT(responses = Final[, c(8:10)],
format = 2,
miss = 'omit',
key = c(4,4,4),
kernel = 'gaussian')
plot(fit.kern.PSU, plottype='expected', axistype='distribution')
plot(fit.kern.PSU,
plottype='EIS',
axistype="distribution")
par(mfrow=c(1,3))
plot(fit.kern.PSU,
plottype='OCC',
axistype="distribution",
ylab = "Probability of Endorsement")
plot(fit.kern.PSU,
plottype='RCC',
axistype="distribution",
subjects = c(1,10,100,200) )
```
```{r Figure 2 - Kernal Smooth Plots}
fit.kern.Total = ksIRT(responses = Final[, c(8:10)],
format = 2,
miss = 'omit',
key = c(4,4,4),
kernel = 'gaussian')
##paste your ksIRT object here
irt.OCC <- fit.kern.Total #paste your ksIRT object here
#pull out variable names from IRT object
item.names <- tibble(irt.OCC$itemlabels) %>%
rownames_to_column() %>%
rename(item = 1,
name = 2) %>%
mutate(item = as.numeric(item))
#pull out 51 theta evaluation points from IRT object
theta.points <- tibble(irt.OCC$evalpoints) %>%
rownames_to_column() %>%
rename(point = 1,
theta = 2) %>%
mutate(point = as.numeric(point))
#pull out option characteristics terms from IRT object
irt.OCC.long <- as_tibble(irt.OCC$OCC) %>%
rename(item = 1, #rename first 3 columns
option = 2,
weight = 3) %>%
arrange(item, option) %>% #sort the data by item then option
mutate(option = as.factor(option)) %>% #turn option into factor
pivot_longer(cols = starts_with("V"), # transpose from wide to long for all values
names_to = "point",
names_prefix = "V",
values_to = "occ.prob",
values_drop_na = TRUE) %>%
mutate(point = as.numeric(point) - 3) %>% #recode eval points to numeric and set to 1:51
left_join(theta.points, by = "point") %>% #merge names and theta points
left_join(item.names, by = "item")
#expected item score
irt.OCC.long <- irt.OCC.long %>%
#filter(item == 1) %>%
#arrange(item, point) %>%
#group_by(item, option, point) %>%
mutate(eis.prob = round(as.numeric(option)*occ.prob, 1),
theta = round(theta, 1)) %>%
group_by(item, point) %>%
mutate(eis.prob = sum(eis.prob)) %>%
ungroup()
myplots <- vector('list',irt.OCC$nitem)
#print ggplots for all evalutated items
for (i in 1:irt.OCC$nitem) {
myplots[[i]] <- print(irt.OCC.long %>%
filter(item == i) %>%
ggplot(aes(x = theta, y = occ.prob, color = option)) +
geom_line() +
scale_colour_grey(name = "Response Option:",
labels = c("Strongly disagree",
"Somewhat disagree",
"Somewhat agree",
"Agree",
"Strongly agree")) +
scale_x_continuous(breaks = c(-3, -2, -1, 0, 1, 2, 3),
sec.axis = dup_axis(breaks = irt.OCC$subjthetasummary,
labels = c("5%", "25%", "", "75%",
"95%"),
name = irt.OCC$itemlabels[i],)) +
scale_y_continuous(breaks = c(0.0, 0.2, 0.4, 0.6, 0.8, 1.0)) +
labs(title = '', #paste(irt.OCC$itemlabels[i]
x = '', #Theta
y = '') + #Probability of Item Endorsement
theme_classic() +
theme(#legend.position = "none",
#axis.text.y = element_text(angle = 90, hjust = .5, size = 10),
panel.border = element_rect(colour = "black", fill=NA),
plot.title = element_blank(),
axis.title.x.bottom = element_blank(),
axis.title.y = element_blank(),
axis.text.x.top = element_text(size=7),
axis.title.x.top = element_text(size=9),
#legend.box.background = element_rect(colour = "black", linetype='solid'),
legend.title = element_text(size=9),
legend.text = element_text(size=9),
legend.spacing.x = unit(.1, 'cm')) +
geom_vline(xintercept=c(irt.OCC$subjthetasummary), linetype = 2,
alpha=.25) +
guides(colour = guide_legend(override.aes = list(size=3)))
)
}
fig1.New <- ggarrange(myplots[[1]],
myplots[[2]],
myplots[[3]],
ncol = 3, nrow = 1, common.legend = TRUE, legend = "bottom")
fig1 <- annotate_figure(fig1.New,
bottom = text_grob(expression(paste("Level of Problematic Smartphone Use (", theta, ")")), size = 10),
left = text_grob("Probability of Item Endorsement", rot = 90, size = 10))
print(fig1)
```
#Regression Tables
```{r Regression Modeling - Constrast Coding}
##Create dummy variables for gender
###Gender
contrasts(Final$Gender) <- contr.treatment(3, base = 2)
Final$Gender
Female.Male <- c(1, 0, 0)
Other.Male <- c(0, 0, 1)
contrasts(Final$Gender) <- cbind(Female.Male, Other.Male)
###Grade Level
contrasts(Final$Grade) <- contr.treatment(2, base = 2)
Final$Grade
grady <- c(0, 1)
contrasts(Final$Grade) <- cbind(grady)
###Race
contrasts(Final$Race) <- contr.treatment(9, base = 1)
Final$Race
Black.vs.White <- c(0, 1, 0, 0, 0, 0, 0, 0, 0)
Hisp.vs.White <- c(0, 0, 1, 0, 0, 0, 0, 0, 0)
As.vs.White <- c(0, 0, 0, 1, 0, 0, 0, 0, 0)
AlN.vs.White <- c(0, 0, 0, 0, 1, 0, 0, 0, 0)
PI.vs.White <- c(0, 0, 0, 0, 0, 1, 0, 0, 0)
Other.vs.White <- c(0, 0, 0, 0, 0, 0, 1, 0, 0)
MR.vs.White <- c(0, 0, 0, 0, 0, 0, 0, 1, 0)
Decline.vs.White <- c(0, 0, 0, 0, 0, 0, 0, 0, 1)
contrasts(Final$Race) <- cbind(Black.vs.White,
Hisp.vs.White,
As.vs.White,
AlN.vs.White,
PI.vs.White,
Other.vs.White,
MR.vs.White,
Decline.vs.White)
```
```{r Design Survey Weighted Model}
## set up survey weighted models
#proportion of each student at each school
#set id var
Final$Student <- factor(seq(100000,100000+nrow(Final)-1))
Final$SCHOOLID <- factor(Final$SCHOOLID)
Final$W1 <- Final$Weight
Final$W2 <- Final$REGION
Final$SP_Soc_Awk <- factor(Final$SP_Soc_Awk)
#set design object
Final.design <- svydesign(id = ~Student,
weights = ~Weight,
strata = ~REGION,
data = Final)
```
```{r Table 3}
#Sleep
fit.glm.Sleep <- svyglm(SP_Sleep ~ PSU.Score +
Gender +
Grade +
Race,
design = Final.design,
na.action=na.omit)
summary.glm(fit.glm.Sleep)
summ(fit.glm.Sleep, confint = TRUE)
regTermTest(fit.glm.Sleep, ~PSU.Score, method="LRT")
fit.glm.Sleep <- allEffects(fit.glm.Sleep)
plot(fit.glm.psc.brief.effects)
#Work
fit.glm.Work <- svyglm(SP_Work ~ PSU.Score +
Gender +
Grade +
Race,
design = Final.design,
na.action=na.omit)
summary.glm(fit.glm.Work)
summ(fit.glm.Work, confint = TRUE)
regTermTest(fit.glm.Work, ~PSU.Score, method="LRT")
fit.glm.Work <- allEffects(fit.glm.Work)
plot(fit.glm.Work)
#Fit Loneliness
fit.glm.loneliness <- svyglm(lonelyR ~ PSU.Score + Gender + Grade + Race, design = final2.design,na.action=na.omit)
summary(fit.glm.loneliness)
summ(fit.glm.loneliness, confint = TRUE)
#Fit Depression
fit.glm.Dep <- svyglm(Sad2 ~ PSU.Score + Gender + Grade + Race,
design = Final.design,
na.action=na.omit,
family = "binomial")
summary(fit.glm.Dep)
summ(fit.glm.Dep, confint = TRUE)
OR.Dep <- cbind(exp(coef(fit.glm.Dep)),
exp(confint(fit.glm.Dep)))
print(OR.Dep)
regTermTest(fit.glm.Dep, ~PSU.Score, method="LRT")
fit.glm.Dep.effects <- allEffects(fit.glm.Dep)
plot(fit.glm.Dep.effects)
```
#Test Information Function
```{r Figure 3 - Test Information Function for Problematic Smartphone Use}
str(plot(fit.mirt.PSU, type='info', MI = 100))$panel.args
TI.PSU = (plot(fit.mirt.PSU, type='info', MI = 100))
data.frame(TI.PSU$panel.args)
str(plot(fit.mirt.PSU, type='SE', MI = 100))
TI.PSU.2 = plot(fit.mirt.PSU, type='SE', MI = 100)
data.frame(TI.PSU.2$panel.args)
library(tidyverse)
cbind(data.frame(TI.PSU$panel.args), data.frame(TI.PSU.2$panel.args))
TI.PSU.Final = cbind(data.frame(TI.PSU$panel.args) %>% rename("z" = 1, "test.info" = 2),
data.frame(TI.PSU.2$panel.args) %>% select(2) %>% rename("se" = 1)) %>%
print()
TI.PSU.Final <- TI.PSU.Final %>%
rowwise() %>%
mutate(ci.low = test.info + (se * 1.96),
ci.high = test.info - (se * 1.96)) %>%
as.data.frame() %>%
print()
ggplot(TI.PSU.Final, aes(x=z)) +
#geom_ribbon(aes(ymin=ci.low, ymax=ci.high, linetype="dotted"), colour="black", alpha = 0.2) +
geom_line(aes(y=se), linetype="dashed") +
geom_line(aes(y=test.info)) +
#scale_linetype_manual(values = c(3))+
scale_fill_manual(values = c("grey60"))+
scale_color_manual(values = c('black'))+
scale_x_continuous(breaks = seq(-5, 5, 1)) +
scale_y_continuous(sec.axis = sec_axis(~., name = "Standard Error")) +
coord_cartesian(ylim = c(0,6), xlim = c(-3.5,3.5)) +
theme_bw() +
theme(legend.position = "none",
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
text=element_text(family = "sans", face = "bold", size = 9),
panel.background = element_rect(colour = "black", fill = NA, linetype=1, size = 1)) +
#ggtitle("PSU and Psychosocial Test Infromation Functions") +
ylab("Test Information (95% CI)") +
xlab("Level of Problematic Smartphone Use") +
geom_vline(xintercept = 0, linetype="dotted", colour="black", alpha = 0.33)
```
#General Additive Modeling
```{r GAM PSU}
#item 3 not looking so good:
#fit gamm to check functional form:
# same as above, but with plausible values to obtain the standard errors
set.seed(4321)
ThetaPV <- fscores(fit.mirt.PSU, plausible.draws=10)
IG0 <- itemGAM(PSU[,1], ThetaPV) #good item
IG1 <- itemGAM(PSU[,2], ThetaPV)
IG2 <- itemGAM(PSU[,3], ThetaPV) #not so good item, cat 2 and 3 dampened
plot(IG0)
plot(IG1)
plot(IG2)
```
```{r Collapse the Middle Category on the Parent Item}
### Given weaker fit for parent item, fit collapsed categories for middle responses given residuals seemed highest there
####Collapsed parent item leads to improved model fit
####Collapsed parent item leads to slight imporvement in CoefH 0.48 -> 0.52
####Collasped parent item leads to improved item residual concordance with ICC
PSU.2 <- PSU
#collapse middle categories
collapse_middle <- function(x) {
x[x == 1] <- 1
x[x %in% 2:3] <- 2
x[x == 4] <- 3
return(x)
}
#try all items
PSU.2 <- data.frame(sapply(PSU.2, collapse_middle))
#better fit if just collapse item 3 'parent'
PSU.2$SP_Parent <- collapse_middle(PSU.2$SP_Parent)
fit.mirt.PSU.v2 <-mirt(PSU.2[1:3], model=1,
itemtype = c('graded','graded','graded'),
#method = "MHRM",
technical= list(removeEmptyRows=TRUE),
SE = TRUE,
survey.weights = PSU.2$Weight)
coef(fit.mirt.PSU.v2, simplify=TRUE, IRTpars=TRUE)
anova(fit.mirt.PSU, fit.mirt.PSU.v2)
itemfit(fit.mirt.PSU.v2)
itemplot(fit.mirt.PSU.v2, 3)
#plot empirical item plot of residuals vs predicted curve
item.fit.psu2.1 <- itemfit(fit.mirt.PSU.v2, group.bins=15,
empirical.plot = 1, method = 'ML') #empirical item plot with 15 points
item.fit.psu2.1
item.fit.psu2.2 <- itemfit(fit.mirt.PSU.v2, group.bins=15,
empirical.plot = 2, method = 'ML') #empirical item plot with 15 points
item.fit.psu2.2
item.fit.psu2.3 <- itemfit(fit.mirt.PSU.v2, group.bins=15,
empirical.plot = 3, method = 'ML') #empirical item plot with 15 points
item.fit.psu2.3
#curve(dchisq(x, df = 7), from = 0, to = 2000)
coefH(PSU[1:3], se=FALSE)
#collapsing does improve the H a little
coefH(PSU.2[1:3], se=FALSE)
```
```{r GAM PSU}
## GAM used to evaluate item form for any deviations from monotone increases
#No obvious shift away from assumptions. Not surprising given fully non-parametric model results
#plot gam
ThetaPV.2 <- fscores(fit.mirt.PSU.v2, plausible.draws=10)
IG2.2 <- itemGAM(PSU.2[,3], ThetaPV.2) #not so good item, cat 2 and 3 dampened
#plot(IG2.2)
```
```{r Person-Level Respones PSU}
#Check person-level responses
person.fit.1 <- personfit(fit.mirt.PSU.v2, stats.only = FALSE)
person.fit.1
hist(person.fit.1$Zh)
#Get IRT Scores
irt.score<-fscores(fit.mirt.PSU.v2, method='EAP', full.scores = FALSE)
irt.score
Final$irt.score<-fscores(fit.mirt.PSU.v2, method='EAP')
#Plot Raw Sum with Latent Factor Score
Final$sum.total<-apply(fit.mirt.PSU.v2@Data$data, 1, sum, na.rm=FALSE)
ggplot(Final, aes(x=sum.total, y=irt.score))+
geom_jitter(width=0.25) +
geom_smooth(method='lm')+
scale_y_continuous('Level of Latent Trait') +
scale_x_continuous('Smartphone Total') +
theme_bw() +
ggtitle('Relationship Between Observed Raw Score and IRT Score')
```
```{r Compute Tertiles}
quantile(Final2$PSU.Score, probs = c(.33, .66, .99))
quantile(Final2$PSC.brief, probs = c(.33, .66, .99))
Final2$SP_Soc_Awk <- as.numeric(as.character(Final2$SP_Soc_Awk))
quantile(Final2$SP_Soc_Awk, probs = c(.33, .66, .99))
quantile(Final2$lonelyR, probs = c(.33, .66, .99))
```
```{r Proportions for Total IRT Score}
TotalScore <- Final[, c(1:3)]
TotalScore <- mutate(TotalScore,
Total = SP_Uncomfort + SP_Constant + SP_Parent)
freqdist::freqdist(TotalScore$Total)
```
<file_sep>/MTMM Project/EverybodyLies.Rmd
---
title: 'Understanding Self-Report and Monomethod Bias in Positive Organizational Psychology:
A Multitrait-Multimethod Analysis'
author: "<NAME>, Ph.D"
date: "9/29/2020"
output:
html_document:
df_print: paged
---
#Upload Packages
```{r Packages, echo=TRUE, message=FALSE, warning=FALSE}
#Upload packages
library(haven)
library(careless)
library(tidyverse)
library(psych)
library(Hmisc)
library(magrittr)
library(pastecs)
library(QuantPsyc)
library(ppcor)
library(GPArotation)
library(gmodels)
```
#Data Manipulation
```{r Data Manipulation, message=FALSE, warning=FALSE, include=FALSE}
#Import from SPSS
MTMM_Clean <- read_sav("MTMM.Clean.sav")
View(MTMM_Clean)
MTMM.ID <- MTMM_Clean %>% mutate(id = row_number())
Demos <- MTMM.ID[, c(82:100, 165:189, 259:277, 347:371, 383)]
#Remove careless responding
##Keep track of all scale items for EMP1(C) and EMP1(C)
Final <- MTMM.ID[, c(11:81, 101:164, 190:258, 278:346, 383)]
##Mahal Distance (Across Pairs)
data.frame(colnames(Final))
MD <- mahad(Final, flag = TRUE, confidence = 0.999)
filter(MD, flagged == TRUE)
Final2 <- Final[-c(165), ]
##Longstring Invariant Responding
###EMP1 Lonstring
EMP1.L <- Final2[ , c(136:204, 274)]
longstring_EMP1 <- longstring(EMP1.L)
longstring_EMP1 <- as.data.frame(longstring_EMP1)
boxplot(longstring_EMP1)
quantile(longstring_EMP1$longstring_EMP1)
table(longstring_EMP1)
###EMP1C Longstring
EMP1C.L <- Final2[ , c(205:273)]
longstring_EMP1C <- longstring(EMP1C.L)
longstring_EMP1C <- as.data.frame(longstring_EMP1C)
boxplot(longstring_EMP1C)
quantile(longstring_EMP1C$longstring_EMP1C)
table(longstring_EMP1C)
#Clean up workspace
rm(list = "EMP1.L", "EMP1C.L", "EMP1.L", "EMP1C.L",
"Final", "longstring_EMP1" , "longstring_EMP1C",
"longstring_EMP1" , "longstring_EMP1C", "MD",
"MTMM_Clean", "MTMM.ID")
#Relational Data (Join the demos with ID variable)
##We want to join the scale data with Final.pairs to demographic data from MTMM_Clean
Final.Pairs2 <- Final2 %>% left_join(Demos, by = "id")
Final2 <- Final.Pairs2
rm(Final.Pairs2)
```
#Scale Scoring
```{r Well-Being Scales}
ScaleData <- Final2
##E1
ScaleData <- mutate(ScaleData,
PREL.Scale.E1 = (PREL_1_EMP1 + PREL_2_EMP1 + PREL_3_EMP1 +
PREL_4_EMP1)/4,
PE.Scale.E1 = (PE_1_EMP1 + PE_2_EMP1 + PE_3_EMP1)/3,
PMEAN.Scale.E1 = (PMEAN_1_EMP1 + PMEAN_2_EMP1 + PMEAN_3_EMP1)/3,
PACCOM.Scale.E1 = (PACCOM_1_EMP1 + PACCOM_2_EMP1 + PACCOM_3_EMP1)/3,
PEN.Scale.E1 = (PEN_1_EMP1 + PEN_2_EMP1 + PEN_3_EMP1)/3,
PECON.Scale.E1 = (PECON_1_EMP1 + PECON_2_EMP1 + PECON_3_EMP1)/3,
PMIND.Scale.E1 = (PMIND_1_EMP1 + PMIND_2_EMP1 + PMIND_3_EMP1)/3,
PHEALTH.Scale.E1 = (PPHealth_1_EMP1 + PPHealth_2_EMP1 + PPHealth_3_EMP1 +
PPHealth_4_EMP1)/4,
PPWE.Scale.E1 = (PPWE_1_EMP1 + PPWE_2_EMP1 + PPWE_3_EMP1)/3,
PERMA.E1 = (PREL.Scale.E1 + PE.Scale.E1 + PMEAN.Scale.E1 +
PACCOM.Scale.E1 + PEN.Scale.E1)/5,
PF.W.Scale.E1 = (PREL.Scale.E1 + PE.Scale.E1 + PMEAN.Scale.E1 +
PACCOM.Scale.E1 + PEN.Scale.E1 + PECON.Scale.E1 +
PMIND.Scale.E1 + PHEALTH.Scale.E1 + PPWE.Scale.E1)/9,
#E2C
PREL.Scale.E2C = (PREL_1_EMP1C + PREL_2_EMP1C + PREL_3_EMP1C +
PREL_4_EMP1C)/4,
PE.Scale.E2C = (PE_1_EMP2_C + PE_2_EMP2_C + PE_3_EMP2_C)/3,
PMEAN.Scale.E2C = (PMEAN_1_EMP2_C + PMEAN_2_EMP2_C + PMEAN_3_EMP2_C)/3,
PACCOM.Scale.E2C = (PACCOM_1_EMP2_C + PACCOM_2_EMP2_C + PACCOM_3_EMP2_C)/3,
PEN.Scale.E2C = (PEN_1_EMP2_C + PEN_2_EMP2_C + PEN_3_EMP2_C)/3,
PECON.Scale.E2C = (PECON_1_EMP2_C + PECON_2_EMP2_C + PECON_3_EMP2_C)/3,
PMIND.Scale.E2C = (PMIND_1__EMP2_C + PMIND_2_EMP2_C + PMIND_3_EMP2_C)/3,
PHEALTH.Scale.E2C= (PPHealth_1_EMP2_C + PPHealth_2_EMP2_C + PPHealth_3_EMP2_C +
PPHealth_4_EMP2_C)/4,
PPWE.Scale.E2C = (PPWE_1_EMP2_C + PPWE_2_EMP2_C + PPWE_3_EMP2_C)/3,
PERMA.E2C = (PREL.Scale.E2C + PE.Scale.E2C + PMEAN.Scale.E2C +
PACCOM.Scale.E2C + PEN.Scale.E2C)/5,
PF.W.Scale.E2C = (PREL.Scale.E2C + PE.Scale.E2C + PMEAN.Scale.E2C +
PACCOM.Scale.E2C + PEN.Scale.E2C + PECON.Scale.E2C +
PMIND.Scale.E2C + PHEALTH.Scale.E2C + PPWE.Scale.E2C)/9)
#Scoring PERMA and PF-W for E2 and E1C
##EMP1
ScaleData <- mutate(ScaleData,
PREL.Scale.E2 = (PREL_1_EMP2 + PREL_2_EMP2 + PREL_3_EMP2 +
PREL_4_EMP2)/4,
PE.Scale.E2 = (PE_1_EMP2 + PE_2_EMP2 + PE_3_EMP2)/3,
PMEAN.Scale.E2 = (PMEAN_1_EMP2 + PMEAN_2_EMP2 + PMEAN_3_EMP2)/3,
PACCOM.Scale.E2 = (PACCOM_1_EMP2 + PACCOM_2_EMP2 + PACCOM_3_EMP2)/3,
PEN.Scale.E2 = (PEN_1_EMP2 + PEN_2_EMP2 + PEN_3_EMP2)/3,
PECON.Scale.E2 = (PECON_1_EMP2 + PECON_2_EMP2 + PECON_3_EMP2)/3,
PMIND.Scale.E2 = (PMIND_1_EMP2 + PMIND_2_EMP2 + PMIND_3_EMP2)/3,
PHEALTH.Scale.E2 = (PPHealth_1_EMP2 + PPHealth_2_EMP2 + PPHealth_3_EMP2 +
PPHealth_4_EMP2)/4,
PPWE.Scale.E2 = (PPWE_1_EMP2 + PPWE_2_EMP2 + PPWE_3_EMP2)/3,
PERMA.E2 = (PREL.Scale.E2 + PE.Scale.E2 + PMEAN.Scale.E2 +
PACCOM.Scale.E2 + PEN.Scale.E2)/5,
PF.W.Scale.E2 = (PREL.Scale.E2 + PE.Scale.E2 + PMEAN.Scale.E2 +
PACCOM.Scale.E2 + PEN.Scale.E2 + PECON.Scale.E2 +
PMIND.Scale.E2 + PHEALTH.Scale.E2 + PPWE.Scale.E2)/9,
#Add coworker
PREL.Scale.E1C = (PREL_1_EMP1C + PREL_2_EMP1C + PREL_3_EMP1C +
PREL_4_EMP1C)/4,
PE.Scale.E1C = (PE_1_EMP1C + PE_2_EMP1C + PE_3_EMP1C)/3,
PMEAN.Scale.E1C = (PMEAN_1_EMP1C + PMEAN_2_EMP1C + PMEAN_3_EMP1C)/3,
PACCOM.Scale.E1C = (PACCOM_1_EMP1C + PACCOM_2_EMP1C + PACCOM_3_EMP1C)/3,
PEN.Scale.E1C = (PEN_1_EMP1C + PEN_2_EMP1C + PEN_3_EMP1C)/3,
PECON.Scale.E1C = (PECON_1_EMP1C + PECON_2_EMP1C + PECON_3_EMP1C)/3,
PMIND.Scale.E1C = (PMIND_1_EMP1C + PMIND_2_EMP1C + PMIND_3_EMP1C)/3,
PHEALTH.Scale.E1C= (PPHealth_1_EMP1C + PPHealth_2_EMP1C + PPHealth_3_EMP1C +
PPHealth_4_EMP1C)/4,
PPWE.Scale.E1C = (PPWE_1_EMP1C + PPWE_2_EMP1C + PPWE_3_EMP1C)/3,
PERMA.E1C = (PREL.Scale.E1C + PE.Scale.E1C + PMEAN.Scale.E1C +
PACCOM.Scale.E1C + PEN.Scale.E1C)/5,
PF.W.Scale.E1C = (PREL.Scale.E1C + PE.Scale.E1C + PMEAN.Scale.E1C +
PACCOM.Scale.E1C + PEN.Scale.E1C + PECON.Scale.E1C +
PMIND.Scale.E1C + PHEALTH.Scale.E1C + PPWE.Scale.E1C)/9
)
#Scoring for PsyCap E1 and E2
ScaleData <- mutate(ScaleData,
PsyCap.Hope.E1 = (Psy_H_1_EMP1 + Psy_H_2_EMP1)/2,
PsyCap.SE.E1 = (Psy_SE_1_EMP1 + Psy_SE_2_EMP1)/2,
PsyCap.Res.E1 = (Psy_R_1_EMP1 + Psy_R_2_EMP1)/2,
PsyCap.O.E1 = (Psy_0_1_EMP1 + Psy_O_2_EMP1)/2,
PsyCap.E1 = (Psy_H_1_EMP1 + Psy_H_2_EMP1 +
Psy_SE_1_EMP1 + Psy_SE_2_EMP1 +
Psy_R_1_EMP1 + Psy_R_2_EMP1 +
Psy_0_1_EMP1 + Psy_O_2_EMP1)/8,
PsyCap.Hope.E2C = (Psy_H_1_EMP2_C + Psy_H_2_EMP2_C)/2,
PsyCap.SE.E2C = (Psy_SE_1_EMP2_C + Psy_SE_2_EMP2_C)/2,
PsyCap.Res.E2C = (Psy_R_1_EMP2_C + Psy_R_2_EMP2_C)/2,
PsyCap.O.E2C = (Psy_0_1_EMP2_C + Psy_O_2_EMP2_C)/2,
PsyCap.E2C = (Psy_H_1_EMP2_C + Psy_H_2_EMP2_C +
Psy_SE_1_EMP2_C + Psy_SE_2_EMP2_C +
Psy_R_1_EMP2_C + Psy_R_2_EMP2_C +
Psy_0_1_EMP2_C + Psy_O_2_EMP2_C)/8)
#Scoring PsyCap E2 and E1C
ScaleData <- mutate(ScaleData,
PsyCap.Hope.E2 = (Psy_H_1_EMP2 + Psy_H_2_EMP2)/2,
PsyCap.SE.E2 = (Psy_SE_1_EMP2 + Psy_SE_1_EMP2)/2,
PsyCap.Res.E2 = (Psy_R_1_EMP2 + Psy_R_1_EMP2)/2,
PsyCap.O.E2 = (Psy_0_1_EMP2 + Psy_O_2_EMP2)/2,
PsyCap.E2 = (Psy_H_1_EMP2 + Psy_H_2_EMP2 +
Psy_SE_1_EMP2 + Psy_SE_1_EMP2 +
Psy_R_1_EMP2 + Psy_R_2_EMP2 +
Psy_0_1_EMP2 + Psy_O_2_EMP2)/8,
PsyCap.Hope.E1C = (Psy_H_1_EMP1C + Psy_H_2_EMP1C)/2,
PsyCap.SE.E1C = (Psy_SE_1_EMP1C + Psy_SE_1_EMP1C)/2,
PsyCap.Res.E1C = (Psy_R_1_EMP1C + Psy_R_1_EMP1C)/2,
PsyCap.O.E1C = (Psy_0_1_EMP1C + Psy_O_2_EMP2_C)/2,
PsyCap.E1C = (Psy_H_1_EMP1C + Psy_H_2_EMP1C +
Psy_SE_1_EMP1C + Psy_SE_1_EMP1C +
Psy_R_1_EMP1C + Psy_R_2_EMP1C +
Psy_0_1_EMP1C + Psy_O_2_EMP1C)/8)
#Scoring for SWL E1 and E2C
ScaleData <- mutate(ScaleData,
SWLS.E1 = (SWL_1_EMP1 + SWL_2_EMP1 +SWL_3_EMP1 + SWL_4_EMP1 +
SWL_5_EMP1)/5,
SWLS.E2C = (SWL_1__EMP2_C + SWL_2__EMP2_C +SWL_3__EMP2_C +
SWL_4__EMP2_C + SWL_5__EMP2_C)/5)
```
```{r Performance Scales}
#Scoring PWB for E1 and E2C
ScaleData <-
mutate(ScaleData,
OPRO.E1 = (PRO1_EMP1 + PRO2_EMP1 + PRO3_EMP1)/3,
OADAPT.E1 = (ADAPT1_EMP1 + ADAPT2_EMP1 + ADAPT3_EMP1)/3,
OPROF.E1 = (PROF1_EMP1 + PROF2_EMP1 + PROF3_EMP1)/3,
OPRO.E2C = (OPRO1_EMP2_C + OPRO2_EMP2_C + OPROF3_EMP2_C)/3,
OADAPT.E2C= (OADAPT1_EMP2_C + OADAPT2_EMP2_C + OADAPT3_EMP2_C)/3,
OPROF.E2C = (OPROF1_EMP2_C + OPROF2_EMP2_C + OPROF3_EMP2_C)/3)
#Scoring PWB for E2 and E1C
ScaleData <-
mutate(ScaleData,
OPRO.E2 = (PRO1_EMP2 + PRO2_EMP2 + PRO3_EMP2)/3,
OADAPT.E2 = (ADAPT1_EMP2 + ADAPT2_EMP2 + ADAPT3_EMP2)/3,
OPROF.E2 = (PROF1_EMP2 + PROF2_EMP2 + PROF3_EMP2)/3,
OPRO.E1C = (OPRO1_EMP1C + OPRO2_EMP1C + OPRO3_EMP1C)/3,
OADAPT.E1C= (OADAPT1_EMP1C + OADAPT2_EMP1C + OADAPT3_EMP1C)/3,
OPROF.E1C = (OPROF1_EMP1C + OPROF2_EMP1C + OPROF3_EMP1C)/3,
#Scoring JAWS
JAWS.PE.E1 = (J1_EMP1 + J2_EMP1 + J3_EMP1 + J4_EMP1 + J5_EMP1 +
J6_EMP1 + J7_EMP1 + J8_EMP1 + J9_EMP1 + J10_EMP1)/10,
JAWS.PE.E2C= (J1_EMP2_C + J2_EMP2_C + J3_EMP2_C + J4_EMP2_C + J5_EMP2_C +
J6_EMP2_C + J7_EMP2_C + J8_EMP2_C + J9_EMP2_C + J10_EMP2_C)/10,
JAWS.PE.E2 = (J1_EMP2 + J2_EMP2 + J3_EMP2 + J4_EMP2 + J5_EMP2 +
J6_EMP2 + J7_EMP2 + J8_EMP2 + J9_EMP2 + J10_EMP2)/10,
JAWS.PE.E1C= (J1_EMP1C + J2_EMP1C + J3_EMP1C + J4_EMP1C + J5_EMP1C +
J6_EMP1C + J7_EMP1C + J8_EMP1C + J9_EMP1C + J10_EMP1C)/10)
#Scoring Turnover for all, echo=false}
##EMP1
ScaleData$Turnover_1_EMP1 <- as.numeric(ScaleData$Turnover_1_EMP1)
ScaleData$Turnover_2_EMP1 <- as.numeric(ScaleData$Turnover_2_EMP1)
ScaleData$Turnover_3_EMP1 <- as.numeric(ScaleData$Turnover_3_EMP1)
ScaleData$Turnover_4_R_EMP1 <- as.numeric(ScaleData$Turnover_4_R_EMP1)
ScaleData$Turnover_5_EMP1 <- as.numeric(ScaleData$Turnover_5_EMP1)
##EMP2C
ScaleData$Turnover_1_EMP2_C <- as.numeric(ScaleData$Turnover_1_EMP2_C)
ScaleData$Turnover_2_EMP2_C <- as.numeric(ScaleData$Turnover_2_EMP2_C)
ScaleData$Turnover_3_EMP2_C <- as.numeric(ScaleData$Turnover_3_EMP2_C)
ScaleData$Turnover_4_R_EMP2_C <- as.numeric(ScaleData$Turnover_4_R_EMP2_C)
ScaleData$Turnover_5_EMP2_C <- as.numeric(ScaleData$Turnover_3_EMP2_C)
##EMP2
ScaleData$Turnover_1_EMP2 <- as.numeric(ScaleData$Turnover_1_EMP2)
ScaleData$Turnover_2_EMP2 <- as.numeric(ScaleData$Turnover_2_EMP2)
ScaleData$Turnover_3_EMP2 <- as.numeric(ScaleData$Turnover_3_EMP2)
ScaleData$Turnover_4_R_EMP2 <- as.numeric(ScaleData$Turnover_4_R_EMP2)
ScaleData$Turnover_5_EMP2 <- as.numeric(ScaleData$Turnover_3_EMP2)
##EMP1C
ScaleData$Turnover_1_EMP1C <- as.numeric(ScaleData$Turnover_1_EMP1C)
ScaleData$Turnover_2_EMP1C <- as.numeric(ScaleData$Turnover_2_EMP1C)
ScaleData$Turnover_3_EMP1C <- as.numeric(ScaleData$Turnover_3_EMP1C)
ScaleData$Turnover_4_R_EMP1C <- as.numeric(ScaleData$Turnover_4_R_EMP1C)
ScaleData$Turnover_5_EMP1C <- as.numeric(ScaleData$Turnover_3_EMP1C)
#Recode Turnover and Reverse the 4th and 5th Item
##EMP1
ScaleData$Turnover_1_EMP1 <- recode(ScaleData$Turnover_1_EMP1,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_2_EMP1 <- recode(ScaleData$Turnover_2_EMP1,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_3_EMP1 <- recode(ScaleData$Turnover_3_EMP1,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_4_R_EMP1 <- recode(ScaleData$Turnover_4_R_EMP1,
'20' = 5,
'21' = 4,
'22' = 3,
'23' = 2,
'24' = 1)
ScaleData$Turnover_5_EMP1 <- recode(ScaleData$Turnover_5_EMP1,
'20' = 5,
'21' = 4,
'22' = 3,
'23' = 2,
'24' = 1)
##EMP2C
ScaleData$Turnover_1_EMP2_C <- recode(ScaleData$Turnover_1_EMP2_C,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_2_EMP2_C <- recode(ScaleData$Turnover_2_EMP2_C,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_3_EMP2_C <- recode(ScaleData$Turnover_3_EMP2_C,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_4_R_EMP2_C <- recode(ScaleData$Turnover_4_R_EMP2_C,
'20' = 5,
'21' = 4,
'22' = 3,
'23' = 2,
'24' = 1)
ScaleData$Turnover_5_EMP2_C <- recode(ScaleData$Turnover_5_EMP2_C,
'20' = 5,
'21' = 4,
'22' = 3,
'23' = 2,
'24' = 1)
##EMP2
ScaleData$Turnover_1_EMP2 <- recode(ScaleData$Turnover_1_EMP2,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_2_EMP2 <- recode(ScaleData$Turnover_2_EMP2,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_3_EMP2 <- recode(ScaleData$Turnover_3_EMP2,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_4_R_EMP2 <- recode(ScaleData$Turnover_4_R_EMP2,
'20' = 5,
'21' = 4,
'22' = 3,
'23' = 2,
'24' = 1)
ScaleData$Turnover_5_EMP2 <- recode(ScaleData$Turnover_5_EMP2,
'20' = 5,
'21' = 4,
'22' = 3,
'23' = 2,
'24' = 1)
##EMP1C
ScaleData$Turnover_1_EMP1C <- recode(ScaleData$Turnover_1_EMP1C,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_2_EMP1C <- recode(ScaleData$Turnover_2_EMP1C,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_3_EMP1C <- recode(ScaleData$Turnover_3_EMP1C,
'20' = 1,
'21' = 2,
'22' = 3,
'23' = 4,
'24' = 5)
ScaleData$Turnover_4_R_EMP1C <- recode(ScaleData$Turnover_4_R_EMP1C,
'20' = 5,
'21' = 4,
'22' = 3,
'23' = 2,
'24' = 1)
ScaleData$Turnover_5_EMP1C <- recode(ScaleData$Turnover_5_EMP1C,
'20' = 5,
'21' = 4,
'22' = 3,
'23' = 2,
'24' = 1)
#Scoring Turnover E1 and E2C
ScaleData <-
mutate(ScaleData,
Turnover.E1 = (Turnover_1_EMP1 + Turnover_2_EMP1 + Turnover_3_EMP1 + Turnover_4_R_EMP1 +
Turnover_5_EMP1)/5,
Turnover.E2C = (Turnover_1_EMP2_C + Turnover_2_EMP2_C + Turnover_3_EMP2_C +
Turnover_4_R_EMP2_C + Turnover_5_EMP2_C)/5)
#Scoring Turnover E2 and E1C
ScaleData <-
mutate(ScaleData,
Turnover.E2 = (Turnover_1_EMP2 + Turnover_2_EMP2 + Turnover_3_EMP2 + Turnover_4_R_EMP2 +
Turnover_5_EMP2)/5,
Turnover.E1C = (Turnover_1_EMP1C + Turnover_2_EMP1C + Turnover_3_EMP1C + Turnover_4_R_EMP1C +
Turnover_5_EMP1C)/5)
```
```{r Demographics - Employee 1}
#Demographics Scoring
##Employee 1 Demos
###Subset only Scale Scores and Demographics
TidyData <- ScaleData[, c(274:293, 363:384)]
TidyData$Ethnicity_EMP1_2[TidyData$Ethnicity_EMP1_2 %in% 1] <- 2
TidyData$Ethnicity_EMP1_3[TidyData$Ethnicity_EMP1_3 %in% 1] <- 3
TidyData$Ethnicity_EMP1_4[TidyData$Ethnicity_EMP1_4 %in% 1] <- 4
TidyData$Ethnicity_EMP1_5[TidyData$Ethnicity_EMP1_5 %in% 1] <- 5
TidyData$Ethnicity_EMP1_6[TidyData$Ethnicity_EMP1_6 %in% 1] <- 6
TidyData$Ethnicity_EMP1_7[TidyData$Ethnicity_EMP1_7 %in% 1] <- 7
#Unite Ethnicity into ETH.NUll and ETH.E2
TidyData <- unite(TidyData, ETH.E1, Ethnicity_EMP1_1, Ethnicity_EMP1_2, Ethnicity_EMP1_3, Ethnicity_EMP1_4, Ethnicity_EMP1_5, Ethnicity_EMP1_6, Ethnicity_EMP1_7, sep = "_", remove = FALSE, na.rm = TRUE)
##Recode into factor variables for both employees (Etnicity, Degree, Industry, JobFunction, Income)
TidyData$ETH.E1 <- as.factor(as.character(TidyData$ETH.E1))
TidyData$Degree_EMP1 <- as.factor(as.character(TidyData$Degree_EMP1))
TidyData$Industry_EMP1 <- as.factor(as.character(TidyData$Industry_EMP1))
TidyData$JobFunction_EMP1 <- as.factor(as.character(TidyData$JobFunction_EMP1))
TidyData$Income_EMP1 <- as.factor(as.character(TidyData$Income_EMP1))
TidyData$Gender_EMP1 <- as.factor(as.character(TidyData$Gender_EMP1))
TidyData <- TidyData %>% mutate(Degree.E1 = fct_recode(Degree_EMP1,
"Associate" = "1",
"Bachelor" = "2" ,
"Master" = "3" ,
"Doctorate" = "4" ,
"Highschool or less" = "5"
))
TidyData <- TidyData %>% mutate(Industry.E1 = fct_recode(Industry_EMP1,
"Banking" = "1",
"Education" = "2" ,
"Food & Beverage" = "3" ,
"Government" = "4" ,
"Healthcare" = "5",
"Manufacturing" = "6",
"Media & Entertainment" = "7",
"Retail, Wholesale, & Distribution" = "8",
"Software & IT" = "9",
"Nonprofit" = "10",
"Other" = "11"
))
TidyData <- TidyData %>% mutate(JobFunction.E1 = fct_recode(JobFunction_EMP1,
"Accounting & Finance" = "1",
"Administrative" = "2" ,
"Arts & Design" = "3" ,
"Education" = "4" ,
"Engineering" = "5",
"IT" = "6",
"Marketing, Sales, & Business Dev." = "7",
"Management" = "8",
"Operations" = "9",
"Other" = "10"
))
TidyData <- TidyData %>% mutate(Income.E1 = fct_recode(Income_EMP1,
"Less than 25k" = "1",
"25-49k" = "2" ,
"50-75k" = "3" ,
"75-99k" = "4" ,
"100-150k" = "5",
"150+" ="6"
))
data.frame(colnames(TidyData))
#####
Employee1.Demos <- TidyData[, c(1, 2, 11, 12, 44:47)]
Employee1.Demos <-Employee1.Demos %>% mutate(Eth.Final.E1 = fct_recode(ETH.E1,
"Multiracial" = "1_2_3_4_5_6_NA",
"Multiracial" = "NA_NA_3_NA_NA_6_NA" ,
"Multiracial" = "NA_NA_NA_4_NA_6_NA",
"Multiracial" = "NA_NA_NA_NA_5_6_NA",
"Multiracial" = "1_NA_3_NA_5_6_NA",
"Multiracial" = "1_NA_NA_NA_5_NA_NA",
"Asian" = "NA_NA_3_NA_NA_NA_NA",
"Hispanic" = "NA_NA_NA_NA_5_NA_NA" ,
"White" = "NA_NA_NA_NA_NA_6_NA",
"Multiracial" = "NA_NA_NA_NA_NA_NA_7",
"Black" = "1_NA_NA_NA_NA_NA_NA",
"NHOPI" = "NA_NA_NA_4_NA_NA_NA",
"ANAI" = "NA_2_NA_NA_NA_NA_NA"))
Employee1.Demos <-Employee1.Demos %>% mutate(Degree.Final = fct_recode(Degree.E1,
"Associate" = "1",
"Bachelor" = "2" ,
"Master" = "3" ,
"Doctorate" = "4" ,
"Highschool or less" = "5"
))
Employee1.Demos <-Employee1.Demos %>% mutate(Gender.Final = fct_recode(Gender_EMP1,
"Male" = "1",
"Female" = "2" ,
"Other" = "3"
))
Employee1.Demos <-Employee1.Demos %>% mutate(Industry.Final = fct_recode(Industry.E1,
"Banking" = "1",
"Education" = "2" ,
"Food & Beverage" = "3" ,
"Government" = "4" ,
"Healthcare" = "5",
"Manufacturing" = "6",
"Media & Entertainment" = "7",
"Retail, Wholesale, & Distribution" = "8",
"Software & IT" = "9",
"Nonprofit" = "10",
"Other" = "11"
))
Employee1.Demos <-Employee1.Demos %>% mutate(JobFunction.Final = fct_recode(JobFunction.E1,
"Accounting & Finance" = "1",
"Administrative" = "2" ,
"Arts & Design" = "3" ,
"Education" = "4" ,
"Engineering" = "5",
"IT" = "6",
"Marketing, Sales, & Business Dev." = "7",
"Operations" = "8",
"Management" = "12",
"Other" = "11"
))
Employee1.Demos <-Employee1.Demos %>% mutate(Income.Final = fct_recode(Income.E1,
"Less than 25k" = "1",
"25-49k" = "3" ,
"50-75k" = "4" ,
"75-99k" = "5" ,
"100-150k" = "6",
"150+" ="7"
))
Employee1.Demos <- Employee1.Demos[, c(3, 9:14)]
```
```{r Demographics - Employee 2}
#Employee 2 Demos
TidyData.E2 <- ScaleData[, c( 319:325, 327, 328, 330, 332, 334, 337)]
TidyData.E2$Ethnicity_EMP2_2[TidyData$Ethnicity_EMP2_2 %in% 1] <- 2
TidyData.E2$Ethnicity_EMP2_3[TidyData$Ethnicity_EMP2_3 %in% 1] <- 3
TidyData.E2$Ethnicity_EMP2_4[TidyData$Ethnicity_EMP2_4 %in% 1] <- 4
TidyData.E2$Ethnicity_EMP2_5[TidyData$Ethnicity_EMP2_5 %in% 1] <- 5
TidyData.E2$Ethnicity_EMP2_6[TidyData$Ethnicity_EMP2_6 %in% 1] <- 6
TidyData.E2$Ethnicity_EMP2_7[TidyData$Ethnicity_EMP2_7 %in% 1] <- 7
attach(TidyData.E2)
#Unite Ethnicity into ETH.NUll and ETH.E2
TidyData.E2 <- unite(TidyData.E2, ETH.E2, Ethnicity_EMP2_1, Ethnicity_EMP2_2, Ethnicity_EMP2_3, Ethnicity_EMP2_4, Ethnicity_EMP2_5, Ethnicity_EMP2_6, Ethnicity_EMP2_7, sep = "_", remove = FALSE, na.rm = TRUE)
##Recode into factor variables for both employees (Etnicity, Degree, Industry, JobFunction, Income)
TidyData.E2$ETH.E2 <- as.factor(as.character(TidyData.E2$ETH.E2))
TidyData.E2$Degree_EMP2 <- as.factor(as.character(TidyData.E2$Degree_EMP2))
TidyData.E2$Industry_EMP2 <- as.factor(as.character(TidyData.E2$Industry_EMP2))
TidyData.E2$JobFunction_EMP2 <- as.factor(as.character(TidyData.E2$JobFunction_EMP2))
TidyData.E2$Income_EMP2 <- as.factor(as.character(TidyData.E2$Income_EMP2))
TidyData.E2$Gender_EMP2 <- as.factor(as.character(TidyData.E2$Gender_EMP2))
TidyData.E2$Age_EMP2 <- as.numeric(as.character(TidyData.E2$Age_EMP2))
TidyData.E2 <- TidyData.E2 %>% mutate(Degree.E2 = fct_recode(Degree_EMP2,
"Associate" = "1",
"Bachelor" = "2" ,
"Master" = "3" ,
"Doctorate" = "4" ,
"Highschool or less" = "5"
))
TidyData.E2 <- TidyData.E2 %>% mutate(Industry.E2 = fct_recode(Industry_EMP2,
"Banking" = "1",
"Education" = "2" ,
"Food & Beverage" = "3" ,
"Government" = "4" ,
"Healthcare" = "5",
"Manufacturing" = "6",
"Media & Entertainment" = "7",
"Retail, Wholesale, & Distribution" = "8",
"Software & IT" = "9",
"Nonprofit" = "10",
"Other" = "11"
))
TidyData.E2 <- TidyData.E2 %>% mutate(JobFunction.E2 = fct_recode(JobFunction_EMP2,
"Accounting & Finance" = "1",
"Administrative" = "2" ,
"Arts & Design" = "3" ,
"Education" = "4" ,
"Engineering" = "5",
"IT" = "6",
"Marketing, Sales, & Business Dev." = "7",
"Management" = "12",
"Operations" = "8",
"Other" = "11"
))
TidyData.E2 <- TidyData.E2 %>% mutate(Income.E2 = fct_recode(Income_EMP2,
"Less than 25k" = "1",
"25-49k" = "3" ,
"50-75k" = "4" ,
"75-99k" = "5" ,
"100-150k" = "6",
"150+" = "7"
))
data.frame(colnames(TidyData.E2))
#####
Employee2.Demos <- TidyData.E2[, c(1, 9, 10, 15:18)]
Employee2.Demos <-Employee2.Demos %>% mutate(Eth.Final.E2 = fct_recode(ETH.E2,
"Multiracial" = "1_1_1_1_1_1_NA",
"Multiracial" = "1_NA_1_NA_1_1_NA" ,
"Multiracial" = "1_NA_NA_NA_1_NA_NA",
"Black" = "1_NA_NA_NA_NA_NA_NA",
"AIAN" = "NA_1_NA_NA_NA_NA_NA",
"Multiracial" = "NA_NA_1_NA_NA_1_NA",
"Asian" = "NA_NA_1_NA_NA_NA_NA",
"NHPI" = "NA_NA_NA_1_NA_NA_NA",
"Multiracial" = "NA_NA_NA_NA_1_1_NA",
"Hispanic" = "NA_NA_NA_NA_1_NA_NA" ,
"White" = "NA_NA_NA_NA_NA_1_NA"
))
Employee2.Demos <-Employee2.Demos %>% mutate(Degree.Final = fct_recode(Degree.E2,
"Associate" = "1",
"Bachelor" = "2" ,
"Master" = "3" ,
"Doctorate" = "4" ,
"Highschool or less" = "5"
))
Employee2.Demos <-Employee2.Demos %>% mutate(Gender.Final = fct_recode(Gender_EMP2,
"Male" = "1",
"Female" = "2" ,
"Other" = "3"
))
Employee2.Demos <-Employee2.Demos %>% mutate(Industry.Final = fct_recode(Industry.E2,
"Banking" = "1",
"Education" = "2" ,
"Food & Beverage" = "3" ,
"Government" = "4" ,
"Healthcare" = "5",
"Manufacturing" = "6",
"Media & Entertainment" = "7",
"Retail, Wholesale, & Distribution" = "8",
"Software & IT" = "9",
"Nonprofit" = "10",
"Other" = "11"
))
Employee2.Demos <-Employee2.Demos %>% mutate(JobFunction.Final = fct_recode(JobFunction.E2,
"Accounting & Finance" = "1",
"Administrative" = "2" ,
"Arts & Design" = "3" ,
"Education" = "4" ,
"Engineering" = "5",
"IT" = "6",
"Marketing, Sales, & Business Dev."= "7",
"Operations" = "8",
"Management" = "12",
"Other" = "11"
))
Employee2.Demos <-Employee2.Demos %>% mutate(Income.Final = fct_recode(Income.E2,
"Less than 25k" = "1",
"25-49k" = "3" ,
"50-75k" = "4" ,
"75-99k" = "5" ,
"100-150k" = "6",
"150+" ="7"
))
Employee2.Demos <- Employee2.Demos[, c(2,8:13)]
```
```{r Bias }
attach(ScaleData)
#E1 get rid of Haven label
ScaleData$Bias_EMP1_1 <- as.numeric(ScaleData$Bias_EMP1_1)
ScaleData$Bias_EMP1_2 <- as.numeric(ScaleData$Bias_EMP1_2)
ScaleData$Bias_EMP1_3 <- as.numeric(ScaleData$Bias_EMP1_3)
ScaleData$Bias_EMP1_4 <- as.numeric(ScaleData$Bias_EMP1_4)
ScaleData$Bias_EMP1_5 <- as.numeric(ScaleData$Bias_EMP1_5)
ScaleData$Bias_EMP1_6 <- as.numeric(ScaleData$Bias_EMP1_6)
#E1
ScaleData$Bias_EMP1_1 <- recode(ScaleData$Bias_EMP1_1,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$Bias_EMP1_2 <- recode(ScaleData$Bias_EMP1_2,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$Bias_EMP1_3 <- recode(ScaleData$Bias_EMP1_3,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$Bias_EMP1_4 <- recode(ScaleData$Bias_EMP1_4,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$Bias_EMP1_5 <- recode(ScaleData$Bias_EMP1_5,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$Bias_EMP1_6 <- recode(ScaleData$Bias_EMP1_6,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
#E2 get rid of Haven label
ScaleData$BIAS_EMP2_C_1 <- as.numeric(ScaleData$BIAS_EMP2_C_1)
ScaleData$BIAS_EMP2_C_2 <- as.numeric(ScaleData$BIAS_EMP2_C_2)
ScaleData$BIAS_EMP2_C_3 <- as.numeric(ScaleData$BIAS_EMP2_C_3)
ScaleData$BIAS_EMP2_C_4 <- as.numeric(ScaleData$BIAS_EMP2_C_4)
ScaleData$BIAS_EMP2_C_5 <- as.numeric(ScaleData$BIAS_EMP2_C_5)
ScaleData$BIAS_EMP2_C_6 <- as.numeric(ScaleData$BIAS_EMP2_C_6)
#E2
ScaleData$BIAS_EMP2_C_1 <- recode(ScaleData$BIAS_EMP2_C_1,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$BIAS_EMP2_C_2 <- recode(ScaleData$BIAS_EMP2_C_2,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$BIAS_EMP2_C_3 <- recode(ScaleData$BIAS_EMP2_C_3,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$BIAS_EMP2_C_4 <- recode(ScaleData$BIAS_EMP2_C_4,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$BIAS_EMP2_C_5 <- recode(ScaleData$BIAS_EMP2_C_5,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData$BIAS_EMP2_C_6 <- recode(ScaleData$BIAS_EMP2_C_6,
'11' = 1,
'12' = 2,
'13' = 3,
'14' = 4,
'15' = 5,
'16' = 6,
'17' = 7)
ScaleData <- mutate(ScaleData,
Knowledge.1.C = (Bias_EMP1_1 + BIAS_EMP2_C_1)/2,
Knowledge.2.C = (Bias_EMP1_2 + BIAS_EMP2_C_2)/2,
Confident.C = (Bias_EMP1_3 + BIAS_EMP2_C_3)/2,
Confident.Self = (Bias_EMP1_4 + BIAS_EMP2_C_4)/2,
Admission.Self = (Bias_EMP1_5 + BIAS_EMP2_C_5)/2,
Fear.Reprisal.Self = (Bias_EMP1_6 + BIAS_EMP2_C_6)/2
)
#Reverse Code Admission and Fear of Reprisal (5 and 6)
##Admission Self
ScaleData$Admission.Self.R <- recode(ScaleData$Admission.Self,
'1' = 7,
'1.5' = 6.5,
'2' = 6,
'2.5' = 5.5,
'3' = 5,
'3.5' = 4.5,
'4' = 4.0,
'4.5' = 3.5,
'5' = 3.0,
'5.5' = 2.5,
'6' = 2.0,
'6.5' = 1.5,
'7.0' = 1.0
)
##Fear of Reprisal Self
ScaleData$Fear.Reprisal.Self.R <- recode(ScaleData$Fear.Reprisal.Self,
'1' = 7,
'1.5' = 6.5,
'2' = 6,
'2.5' = 5.5,
'3' = 5,
'3.5' = 4.5,
'4' = 4.0,
'4.5' = 3.5,
'5' = 3.0,
'5.5' = 2.5,
'6' = 2.0,
'6.5' = 1.5,
'7.0' = 1.0
)
```
#Merge, Clean, and Create Master Data
```{r Create Master DATASET, echo=FALSE, message=FALSE, warning=FALSE}
#Create dataset for PERMA(4) and SWLS
Scale.Final <- ScaleData[, c(363:456)]
###Score Aggregated PERMA and PF
attach(Scale.Final)
Scale.Final$Empty <- seq(NA)
Scale.Final$Empty <- NA
Master <- data.frame(
PERMA.Self = c(Scale.Final$PERMA.E1, Scale.Final$PERMA.E2),
PF.Self = c(Scale.Final$PF.W.Scale.E1 , Scale.Final$PF.W.Scale.E2),
PERMA.C = c(Scale.Final$PERMA.E1C , Scale.Final$PERMA.E2C),
PF.C = c(Scale.Final$PF.W.Scale.E1C , Scale.Final$PF.W.Scale.E2C),
SWB.Self = c(Scale.Final$SWLS.E1, Scale.Final$Empty),
SWB.C = c(Scale.Final$SWLS.E2C, Scale.Final$Empty),
###Score Aggregated for PWB
OPRO.Self = c(Scale.Final$OPRO.E1 , Scale.Final$OPRO.E2),
OADAPT.Self = c(Scale.Final$OADAPT.E1 , Scale.Final$OADAPT.E2),
OPROF.Self = c(Scale.Final$OPROF.E1 , Scale.Final$OPROF.E2),
OPRO.C = c(Scale.Final$OPRO.E1C ,Scale.Final$OPRO.E2C),
OADAPT.C = c(Scale.Final$OADAPT.E1C , Scale.Final$OADAPT.E2C),
OPROF.C = c(Scale.Final$OPROF.E1C , Scale.Final$OPROF.E2C),
###JAWS
JAWS.PE.Self = c(Scale.Final$JAWS.PE.E1 , Scale.Final$JAWS.PE.E2),
JAWS.PE.C = c(Scale.Final$JAWS.PE.E1C , Scale.Final$JAWS.PE.E2C),
###Turnover
Turnover.Self = c(Scale.Final$Turnover.E1 , Scale.Final$Turnover.E2),
Turnover.C = c(Scale.Final$Turnover.E1C , Scale.Final$Turnover.E2C),
###PsyCap
PsyCap.Self = c(Scale.Final$PsyCap.E1 , Scale.Final$PsyCap.E2),
PsyCap.C = c(Scale.Final$PsyCap.E1C , Scale.Final$PsyCap.E2C),
###Bias
Accuracy.Co = (Scale.Final$Knowledge.1.C +
Scale.Final$Knowledge.2.C +
Scale.Final$Confident.C)/3,
Accuracy.Self = (Scale.Final$Admission.Self.R +
Scale.Final$Fear.Reprisal.Self.R)/2)
#Concatenate DEMOS
Demos.Final <- data.frame(
Age = c(Employee1.Demos$Age_EMP1,
Employee2.Demos$Age_EMP2),
Race = str_c(Employee1.Demos$Eth.Final.E1,
Employee2.Demos$Eth.Final.E2),
Gender = c(Employee1.Demos$Gender.Final,
Employee2.Demos$Gender.Final),
Income = c(Employee1.Demos$Income.Final,
Employee2.Demos$Income.Final),
Industry = c(Employee1.Demos$Industry.Final,
Employee2.Demos$Industry.Final),
JobFunction = c(Employee1.Demos$JobFunction.Final,
Employee2.Demos$JobFunction.Final),
Degree = c(Employee1.Demos$Degree.Final,
Employee2.Demos$Degree.Final)
)
##Final Merge
Demos.Final$ID.Final <- seq.int(nrow(Demos.Final))
Master$ID.Final <- seq.int(nrow(Master))
THE.MASTER <- left_join(Master, Demos.Final, by = "ID.Final")
```
```{r Final Recode, echo=FALSE, message=FALSE, warning=FALSE, paged.print=TRUE}
#Gender
THE.MASTER$Gender <- as.factor(THE.MASTER$Gender)
THE.MASTER$Gender <- recode_factor(THE.MASTER$Gender,
'1' ="Male",
'2' = "Female",
'3' = "Other")
#Race
THE.MASTER$Race <- as.factor(THE.MASTER$Race)
THE.MASTER$Race <- recode_factor(THE.MASTER$Race,
'1' ="Black",
'2' = "ANAI",
'3' = "Asian",
'4' ="NHPI",
'5' = "Hispanic",
'6' = "White",
'7' = "Other")
#Income
THE.MASTER$Income <- as.factor(THE.MASTER$Income)
THE.MASTER$Income <- recode_factor(THE.MASTER$Income,
'1' ="<25k",
'2' = "25-49k",
'3' = "50-74k",
'4' ="75-99k",
'5' = "100-150k",
'6' = "150k+")
#Industry
THE.MASTER$Industry <- as.factor(THE.MASTER$Industry)
THE.MASTER$Industry <- recode_factor(THE.MASTER$Industry,
'1' ="Banking & Financial Services",
'2' = "Education",
'3' = "Food & Beverage",
'4' ="Government",
'5' = "Healthcare",
'6' = "Manufacturing",
'7' = "Media & Entertainment",
'8' = "Retail, Wholesale, & Distribution",
'9' = "Software & IT Services",
'10'= "Non-Profit",
'11'= "Other")
#Job Function
THE.MASTER$JobFunction <- as.factor(THE.MASTER$JobFunction)
THE.MASTER$JobFunction <- recode_factor(THE.MASTER$JobFunction,
'1' ="Accounting & Finance",
'2' = "Administrative",
'3' = "Arts & Design",
'4' ="Education",
'5' = "Engineering",
'6' = "Information Technology",
'7' = "Marketing, Sales, & Business Development",
'8' = "Management",
'9' = "Operations",
'10' = "Other")
#Degree
THE.MASTER$Degree <- as.factor(THE.MASTER$Degree)
THE.MASTER$Degree <- recode_factor(THE.MASTER$Degree,
'1' ="Associate",
'2' = "Bachelor",
'3' = "Master",
'4' ="Doctorate",
'5' = "Other")
#Recode into Three categories
##Accuracy Self
THE.MASTER$Accuracy.Self.NEW[THE.MASTER$Accuracy.Self < 4] <- "Inaccurate"
THE.MASTER$Accuracy.Self.NEW[THE.MASTER$Accuracy.Self > 4] <- "Accurate"
##Accuracy Coworker
THE.MASTER$Accuracy.Co.NEW[THE.MASTER$Accuracy.Co < 4] <- "Inaccurate"
THE.MASTER$Accuracy.Co.NEW[THE.MASTER$Accuracy.Co > 4] <- "Accurate"
```
#Exploratory Factor Analysis with Accuracy Items
```{r Exploratory Factor Analysis}
#Subset Accuracy Items
Accurate <- ScaleData[,c(449:456)]
Accurate.NM <- na.omit(Accurate[, c(1:4, 7,8)])
Accurate.Final <- Accurate.NM[, -4] #Drop confident self
#Bartlet Test - is factor analysis appropirate
cortest.bartlett(Accurate.Final)
#KMO - is sample size and data adequate
KMO(Accurate.Final)
#Determinant
det(cor(Accurate.Final))
#Descriptives for the variables
sapply(Accurate.Final, mean, na.rm=TRUE)
cor(Accurate.Final)
#Alpha
alpha(Accurate.Final, check.keys = TRUE)
#Correlation between Self and Coworker Accuracy
Se.CO.Correlation <- THE.MASTER[, c(19,20)]
Se.CO.Correlation <- na.omit(Se.CO.Correlation)
cor(Se.CO.Correlation)
#Horn's Parallel Analysis
parallel <- fa.parallel(Accurate.Final, fm = 'minres', fa = 'fa')
#EFA Procedure
EFA = fa(Accurate.Final, nfactors = 2, rotate = "oblimin" , cor = "poly", scores = TRUE)
print(EFA)
```
```{r Accuracy Crosstab}
attach(THE.MASTER)
CrossTable(THE.MASTER$Accuracy.Co.NEW,
THE.MASTER$Accuracy.Self.NEW)
```
#Table 1 - Demographic Characteristics
```{r Method Section}
#Age
mean(THE.MASTER$Age, na.rm = TRUE)
sd(THE.MASTER$Age, na.rm = TRUE)
#Gender
freqdist::freqdist(THE.MASTER$Gender)
#Ethnicity
freqdist::freqdist(THE.MASTER$Race)
#Degree
freqdist::freqdist(THE.MASTER$Degree)
#Income
freqdist::freqdist(THE.MASTER$Income)
#Industry
freqdist::freqdist(THE.MASTER$Industry)
```
#Table 2 - Zero Order Convergence
```{r Table 2 Convergence}
#Means and SDS for PF and PsyCap Components
MeansTable.Other <- BuildingBlocks[, c(1:22, 35:44)]
sapply(MeansTable.Other, mean, na.rm=TRUE)
sapply(MeansTable.Other, sd, na.rm=TRUE)
MeansTable.Other.matrix <- as.matrix(MeansTable.Other)
#Convergence
##Well-Being Measures
rcorr(MeansTable.Other.matrix[, c(1, 10)], type = "pearson") #P
rcorr(MeansTable.Other.matrix[, c(2, 11)], type = "pearson") #E
rcorr(MeansTable.Other.matrix[, c(3, 12)], type = "pearson") #R
rcorr(MeansTable.Other.matrix[, c(4, 13)], type = "pearson") #M
rcorr(MeansTable.Other.matrix[, c(5, 14)], type = "pearson") #A
rcorr(MeansTable.Other.matrix[, c(6, 15)], type = "pearson") #Health
rcorr(MeansTable.Other.matrix[, c(7, 16)], type = "pearson") #Mind
rcorr(MeansTable.Other.matrix[, c(8, 17)], type = "pearson") #Enviro
rcorr(MeansTable.Other.matrix[, c(9, 18)], type = "pearson") #Econ
rcorr(MeansTable.Other.matrix[, c(23, 27)], type = "pearson") #H
rcorr(MeansTable.Other.matrix[, c(24, 28)], type = "pearson") #SE
rcorr(MeansTable.Other.matrix[, c(25, 29)], type = "pearson") #Res
rcorr(MeansTable.Other.matrix[, c(26, 30)], type = "pearson") #Opti
rcorr(MeansTable.Other.matrix[, c(19, 21)], type = "pearson") #PERMA
rcorr(MeansTable.Other.matrix[, c(20, 22)], type = "pearson") #PFW
rcorr(MeansTable.Other.matrix[, c(31, 32)], type = "pearson") #PsyCap
```
#Table 3 - MTMM Matrix
```{r Reliability Diagonals Self-Self}
#Create Reliability Dataset
#Self-Reported
##PF-W
PFW_Alpha <- Scale.Final[, c(1:9, 23:31)]
alpha(PFW_Alpha)
##OADAPT
OADAPT_Alpha <- ScaleData[, c(38:40, 171:173)]
alpha(OADAPT_Alpha)
##OPRO
OPRO_Alpha <- ScaleData[, c(41:43, 174:176)]
alpha(OPRO_Alpha)
##OPROF
OPROF_Alpha <- ScaleData[, c(35:37, 168:170)]
alpha(OPROF_Alpha)
```
```{r Reliability Diagonals Co-Co}
#Create Reliability Dataset
#Self-Reported
##PF-W
PFW_Alpha.C <- Scale.Final[, c(12:20, 34:42)]
alpha(PFW_Alpha.C)
##OADAPT
OADAPT_Alpha.C <- ScaleData[, c(107:109, 240:242)]
alpha(OADAPT_Alpha.C)
##OPRO
OPRO_Alpha.C <- ScaleData[, c(110:112, 243:245)]
alpha(OPRO_Alpha.C)
##OPROF
OPROF_Alpha.C <- ScaleData[, c(237:239, 104:106)]
alpha(OPROF_Alpha.C)
```
```{r MonoMethod Block Self-Self}
THE.MASTER.matrix <- as.matrix(THE.MASTER)
#SelfReport
##PFW
rcorr(THE.MASTER.matrix[, c(2, 8)], type = "pearson")
rcorr(THE.MASTER.matrix[, c(2, 7)], type = "pearson")
rcorr(THE.MASTER.matrix[, c(2, 9)], type = "pearson")
##OADAPT
THE.MASTER.matrix <- as.matrix(THE.MASTER)
rcorr(THE.MASTER.matrix[, c(8, 7)], type = "pearson")
rcorr(THE.MASTER.matrix[, c(8, 9)], type = "pearson")
##OPRO
rcorr(THE.MASTER.matrix[, c(7, 9)], type = "pearson")
```
```{r MonoMethod Block Co-Co}
#Collateral Report
##PFW
rcorr(THE.MASTER.matrix[, c(4, 11)], type = "pearson")
rcorr(THE.MASTER.matrix[, c(4, 10)], type = "pearson")
rcorr(THE.MASTER.matrix[, c(4, 12)], type = "pearson")
##OADAPT
rcorr(THE.MASTER.matrix[, c(11, 10)], type = "pearson")
rcorr(THE.MASTER.matrix[, c(11, 12)], type = "pearson")
##OPRO
rcorr(THE.MASTER.matrix[, c(10, 12)], type = "pearson")
```
```{r Validity Diagonals}
THE.MASTER.matrix <- as.matrix(THE.MASTER)
##PFW
rcorr(THE.MASTER.matrix[, c(2, 4)], type = "pearson")
##OADAPT
rcorr(THE.MASTER.matrix[, c(8, 11)], type = "pearson")
##OPRO
rcorr(THE.MASTER.matrix[, c(7, 10)], type = "pearson")
##OPROF
rcorr(THE.MASTER.matrix[, c(9, 12)], type = "pearson")
```
```{r HeteroTrait HeteroMethod Triangle}
#PFW
rcorr(THE.MASTER.matrix[, c(4, 8)], type = "pearson")
rcorr(THE.MASTER.matrix[, c(4, 7)], type = "pearson")
rcorr(THE.MASTER.matrix[, c(4, 9)], type = "pearson")
##ODAPT
rcorr(THE.MASTER.matrix[, c(11, 2)], type = "pearson")
rcorr(THE.MASTER.matrix[, c(11,7)], type = "pearson")
rcorr(THE.MASTER.matrix[, c(11, 9)], type = "pearson")
##OPRO
rcorr(THE.MASTER.matrix[, c(10, 2)], type = "pearson")
rcorr(THE.MASTER.matrix[, c(10, 8)], type = "pearson")
rcorr(THE.MASTER.matrix[, c(10, 9)], type = "pearson")
##OPROF
rcorr(THE.MASTER.matrix[, c(12, 2)], type = "pearson")
rcorr(THE.MASTER.matrix[, c(12, 8)], type = "pearson")
rcorr(THE.MASTER.matrix[, c(12, 7)], type = "pearson")
```
#Table 4 - Self-Reported Predicting Work Outcomes
```{r Self-Reported Building Blocks (PERMA+4) Predicting Self-Reported and Collateral-Reported Work Role Performance}
attach(THE.MASTER)
#Self-Self Overall
Reg.PF.S <- lm(OADAPT.Self ~
PF.Self)
summary(Reg.PF.S)
confint.lm(Reg.PF.S)
#Self-Self Bias Correction
Adjusted <- THE.MASTER %>% filter(Accuracy.Self.NEW == "Accurate")
attach(Adjusted)
Reg.PF.AC <- lm(OPROF.Self ~
PF.Self)
summary(Reg.PF.AC)
confint.lm(Reg.PF.AC)
#Collateral-Report
attach(THE.MASTER)
Reg.PF.C <- lm(OADAPT.C ~
PF.Self)
summary(Reg.PF.C)
confint.lm(Reg.PF.C)
```
#Table 5 - Collateral-Reported Predicting Work Outcomes
```{r Regression for Self-Report Building Blocks and Work Outcomes, message=FALSE, warning=FALSE, include=FALSE}
attach(THE.MASTER)
#Co-Co Overall
Reg.PF.Co <- lm(OADAPT.C~
PF.C)
summary(Reg.PF.Co)
confint.lm(Reg.PF.Co)
#Co-Co Bias Correction
Adjusted.C <- THE.MASTER %>% filter(Accuracy.Co.NEW == "Accurate")
attach(Adjusted.C)
Reg.PF.C.AC <- lm(OPRO.C~
PF.C)
summary(Reg.PF.C.AC)
confint.lm(Reg.PF.C.AC)
#Co-Self Overall
attach(THE.MASTER)
Reg.PF.C.S <- lm(OADAPT.Self~
PF.C)
summary(Reg.PF.C.S)
confint.lm(Reg.PF.C.S)
```
#Psycap Paper
```{r PsyCap Paper, include=FALSE}
Scott <- mutate(ScaleData,
PsyCap.H.E1 = (Psy_H_1_EMP1 + Psy_H_2_EMP1)/2,
PsyCap.SE.E1 = (Psy_SE_1_EMP1 + Psy_SE_1_EMP1)/2,
PsyCap.R.E1 = (Psy_R_1_EMP1 + Psy_R_2_EMP1)/2,
PsyCap.O.E1 = (Psy_0_1_EMP1 + Psy_O_2_EMP1)/2,
PsyCap.H.E2C = (Psy_H_1_EMP2_C + Psy_H_2_EMP2_C)/2,
PsyCap.SE.E2C = (Psy_SE_1_EMP2_C + Psy_SE_1_EMP2_C)/2,
PsyCap.R.E2C = (Psy_R_1_EMP2_C + Psy_R_2_EMP2_C)/2,
PsyCap.O.E2C = (Psy_0_1_EMP2_C + Psy_O_2_EMP2_C)/2)
```
```{r Regression for PsyCap and Work Outcomes, message=FALSE, include=FALSE}
#Unadjusted
attach(BuildingBlocks)
Reg.PC <- lm(SWB.C ~
Hope.Self +
SE.Self +
Res.Self +
Opti.Self)
summary(Reg.PC)
confint.lm(Reg.PC)
PsyCap.Self)
#Adjusted for Bias
Adjusted <- BuildingBlocks %>% filter(Accuracy.Self.NEW == "Unlikely" &
Coworker.Error.NEW == "Unlikely" &
Admission.Error.NEW == "Unlikely")
attach(Adjusted)
Reg.PC <- lm(SWB.C ~
Hope.Self +
SE.Self +
Res.Self +
Opti.Self)
summary(Reg.PC)
confint.lm(Reg.PC)
PsyCap.Self)
```
|
4c940d62e76ce33b2b7546a91d40e30cf1b6cbc6
|
[
"R",
"RMarkdown"
] | 10
|
RMarkdown
|
SDonaldsonUSC/R-Code-Repository
|
f154021bfd295d5ee41ba38547f088d998cb69da
|
6fb3a4771417b106fe8db7f978b8a42f9a7e6541
|
refs/heads/master
|
<file_sep>package com.sorteberg.rcplugins;
import java.util.List;
import java.util.ArrayList;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class MessageProcessor {
// A pointer to the logger created
// in main class is used for logging purpose.
private BCLogger logger;
// The userStatusList contains a list containing
// information about all users logged on since last server restart.
private UserStatusList userStatusList;
private int slowdownLimit;
private int slowdownFactor;
private int slowdownShowCounter=0;
// Messages from the dataFile are stored in arrays, one for
// startup messages and one for recurring messages.
private List<String> startupMessages = new ArrayList<String>();
private List<String> recurringMessages = new ArrayList<String>();
// Pointers to the logger, the MessageNode from the JSON data object
// and the empty UserStatusList are received via the constructor.
public MessageProcessor(
BCLogger logger,
JSONArray messageArray,
UserStatusList userStatusList,
int slowdownLimit,
int slowdownFactor
) {
try{
this.logger = logger;
this.userStatusList = userStatusList;
this.slowdownLimit = slowdownLimit;
this.slowdownFactor = slowdownFactor;
// check all messages in the JSON and split them
// into the two message objects.
// Messages marked as not enabled are ignored.
for(int i = 0; i < messageArray.size(); i++)
{
JSONObject msg = (JSONObject)messageArray.get(i);
String msgType = (String)msg.get("type");
if(msgType.equals("startup") && (long)msg.get("enabled") == 1L){
startupMessages.add((String)msg.get("message"));
logger.log(3,"Startup message loaded: " + (String)msg.get("message"));
}
else if(msgType.equals("recurring") && (long)msg.get("enabled") == 1L){
recurringMessages.add((String)msg.get("message"));
logger.log(3,"Recurring message loaded: " + (String)msg.get("message"));
}
}
}
catch(Exception e){
logger.log(0,"MessageProcessor construction: FALSE. " + e.getMessage());
}
}
public boolean SendMessages()
{
try{
slowdownShowCounter++;
for (int i = 0 ; i < userStatusList.size(); i++) {
UserStatus userStatus = userStatusList.get(i);
if(userStatus != null)
{
if(userStatus.joined){
if(userStatus.modus == 0){
if(userStatus.nextMessage < startupMessages.size()){
userStatus.player.sendMessage(
startupMessages.get(
userStatus.nextMessage));
userStatus.nextMessage++;
logger.log(2,
"Sendt startup message "
+ userStatus.nextMessage
+ " to "
+ userStatus.player.getName());
}
else{
// All startup messages are sent.
// Reset nextMessage counter and flag for recurring messages.
userStatus.modus = 1;
userStatus.nextMessage = 0;
}
}
else{ //Modus == 1
if(userStatus.nextMessage < recurringMessages.size()){
if(userStatus.slowdownCounter < slowdownLimit
|| slowdownShowCounter == slowdownFactor){
userStatus.player.sendMessage(
recurringMessages.get(
userStatus.nextMessage));
logger.log(2,
"Sendt recurring message "
+ userStatus.nextMessage
+ " (" + recurringMessages.get(
userStatus.nextMessage) + ")"
+ " to "
+ userStatus.player.getName());
userStatus.nextMessage++;
}
}
else{
userStatus.slowdownCounter++;
userStatus.nextMessage = 0;
}
}
} //if(userStatus.joined)
else{
logger.log(2,userStatus.player.getName() + " is offline");
} //else (userStatus.joined)
} //if(userStatus != null)
}
if(slowdownShowCounter == slowdownFactor)
slowdownShowCounter=0;
return true;
}
catch(Exception e){
logger.log(0,"MessageProcessor construction: FALSE. " + e.getMessage());
return false;
}
}
}
<file_sep>package com.sorteberg.rcplugins;
import org.bukkit.plugin.java.JavaPlugin;
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
public class RCBroadcaster extends JavaPlugin{
private BCLogger logger = new BCLogger(1,getLogger());
private UserStatusList userStatusList = new UserStatusList(getLogger());
private MessageProcessor messageProcessor;
private BCScheduler bcScheduler;
@Override
public void onEnable() {
try{
boolean loadedOK = true;
//
// To run the broadcaster successfully, we need to load a valid data file:
//
//If the plugin's data folder don't exist, we have to create it.
BCDataFile BCDataFile = new BCDataFile(
logger,
getDataFolder());
if(!BCDataFile.dataFolderExist()){
BCDataFile.createDataFolder();
}
//If the data file don't exist, we have to create a new one with default content.
if(!BCDataFile.dataFileExist()){
if(BCDataFile.createDataFile() == true){
logger.log(1,"Data file not found. New, default file created.");
}
else{
logger.log(0,"Data file not found. Error creating new file in " + getDataFolder().getAbsolutePath());
loadedOK=false;
}
}
else{
getLogger().info("Data file found.");
}
JSONObject dataFile = BCDataFile.parseDataFile();
if(dataFile == null){
logger.log(0,"The data file is not received by the Plugin class.");
loadedOK=false;
}
//
// The scheduler needs a pointer to the Message processor.
// This must be created before the creation of the scheduler.
//
JSONObject settings = (JSONObject)dataFile.get("settings");
messageProcessor = new MessageProcessor(
logger,
(JSONArray) dataFile.get("messages"),
userStatusList,
(int)((long)settings.get("slowdown-count")),
(int)((long)settings.get("slowdown-factor"))
);
if(messageProcessor == null){
logger.log(0,"Error creating the Message Processor.");
loadedOK=false;
}
//
// If and when the data file is loaded successfully,
// we can create a BCScheduler to send messages regular to players.
//
if(loadedOK == true){
bcScheduler = new BCScheduler(
logger,
dataFile,
messageProcessor);
if(bcScheduler == null){
logger.log(1,"Error creating Scheduler.");
loadedOK=false;
}
}
//
// If all preparations went well, register necessary events
// and start the BCScheduler.
//
if(loadedOK == true){
getServer().getPluginManager().registerEvents(
new BCListener(userStatusList),
this);
bcScheduler.Schedule();
logger.log(1,"Broadcaster enabled successfully.");
}
else{
logger.log(0,"RC-Broadcaster is loaded, but will not run due to errors.");
}
}
catch (Exception e){
logger.log(0,"Error loading Plugin: " + e.getMessage());
}
}
@Override
public void onDisable() {
}
}
|
e842d9be63a1eea3b73a686fccaa94aa07de2704
|
[
"Java"
] | 2
|
Java
|
radline/RCBroadcaster
|
301e67aca35c93ba68a3186d1944d2485e0ba9c7
|
7b6f33e26d2c9a2fa82fc9b6dc8fcef1ef2d94f5
|
refs/heads/master
|
<file_sep>export const STORE_USER_KEY = 'mengmengliu.me.user';
export const USER_TOKEN_KEY = 'mengmengliu.me.user.token';
export const USER_INFO_KEY = 'mengmengliu.me.user.info';
export const QINIUURL = 'https://imgs.mengmengliu.me/';
export const QINIU_UPLOADURL = 'https://upload-z1.qiniup.com';
export const PATH_BEFORLOGIN = 'mengmengliu.me.user.path.before.login';
<file_sep>import store from 'store';
export const getStorage = key => store.get(key);
export const setStorage = (key, value) => store.set(key, value);
export const removeStorage = key => store.remove(key);
export const clearStorage = () => store.clearAll();
<file_sep>import React, { PureComponent, createContext } from 'react';
import Dialog from '@material-ui/core/Dialog';
import Slide from '@material-ui/core/Slide';
import { randomString } from '@/utils/common';
export const ModalContext = createContext();
function Transition(props) {
return <Slide direction="up" {...props} />;
}
export function modalProvider(WrappedComponent) {
return class ModalContextProvider extends PureComponent {
state = {
modals: [],
}
handleClose = (key) => {
const { modals = [] } = this.state;
modals.find(i => i.key === key).open = false;
this.setState({ modals: [...modals] });
};
destory = (key) => {
const { modals = [] } = this.state;
modals.splice(modals.findIndex(i => i.key === key), 1);
this.setState({ modals: [...modals] });
}
render() {
const { modals = [] } = this.state;
return (<ModalContext.Provider
value={{
modal: (C) => {
this.setState({
modals: [...modals, {
key: randomString(),
open: true,
C,
}],
});
},
}}
>
<WrappedComponent {...this.props} />
{modals.map(({ key, C, open }) =>
(<Dialog
key={key}
open={open}
keepMounted={false}
TransitionComponent={Transition}
onClose={() => this.handleClose(key)}
onExited={() => this.destory(key)}
aria-labelledby="form-dialog-title"
>
<C close={() => this.handleClose(key)} />
</Dialog>))}
</ModalContext.Provider>);
}
};
}
export function modalConsumer(WrappedComponent) {
return class ThemedComponent extends PureComponent {
render() {
return (
<ModalContext.Consumer>
{(value) => {
return (<WrappedComponent
{...this.props}
{...value}
/>);
}}
</ModalContext.Consumer>
);
}
};
}
@modalProvider
export default class Modal extends PureComponent {
render() {
return this.props.children;
}
}
<file_sep>import { ApolloClient, InMemoryCache } from 'apollo-boost';
import fetch from 'isomorphic-unfetch';
import { HttpLink } from 'apollo-link-http';
import { onError } from 'apollo-link-error';
import { withClientState } from 'apollo-link-state';
import { ApolloLink } from 'apollo-link';
import { Observable } from 'rxjs';
import Snackbar from '@/components/snackbar';
import { getStorage } from '@/utils/store';
import { STORE_USER_KEY } from '@/constants/base';
let apolloClient = null;
// Polyfill fetch() on the server (used by apollo-client)
if (!process.browser) {
global.fetch = fetch;
}
const cache = new InMemoryCache({
// 存缓解析器,实现列表目录到详情
cacheRedirects: {
Query: {
say: (_, { _id }, { getCacheKey }) => getCacheKey({ __typename: 'Say', _id }),
article: (_, { _id }, { getCacheKey }) => getCacheKey({ __typename: 'Article', _id }),
timetable: (_, { _id }, { getCacheKey }) => getCacheKey({ __typename: 'Timetable', _id }),
},
},
});
const request = async (operation) => {
const { token } = await getStorage(STORE_USER_KEY) || {};
operation.setContext({
headers: {
Authorization: `bearer ${token}`,
},
});
};
const requestLink = new ApolloLink((operation, forward) => new Observable((observer) => {
let handle;
Promise.resolve(operation)
.then(oper => request(oper))
.then(() => {
handle = forward(operation).subscribe({
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer),
});
})
.catch(observer.error.bind(observer));
return () => {
if (handle) handle.unsubscribe;
};
}));
function create(initialState) {
return new ApolloClient({
connectToDevTools: process.browser,
ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
// link: new HttpLink({
// uri: 'https://api.mengmengliu.me/graphql', // Server URL (must be absolute)
// credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
// }),
link: ApolloLink.from([
onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
// console.log('graphQLErrors');
// console.log(graphQLErrors);
Snackbar.error(graphQLErrors[0].message);
// throw new Error(graphQLErrors);
// sendToLoggingService(graphQLErrors);
// throw graphQLErrors[0];
}
if (networkError) {
Snackbar.error('网络连接失败');
console.log('logoutUser');
console.log(networkError);
// logoutUser();
}
}),
requestLink,
withClientState({
defaults: {
isConnected: true,
},
resolvers: {
Mutation: {
updateNetworkStatus: (_, { isConnected }, { cache }) => {
cache.writeData({ data: { isConnected } });
return null;
},
},
},
cache,
}),
new HttpLink({
uri: 'https://api.mengmengliu.me/graphql', // Server URL (must be absolute)
credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
}),
]),
cache: cache.restore(initialState || {}),
});
}
export default function initApollo(initialState) {
// Make sure to create a new client for every server-side request so that data
// isn't shared between connections (which would be bad)
if (!process.browser) {
return create(initialState);
}
// Reuse client on the client-side
if (!apolloClient) {
apolloClient = create(initialState);
}
return apolloClient;
}
<file_sep>import React, { PureComponent, Fragment } from 'react';
import { CREATE_TIMETABLE } from '@/graphql/timetable';
import { withStyles } from '@material-ui/core/styles';
import { connect } from 'react-redux';
import { Mutation } from 'react-apollo';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import IconButton from '@material-ui/core/IconButton';
import Router from 'next/router';
import Button from '@material-ui/core/Button';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Book from '@/view/book';
import { modalConsumer } from '@/hoc/widthModal';
import TimetableView from '@/view/timetable/result';
import pp from '@/hoc/pp';
import Layout from '@/components/layout';
const styles = theme => ({
root: {
maxWidth: 700,
margin: '0px auto 16px',
},
appbar: {
// borderRadius: 5,
},
submitButton: {
marginTop: 16,
margin: '0 auto',
display: 'block',
// padding: '16px 32px',
},
menuButton: {
marginLeft: -12,
marginRight: 20,
},
tip: {
fontSize: 10,
color: '#999',
marginBottom: 8,
},
});
@connect(({ book }) => ({ ...book }))
@withStyles(styles)
@modalConsumer
export default class Index extends PureComponent {
constructor(props) {
super(props);
this.state = {
times: this.props.times,
setting: this.props.setting,
};
}
onChange = (values) => {
console.log('values');
console.log(values);
this.setState({ times: values });
const { dispatch } = this.props;
dispatch({
type: 'book/save',
payload: {
times: values,
},
});
}
render() {
const { classes } = this.props;
return (
<Layout>
<Mutation mutation={CREATE_TIMETABLE}>
{(createTimetable, { loading, error, data = {} }) => {
const onSubmit = async () => {
const { times, setting } = this.state;
const input = {
...setting,
times: JSON.stringify(times),
};
try {
const { data } = await createTimetable({
variables: { input },
refetchQueries: ['TimetableList'],
});
const { modal } = this.props;
modal(pp(TimetableView, { timetable: data.item }));
// console.log('result');
// console.log(result);
// Router.push('/article');
} catch (err) {
console.log('err');
console.log(err);
// Snackbar.error('文章发');
}
};
return (
<Fragment>
<AppBar position="static" className={classes.appbar}>
<Toolbar>
<IconButton
className={classes.menuButton}
color="inherit"
aria-label="Menu"
onClick={() => {
Router.push('/timetable/create');
}}
>
<ArrowBackIcon />
</IconButton>
<Typography variant="title" color="inherit" className={classes.flex}>
Select available time
</Typography>
</Toolbar>
</AppBar>
<div className={classes.root}>
<div>
<CardContent>
<div className={classes.tip}>
Click to select the available time period
click and drag to select more than one at a time
</div>
<Book onChange={this.onChange} />
<Button
variant="contained"
color="primary"
className={classes.submitButton}
onClick={onSubmit}
>
I have chosen the time
</Button>
</CardContent>
</div>
</div>
</Fragment>
);
}}
</Mutation>
</Layout>
);
}
}
<file_sep>const express = require('express');
const next = require('next');
const LRUCache = require('lru-cache');
const { minify } = require('html-minifier');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dir: '.', dev });
const handle = app.getRequestHandler();
const port = dev ? 8000 : 3202;
// This is where we cache our rendered HTML pages
const ssrCache = new LRUCache({
max: 100,
maxAge: 1000 * 60 * 60 * 3, // 1分钟
});
app.prepare()
.then(() => {
const server = express();
// Use the `renderAndCache` utility defined below to serve pages
[
'/',
].map((i) => {
return server.get(i, (req, res) => {
renderAndCache(req, res, i, req.query);
});
});
server.use(express.static('public'));
server.get('*', (req, res) => {
return handle(req, res);
});
server.listen(port, (err) => {
if (err) throw err;
console.log(`> Ready on http://localhost:${port}`);
});
})
.catch((err) => {
ssrCache.reset();
console.log('server.js err');
console.log(err);
});
/*
* NB: make sure to modify this to take into account anything that should trigger
* an immediate page change (e.g a locale stored in req.session)
*/
function getCacheKey(req) {
const { path } = req.route;
switch (path) {
case '/': return path;
case '/news/detail': {
const { id } = req.query;
if (id) {
return `${path}?id=${id}`;
} else {
return req.url;
}
}
default: return req.url;
}
}
function renderAndCache(req, res, pagePath, queryParams) {
const key = getCacheKey(req);
// If we have a page in the cache, let's serve it
if (ssrCache.has(key)) {
console.log(`命中存缓: ${key}`);
res.send(ssrCache.get(key));
return;
}
// If not let's render the page into HTML
app.renderToHTML(req, res, pagePath, queryParams)
.then(html => minify(html, {
// 引号
removeAttributeQuotes: true,
// 注释
removeComments: true,
// 空格
collapseWhitespace: true,
// 压缩html里的css
minifyCSS: true,
// 压缩html里的js
minifyJS: true,
}))
.then((html) => {
if (html.indexOf('ERROR_0120_ERROR') === -1) {
console.log(`新建存缓: ${key}`);
ssrCache.set(key, html);
} else {
console.log('发现错误!!!!!!!!!!');
// const shpath = '/root/mengmengliu.me/auto_build.sh';
// console.log(`将运行自启动脚本:${shpath}`);
ssrCache.reset();
// RunCmd('sh', [shpath], (result) => {
// console.log(result);
// });
}
res.send(html);
// Let's cache this page
// ssrCache.set(key, html);
// res.send(html);
})
.catch((err) => {
ssrCache.reset();
app.renderError(err, req, res, pagePath, queryParams);
console.log('server.js err');
console.log(err);
});
}
// function RunCmd(cmd, args, cb) {
// const spawn = require('child_process').spawn;
// const child = spawn(cmd, args);
// let result = '';
// child.stdout.on('data', (data) => {
// result += data.toString();
// });
// child.stdout.on('end', () => {
// cb(result);
// });
// child.stderr.on('data', (data) => {
// console.log(`Error: \n${data}`);
// });
// child.on('exit', (code, signal) => {
// console.log(`Exit: ${code}`);
// });
// }
<file_sep>import React, { PureComponent, Fragment } from 'react';
import CreateAvailableTime from '@/view/availableTime/create';
import Layout from '@/components/layout';
export default class Index extends PureComponent {
render() {
return (
<Fragment>
<Layout>
<CreateAvailableTime />
</Layout>
</Fragment>
);
}
}
<file_sep>import React, { PureComponent, Fragment } from 'react';
import Button from '@material-ui/core/Button';
import Card from '@material-ui/core/Card';
import Link from 'next/link';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Typography from '@material-ui/core/Typography';
import { withStyles } from '@material-ui/core/styles';
import CircularProgress from '@material-ui/core/CircularProgress';
const styles = theme => ({
input: {
display: 'none',
},
card: {
maxWidth: 500,
margin: '50px auto',
},
media: {
height: 0,
paddingTop: '56.25%', // 16:9
},
button: {
// fontSize: 20,
marginBottom: 16,
background: 'rgba(22,200,200,0.03)',
},
progress: {
margin: theme.spacing.unit * 2,
},
});
@withStyles(styles)
export default class Index extends PureComponent {
render() {
const { classes } = this.props;
return (
<Fragment>
<Card className={classes.card}>
<CardMedia
className={classes.media}
image="/static/images/1.jpg"
title="Contemplative Reptile"
/>
<CardContent>
<Typography color="textSecondary">
loading...
</Typography>
<CircularProgress className={classes.progress} />
</CardContent>
</Card>
</Fragment>
);
}
}
<file_sep># 前端部分
### how to use
```
npm i
// 安装依赖
npm run start
// 开发环境运行
npm run build
// 编译
npm run deploy
// 推送到服务器
```
### 主要用到的开源技术框架
React,next,material-ui,redux,graphql,store
### 项目简述
本项目定义为简单快速的 ssr + spa 项目,用户打开页面速度快,页面间跳转无需加载,提高用户体验。以及使用一系列优秀的开源技术提高开发效率。
服务端渲染框架用的nextjs
ui框架用的material-ui
数据层使用redux以及基于appolo实现的graphql状态管理器
持久层使用store,忽略平台差异,将数据保存在本地
### 文件结构
```
/ 根目录
/pages 页面文件
/views 视图组件
/components ui组件
/hoc 高阶组件
/utils 工具方法
/static 静态资源,带有/static路径
/public 静态资源,挂载在根路由
/graphql ql相关
/constants 全局常量
```
### 核心业务组件
#### views/availableTime
设置可用时间
用于限制时间选择表的参数
输入用户操作
输出时间表参数,类似于:
```
{
days: 7, // 可选天数
startOfDay: 8, // 每日开始时间
endOfDay: 17, // 每日结束时间
timeRange: 60, // 时间颗粒大小
multi: true // 是否可以多选
}
```
#### views/book
选择时间详细信息
输入时间表参数
输出时间选择结果
### 用户登录
创建全局组件requireAuth,对所有页面进行检测(排除login/oauth页面),判断用户是否登录,如果尚未登录,则要求用户先登录。
登录逻辑由后端操控,url转跳至http://api.mengmengliu.me/oauth/outlook即可
```
if (router.pathname === '/login/oauth') {
return (
<Fragment>
{children}
</Fragment>
);
}
if (!user || !user.token) {
return (
<Fragment>
<div style={{ padding: 50 }}>
请先
<a href="http://api.mengmengliu.me/oauth/outlook">
登录
</a>
</div>
</Fragment>
);
}
```
创建login/oauth页面,用于接受登录成功返回的token,并触发redux中的登录逻辑
```
componentDidMount() {
const { dispatch, router } = this.props;
const { token } = router.query || {};
if (token) {
dispatch({
type: 'user/loginByOauth',
payload: { token },
});
}
}
```
### 可以实现的功能:
随机生成不重复的key,将key作为一个可查询条件
显示日程具体信息
创建成功预订成功发送邮件通知
显示用户邮箱和昵称
<file_sep>import React, { PureComponent, Fragment } from 'react';
import { CREATE_BOOK } from '@/graphql/book';
import { withStyles } from '@material-ui/core/styles';
import { connect } from 'react-redux';
import { Mutation } from 'react-apollo';
import { withRouter } from 'next/router';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import IconButton from '@material-ui/core/IconButton';
import Router from 'next/router';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import { modalConsumer } from '@/hoc/widthModal';
import Form from '@/view/availableTime/createBook';
import Layout from '@/components/layout';
const styles = theme => ({
root: {
maxWidth: 700,
margin: '0px auto 0px',
},
appbar: {
},
submitButton: {
marginTop: 16,
margin: '0 auto',
display: 'block',
},
menuButton: {
marginLeft: -12,
marginRight: 20,
},
tip: {
fontSize: 10,
color: '#999',
marginBottom: 8,
},
});
@connect(({ book }) => ({ ...book }))
@withStyles(styles)
@withRouter
@modalConsumer
export default class Index extends PureComponent {
constructor(props) {
super(props);
this.state = {
ibooktimes: this.props.ibooktimes,
};
}
render() {
const { classes } = this.props;
return (
<Layout>
<Mutation mutation={CREATE_BOOK}>
{(createBook, { loading, error, data = {} }) => {
const onSubmit = async (values) => {
const { ibooktimes, router } = this.props;
const input = {
...values,
timetable: router.query._id,
times: JSON.stringify(ibooktimes),
};
console.log(input);
try {
const { data } = await createBook({
variables: { input },
refetchQueries: ['TimetableList'],
});
const { modal } = this.props;
console.log('data');
console.log(data);
modal(() => (
<Card className={classes.card}>
<CardContent>
<Typography gutterBottom variant="headline" component="h2">
your meeting is booked!The confirmation email has been sent !
</Typography>
</CardContent>
</Card>
));
} catch (err) {
console.log('err');
console.log(err);
}
};
const { router } = this.props;
return (
<Fragment>
<AppBar position="static" className={classes.appbar}>
<Toolbar>
<IconButton
className={classes.menuButton}
color="inherit"
aria-label="Menu"
onClick={() => {
Router.push(`/timetable/detail?_id=${router.query._id}`);
}}
>
<ArrowBackIcon />
</IconButton>
<Typography variant="title" color="inherit" className={classes.flex}>
choose your availableTime
</Typography>
</Toolbar>
</AppBar>
<div className={classes.root}>
<CardContent>
<Form onSubmit={onSubmit} />
</CardContent>
</div>
</Fragment>
);
}}
</Mutation>
</Layout>
);
}
}
<file_sep>export function isWeixin() {
const ua = navigator.userAgent.toLowerCase();
if (ua.indexOf('micromessenger') !== -1) {
return true;
} else {
return false;
}
}
export function isServerSide() {
return typeof window === 'undefined' || typeof document === 'undefined';
}
export function isTel(Tel) {
const re = new RegExp(/^((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)$/);
const retu = Tel.match(re);
if (retu) {
return true;
} else {
return false;
}
}
export function getScrollTop() {
let scrollTop = 0;
if (document.documentElement && document.documentElement.scrollTop) {
scrollTop = document.documentElement.scrollTop;
} else if (document.body) {
scrollTop = document.body.scrollTop;
}
return scrollTop;
}
export function lessStr(str, end = 15, start = 0) {
if (str && str.length > end) {
return `${str.substring(start, end)}...`;
} else {
return str;
}
}
export const getSmallImg = (url, propsX, propsY) => {
const x = propsX || 200;
const y = propsY || 200;
return `${url}?imageMogr2/thumbnail/!${x}x${y}r/gravity/Center/crop/${x}x${y}`;
};
export function formatTime(tm, conf = 'YYYY年MM月DD日 HH:mm:ss 星期') {
const t = new Date(tm);
return conf
.replace(/YYYY/g, t.getFullYear())
.replace(/MM/g, t.getMonth() + 1)
.replace(/DD/g, t.getDate())
.replace(/HH/g, t.getHours())
.replace(/mm/g, (`0${t.getMinutes()}`).slice(-2))
.replace(/ss/g, t.getSeconds())
.replace(/星期/g, `星期${['日', '一', '二', '三', '四', '五', '六'][t.getDay()]}`);
}
export const randomString = (len = 32) => {
const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
/** **默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1*** */
const maxPos = $chars.length;
let pwd = '';
for (let i = 0; i < len; i += 1) {
pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
}
return pwd;
};
<file_sep>import React, { PureComponent, Fragment, createRef } from 'react';
import Button from '@material-ui/core/Button';
import Card from '@material-ui/core/Card';
import Link from 'next/link';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Typography from '@material-ui/core/Typography';
import { withStyles } from '@material-ui/core/styles';
import TextField from '@material-ui/core/TextField';
import Router from 'next/router';
import Layout from '@/components/layout';
const styles = theme => ({
input: {
display: 'none',
},
card: {
maxWidth: 500,
margin: '50px auto',
paddingBottom: 16,
},
media: {
height: 0,
paddingTop: '56.25%', // 16:9
},
button: {
// fontSize: 20,
// marginBottom: 16,
background: 'rgba(22,200,200,0.05)',
},
bootstrapRoot: {
padding: 0,
'label + &': {
marginTop: theme.spacing.unit * 3,
},
},
bootstrapInput: {
borderRadius: 4,
backgroundColor: theme.palette.common.white,
border: '1px solid #ced4da',
fontSize: 16,
padding: '10px 12px',
width: 'calc(100% - 24px)',
transition: theme.transitions.create(['border-color', 'box-shadow']),
fontFamily: [
'-apple-system',
'BlinkMacSystemFont',
'"Segoe UI"',
'Roboto',
'"Helvetica Neue"',
'Arial',
'sans-serif',
'"Apple Color Emoji"',
'"Segoe UI Emoji"',
'"Segoe UI Symbol"',
].join(','),
'&:focus': {
borderColor: '#80bdff',
boxShadow: '0 0 0 0.2rem rgba(0,123,255,.25)',
},
},
bootstrapFormLabel: {
fontSize: 18,
},
});
@withStyles(styles)
export default class Index extends PureComponent {
input = createRef()
render() {
const { classes } = this.props;
return (
<Layout>
<Fragment>
<CardContent>
<TextField
// defaultValue=""
label="Please enter the invitation code"
id="bootstrap-input"
InputProps={{
disableUnderline: true,
classes: {
root: classes.bootstrapRoot,
input: classes.bootstrapInput,
},
inputRef: (c) => { this.input = c; },
}}
InputLabelProps={{
shrink: true,
className: classes.bootstrapFormLabel,
}}
style={{ width: '100%' }}
/>
</CardContent>
<CardActions>
<Button
onClick={() => {
console.log(this.input.value);
Router.push(`/timetable/detail?_id=${this.input.value}`);
}}
raised
className={classes.button}
size="large"
color="primary"
>
book meeting
</Button>
</CardActions>
</Fragment>
</Layout>
);
}
}
<file_sep>export const fetchMore = (data) => {
return data.fetchMore({
variables: {
skip: data.list.length,
},
updateQuery: (previousResult, { fetchMoreResult }) => {
if (!fetchMoreResult) {
return previousResult;
}
return {
...fetchMoreResult,
list: [
...previousResult.list,
...fetchMoreResult.list,
],
};
},
});
};
export const updateQuery = (previousResult, { fetchMoreResult }) => {
if (!fetchMoreResult) {
return previousResult;
}
return {
...fetchMoreResult,
list: [
...previousResult.list,
...fetchMoreResult.list,
],
};
};
<file_sep>import axios from 'axios';
import es6promise from 'es6-promise';
// import { API_URL } from '@/constants/api';
import { getStorage } from './store';
es6promise.polyfill();
const instance = axios.create({
baseURL: 'https://api.mengmengliu.me',
method: 'POST',
timeout: 6000,
});
instance.defaults.retry = 4;
instance.defaults.retryDelay = 6000;
instance.interceptors.response.use(undefined, (err) => {
const { config } = err;
if (!config || !config.retry) return Promise.reject(err);
config.__retryCount = config.__retryCount || 0;
if (config.__retryCount >= config.retry) {
return Promise.reject(err);
}
config.__retryCount += 1;
const backoff = new Promise(((resolve) => {
setTimeout(() => { resolve(); }, config.retryDelay || 1);
}));
return backoff.then(() => { return axios(config); });
});
export default (url, data, options) => {
const token = getStorage('mengmengliu.me.token');
return instance({
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
// Authorization: `bearer ${token}`,
},
url,
data: { token, ...data },
...options,
})
.then((response) => {
return response.data;
});
// .catch((err) => {
// console.log('request请求服务器出错');
// console.log(err);
// });
};
<file_sep>import React, { PureComponent, Fragment } from 'react';
import { Query } from 'react-apollo';
import { connect } from 'react-redux';
import { withStyles } from '@material-ui/core/styles';
import { USERINFO } from '@/graphql/user';
import Avatar from '@material-ui/core/Avatar';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import ButtonBase from '@material-ui/core/ButtonBase';
import { withRouter } from 'next/router';
import { clearStorage } from '@/utils/store';
import { modalConsumer } from '@/hoc/widthModal';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
const styles = theme => ({
root: {
padding: 16,
color: '#fff',
display: 'flex',
background: 'rgba(0,0,0,0.5)',
},
avatar: {
width: 60,
height: 60,
marginRight: 16,
border: '2px #fff solid',
},
p: {
color: '#fff',
margin: 0,
},
logout: {
fontSize: 12,
color: '#fff',
border: '1px rgba(255,255,255,0.5) solid',
lineHeight: '14px',
marginLeft: 16,
},
});
@connect(({ book }) => ({ book }))
@withStyles(styles)
@withRouter
@modalConsumer
export default class ArticleDetail extends PureComponent {
render() {
const { classes, router, modal } = this.props;
const showModal = () => modal(({ close }) => (
<Fragment>
<DialogTitle id="alert-dialog-title">
do you want to login out?
</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
You need to login again to continue after exiting
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={close} color="primary">
cancell
</Button>
<Button
onClick={() => {
close();
clearStorage();
window.location.href = '/';
}}
color="primary"
autoFocus
>
log out
</Button>
</DialogActions>
</Fragment>
));
return (
<Query query={USERINFO}>
{({ loading, error, data = {} }) => {
const { user = {} } = data;
// console.log('user');
// console.log(user);
if (loading) return 'Loading...';
if (error) return `Error! ${error.message}`;
return (
<Fragment>
<div className={classes.root}>
<ButtonBase>
<Avatar onClick={() => { router.push('/me'); }} className={classes.avatar} src="/static/images/avatar.jpeg" />
</ButtonBase>
<div>
<Typography className={classes.p} variant="title" gutterBottom>
{user && user.nickname}
<Button
onClick={() => { router.push('/'); }}
className={classes.logout}
variant="outlined"
component="span"
>
Home
</Button>
<Button
onClick={showModal}
className={classes.logout}
variant="outlined"
component="span"
>
logout
</Button>
</Typography>
<Typography className={classes.p} variant="Subheading" gutterBottom>
{user && user.username}
</Typography>
</div>
</div>
</Fragment>
);
}}
</Query>
);
}
}
<file_sep>import React, { PureComponent } from 'react';
import Dialog from '@material-ui/core/Dialog';
import Slide from '@material-ui/core/Slide';
import styleRoot from '@/hoc/styleRoot';
import reduxRoot from '@/hoc/reduxRoot';
import { domRender } from '@/utils/react';
function Transition(props) {
return <Slide direction="up" {...props} />;
}
export default function (WrappedComponent) {
@domRender
@reduxRoot
@styleRoot
class Modal extends PureComponent {
state = {
open: true,
};
handleClose = () => {
this.setState({ open: false });
console.log('this.props');
console.log(this.props);
const { onClose } = this.props;
if (onClose) onClose();
};
render() {
const { destory } = this.props;
return (
<div>
<Dialog
open={this.state.open}
keepMounted={false}
transition={Transition}
onClose={this.handleClose}
onExited={() => { if (destory) destory(); }}
aria-labelledby="form-dialog-title"
>
<WrappedComponent close={this.handleClose} />
</Dialog>
</div>
);
}
}
return Modal;
}
<file_sep>import Container from './container';
const snackbar = Object.assign(
(text, option) => Container({ message: text, ...option }),
{
error: (text, option) => Container({ message: text, type: 'error', ...option }),
success: (text, option) => Container({ message: text, type: 'success', ...option }),
info: (text, option) => Container({ message: text, type: 'info', ...option }),
warn: (text, option) => Container({ message: text, type: 'warn', ...option }),
},
);
export default snackbar;
<file_sep>
# scp -r /Users/liumin/Desktop/Dva/Admin.HuarenLife/dist root@192.168.127.12:/root/huarenShenghuo
# DATA=$(date +%y%m%d)
SERVER="root@172.16.31.10"
DIR="/root/mengmengliu.me/.next"
LOCAL_DIR=".next"
# FILELIST=$(git diff --name-only HEAD~ HEAD)
# for i in ${FILELIST}
# do
# scp -r $(pwd)/${i} ${SERVER}:${DIR}
# done
echo '本地路径:'
echo $(pwd)/${LOCAL_DIR}
echo $(pwd)
# TEMP=`find $(pwd) \( -path $(pwd)/node_modules -o -path $(pwd)/.next -o -path $(pwd)/.git \) -prune -o -maxdepth 1 -mindepth 1 -name "*" -print`
# TEMP=`find $(pwd) -name "*" -path $(pwd)/node_modules -prune -o -maxdepth 1 -print`
# TEMP=`find $(pwd)/* -path $(pwd)/node_modules -prune -o -maxdepth 0 -print`
# echo ${TEMP}
echo '远程路径:'
echo ${DIR}
# echo '开始推送文件到国内服务器'
# scp -r ${TEMP} root@172.16.17.32:${DIR}
echo '开始推送文件到坚挺号服务器'
scp -r $(pwd)/${LOCAL_DIR} ${SERVER}:${DIR}
echo '传输完毕,cool~~~'
<file_sep>import gql from 'graphql-tag';
export const TIMETABLE_DETAIL = gql`
query TimetableDetail($_id: String!) {
timetable: timetable(_id: $_id) {
__typename
_id
title
cover
description
startOfDay
endOfDay
startOfHour
endOfHour
timeRange
multi
times
createdAt
user {
nickname
}
}
}
`;
export const TIMETABLE_LIST = gql`
query TimetableList($first: Int!, $skip: Int!) {
list: timetables(first: $first, skip: $skip) {
__typename
_id
title
createdAt
}
meta: _timetablesMeta {
count
}
}
`;
export const CREATE_TIMETABLE = gql`
mutation ($input: TimetableInput) {
item: createTimetable(input: $input) {
__typename
_id
title
}
}
`;
export const DELETE_TIMETABLE = gql`
mutation ($id: String!) {
item: deleteTimetable(id: $id) {
__typename
}
}
`;
<file_sep>import gql from 'graphql-tag';
export const USER_LOGIN = gql`
mutation userLogin($username: String!, $password: String!) {
result: userLogin(username: $username, password: $password) {
status
message
token
userInfo {
_id
nickname
avatarUrl
}
}
}
`;
export const USERINFO = gql`
query user {
user: user {
__typename
_id
nickname
username
}
}
`;
<file_sep>import React, { PureComponent } from 'react';
import { isServerSide } from '@/utils/common';
// import Loading from '@/components/loading';
import CircularProgress from '@material-ui/core/CircularProgress';
export default (WrappedComponent) => {
return class NossrComponent extends PureComponent {
state = {
show: false,
skip: false,
}
componentDidMount() {
this.change();
}
change = () => {
if (!this.state.skip && !isServerSide()) {
this.setState({ show: true, skip: true });
}
}
render() {
const { ...other } = this.props;
if (!this.state.show) {
return 'loading';
}
return (
<WrappedComponent {...other} />
);
}
};
};
<file_sep>import React, { PureComponent, Fragment } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'next/router';
@connect(({ user }) => ({ user }))
@withRouter
export default class Index extends PureComponent {
componentDidMount() {
const { dispatch, router } = this.props;
const { token } = router.query || {};
if (token) {
dispatch({
type: 'user/loginByOauth',
payload: { token },
});
}
}
render() {
return (
<Fragment>
Successful user login
</Fragment>
);
}
}
<file_sep>PRO_DIR="../mengmengliu.me"
GIT_URL="https://github.com/liumin1128/mengmengliu.me.git"
pwd
# echo "切换到Node 版本:8.8.1"
# source ~/.nvm/nvm.sh
# nvm use 8.8.1
# echo "Node 版本:"
# node -v
# echo "关闭pm2"
# pm2 delete mengmengliu.me
echo "进入项目目录"
pwd
cd $PRO_DIR
pwd
echo "从 $PATH_OLD 切换到 $PATH_NEW"
echo "正在从git同步代码"
# output1=`git fetch --all && git reset --hard origin/master && git pull`
# echo $output1
git fetch --all
git reset --hard origin/v3
git pull
# echo "正在下载依赖"
# yarn
# echo "正在编译"
# yarn build
echo "重启pm2"
yarn pm2
pm2 ls
echo "项目已更新!"
<file_sep>import React, { PureComponent, Fragment } from 'react';
import { Query, Mutation } from 'react-apollo';
import { connect } from 'react-redux';
import moment from 'moment';
import { BOOK_LIST, DELETE_BOOK } from '@/graphql/book';
import { withStyles } from '@material-ui/core/styles';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import Avatar from '@material-ui/core/Avatar';
import ImageIcon from '@material-ui/icons/Image';
import Button from '@material-ui/core/Button';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import { modalConsumer } from '@/hoc/widthModal';
const styles = theme => ({
root: {
maxWidth: 700,
margin: '92px auto 32px',
},
submitButton: {
marginTop: 16,
margin: '0 auto',
display: 'block',
padding: '16px 32px',
},
});
@connect(({ book }) => ({ book }))
@withStyles(styles)
@modalConsumer
export default class BookList extends PureComponent {
render() {
const { modal } = this.props;
return (
<Query query={BOOK_LIST} variables={{ skip: 0, first: 999 }}>
{({ loading, error, data = {} }) => {
const { list } = data;
// console.log('list');
// console.log(list);
if (loading) return 'Loading...';
if (error) return `Error! ${error.message}`;
return (
<Mutation mutation={DELETE_BOOK}>
{(deleteBook, { loading, error }) => {
const onDelete = async (id) => {
const result = await deleteBook({ variables: { id }, refetchQueries: ['BookList'] });
console.log('result');
console.log(result);
};
const showModal = id => modal(({ close }) => (
<Fragment>
<DialogTitle id="alert-dialog-title">
do you want to cancel this booking?
</DialogTitle>
<DialogContent>
<DialogContentText id="alert-dialog-description">
delete
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={close} color="primary">
cancel
</Button>
<Button
onClick={() => {
onDelete(id);
close();
}}
color="primary"
autoFocus
>
delete booking
</Button>
</DialogActions>
</Fragment>
));
return (
<Fragment>
<List>
{
list.map(i => (
<ListItem onClick={() => showModal(i._id)}>
<Avatar>
<ImageIcon />
</Avatar>
<ListItemText
primary={`i booked the meeting:${i.timetable ? i.timetable.title : 'the meeting has been cancelled'}`}
secondary={moment(i.createdAt).format('llll')}
/>
</ListItem>
))
}
</List>
</Fragment>
);
}}
</Mutation>
);
}}
</Query>
);
}
}
<file_sep>import React, { PureComponent, Fragment } from 'react';
import { connect } from 'react-redux';
import moment from 'moment';
import ButtonBase from '@material-ui/core/ButtonBase';
import { withStyles } from '@material-ui/core/styles';
/* eslint-disable no-case-declarations */
const styles = theme => ({
container: {
maxWidth: 1000,
margin: '0 auto',
// border: '1px red solid',
},
day: {
// width: `${100 / 15}%`,
display: 'inline-block',
textAlign: 'center',
// padding: 2,
maxWidth: 100,
},
dayTitle: {
color: '#666',
padding: '16px 0',
fontWeight: 700,
// background: 'rgba(0,0,0,0.05)',
borderBottom: '2px rgba(0,0,0,0.1) dashed',
marginBottom: 16,
},
item: {
display: 'inline-block',
// width: `${100 / 7}%`,
// border: '1px red solid',
padding: '8px 0',
height: 60,
fontWeight: 400,
// background: 'green',
// transition: '1s',
// background: '#f1f1f1',
// margin: 2,
// borderRadius: 2,
fontSize: 10,
color: '#999',
whiteSpace: 'nowrap',
overflow: 'hidden',
'&:hover': {
boxShadow: '0 0 0px 1px #d500f9',
zIndex: 1,
boxSizing: 'border-box',
// background: '#f2f2f2',
},
},
active: {
background: '#00B9F7',
// transition: 'none',
color: '#fff',
},
ripple: {
background: '#00B9F7',
},
});
@connect(({ book }) => ({ ...book }))
@withStyles(styles)
export default class Index extends PureComponent {
constructor(props) {
super(props);
this.state = {
values: this.props.times || {},
};
}
onSelect = ({ day, start, end, idx, active }) => {
// const { days } = this.state;
// const idx = days.findIndex(i => i.key === key);
// days[idx].active = !days[idx].active;
// this.setState({
// days: [...days],
// });
console.log(day, idx, active);
const { values } = this.state;
if (active) {
const index = values[day].findIndex(i => i === idx);
values[day].splice(index, 1);
if (values[day].length === 0) delete values[day];
} else {
if (!values[day]) {
values[day] = [];
}
const index = values[day].findIndex(i => i > idx);
// console.log(index);
if (index === -1) {
values[day].push(idx);
} else {
values[day].splice(index, 0, idx);
}
}
this.setValue({ ...values });
}
onMutiSelectStart = (x, y) => {
// 获取多选开始坐标并记录
// console.log(x, y);
this.setState({
xyTemp: { x, y },
});
}
onMutiSelectEnd = (_x, _y) => {
// 获取多选开始坐标)
const { xyTemp: { x, y } } = this.state;
// console.log(x, y);
// 如果检测到开始坐标与结束坐标一致,则该事件已在点击事件中处理,这边忽略即可
if (x === _x && y === _y) return;
// 由于不知道用户选择的方向性,故默认较将小的作为开始点
let x0;
let y0;
let x1;
let y1;
if (x < _x) {
x0 = x;
x1 = _x;
} else {
x0 = _x;
x1 = x;
}
if (y < _y) {
y0 = y;
y1 = _y;
} else {
y0 = _y;
y1 = y;
}
// 至此得到了矩形左上角 => 右下角的两个坐标
console.log(x0, y0, x1, y1);
const { values } = this.state;
// 在一个二维循环中对数值进行操作
for (let i = 0; i <= x1 - x0; i += 1) {
const startX = moment().add(x0 + i, 'days').startOf('day').format('YYYY-MM-DD');
for (let j = 0; j <= y1 - y0; j += 1) {
// values[startX].push();
if (!values[startX]) values[startX] = [];
const isSelected = values[startX].findIndex(d => d === y0 + j);
if (isSelected === -1) {
// console.log(index);
const value = y0 + j;
const index = values[startX].findIndex(d => d > value);
if (index === -1) {
values[startX].push(value);
} else {
values[startX].splice(index, 0, value);
}
values[startX].push();
}
}
}
// 保存数据并清空开始坐标
this.setState({
xyTemp: {},
});
this.setValue({ ...values });
}
setValue = (values) => {
this.setState({ values });
const { onChange } = this.props;
if (onChange) {
onChange(values);
}
}
render() {
const { type, values } = this.state;
const { classes, setting = {} } = this.props;
// console.log('setting');
// console.log(setting);
const { startOfHour, endOfHour, startOfDay, endOfDay, timeRange, title } = setting;
// const startOfDayOfYear = moment(startOfDay).dayOfYear()
// const endOfDayOfYear = moment(endOfDay).dayOfYear()
// const yearCha = moment(endOfDay) - moment(startOfDay)
const _days = (moment(endOfDay) - moment(startOfDay)) / (1000 * 60 * 60 * 24) + 1;
// console.log('_days');
// console.log(_days);
// console.log(_days);
const days = new Array(_days)
.fill('x')
.map((i, index) => index);
return (
<Fragment>
{
// <Typography variant="title" gutterBottom>
// 活动:
// {title}
// </Typography>
// <Typography variant="subheading" gutterBottom>
// 点击选择可用时间段,可以按住拖动来一次选择多个哦~
// </Typography>
}
{
// JSON.stringify(values, 0, 2)
}
{(() => {
switch (type) {
case 'day':
return (
<div className={classes.container}>
{
days.map(i => (
<ButtonBase
className={classes.item + (i.active ? ` ${classes.active}` : '')}
onClick={() => {
this.onSelect(i.key);
}}
TouchRippleProps={{
classes: {
child: classes.ripple,
},
}}
>
{i.label}
</ButtonBase>
))
}
</div>
);
default:
const temp = [];
// 最小时间颗粒
const interval = timeRange * 60;
// 填充最小时间颗粒
for (let i = 0; i < 60 * 24 / timeRange; i += 1) {
// 最小时间颗粒的起始值
const start = i * interval;
// 最小时间颗粒的结束值
const end = start + interval;
if (start >= startOfHour * 60 * 60 && end <= (endOfHour + 1) * 60 * 60) {
// 如果时间点在可选范围以外,则不填充
temp.push({
idx: i,
// 显示字符
label: i,
start,
end,
});
}
}
return (
<div className={classes.container}>
{
days.map((i, dayIndex) => (
<div
style={{
// width: 100
width: `${100 / _days}%`,
}}
className={classes.day}
>
<div className={classes.dayTitle}>
{moment(startOfDay).add(i, 'days').format('DD ddd')}
</div>
{temp.map((j, timeIndex) => {
// console.log(values);
const dayX = moment().add(dayIndex, 'days').startOf('day').format('YYYY-MM-DD');
const valueList = values[dayX] || [];
// console.log(valueList);
const active = valueList.findIndex((v) => { return j.idx === v; }) !== -1;
return (
<ButtonBase
className={classes.item + (active ? ` ${classes.active}` : '')}
onClick={() => {
this.onSelect({ day: dayX, start: j.start, end: j.end, idx: j.idx, active });
}}
style={{ width: '100%', height: 32 }}
TouchRippleProps={{
classes: {
child: classes.ripple,
},
}}
onMouseDown={() => {
// console.log(dayIndex, j.idx);
this.onMutiSelectStart(dayIndex, j.idx);
}}
onMouseUp={() => {
// console.log(dayIndex, j.idx);
this.onMutiSelectEnd(dayIndex, j.idx);
}}
>
{
moment()
.startOf('day')
.second(j.start)
.format('hh:mm a')
}
</ButtonBase>
);
})}
</div>
))
}
</div>
);
}
})()}
</Fragment>
);
}
}
<file_sep>import React, { PureComponent, Fragment } from 'react';
import Card from '@material-ui/core/Card';
import CardMedia from '@material-ui/core/CardMedia';
import { withStyles } from '@material-ui/core/styles';
import UserInfo from '@/view/me/info';
const styles = theme => ({
input: {
display: 'none',
},
card: {
maxWidth: 700,
margin: '50px auto',
paddingBottom: 16,
[theme.breakpoints.down('xs')]: {
margin: 'auto',
},
},
media: {
height: 0,
paddingTop: '45%', // 16:9
},
box: {
position: 'relative',
},
info: {
position: 'absolute',
bottom: 0,
color: '#fff',
},
button: {
background: 'rgba(22,200,200,0.05)',
},
});
@withStyles(styles)
export default class Index extends PureComponent {
render() {
const { classes, children, noAuth } = this.props;
return (
<Fragment>
<Card className={classes.card}>
<div className={classes.box}>
<CardMedia
className={classes.media}
image="/static/images/1.jpg"
title="Contemplative Reptile"
/>
{!noAuth && (
<div className={classes.info}>
<UserInfo />
</div>
)}
</div>
{children}
</Card>
</Fragment>
);
}
}
<file_sep>const defaultReducers = {
save: (state = {}, action) => {
return {
...state,
...action.payload,
};
},
clear: () => {
return {};
},
default: (state = {}) => {
return state;
},
};
export function reducerCreator(options) {
const { namespace = options, props = {}, initState = {} } = options;
return (state = initState, action) => {
const reducers = { ...defaultReducers, ...props };
const key = Object.keys(reducers).find((i) => {
return `${namespace}/${i}` === action.type;
}) || 'default';
return reducers[key](state, action);
};
}
export function reducerFactory(arr) {
const temp = {};
arr.map((i) => {
if (typeof i === 'string') {
temp[i] = reducerCreator(i);
} else if (typeof i === 'object') {
temp[i.namespace] = reducerCreator(i);
}
return i;
});
return temp;
}
<file_sep>import { createMuiTheme } from '@material-ui/core/styles';
import blue from '@material-ui/core/colors/blue';
import red from '@material-ui/core/colors/red';
import Color from 'color';
// import 'typeface-roboto';
const theme = createMuiTheme();
export default createMuiTheme({
overrides: {
MuiAppBar: {
root: {
background: `linear-gradient(60deg, ${Color('#2196f3').lighten(0.1)}, ${Color('#2196f3').darken(0.1)})`,
boxShadow: `0 4px 20px 0px ${Color('#2196f3').alpha(0.3)}, 0 7px 10px -5px ${Color('#2196f3').alpha(0.5)}`,
},
},
MuiInputLabel: {
formControl: {
color: '#9197a3',
},
},
MuiInput: {
underline: {
'&::before': {
borderBottom: '1px #ddd solid',
},
},
},
MuiPaper: {
elevation1: {
boxShadow: '0 3px 5px 0px rgba(0, 0, 0, 0.05)',
},
elevation2: {
boxShadow: '0 3px 5px 0px rgba(0, 0, 0, 0.05)',
borderRadius: 4,
// marginBottom: theme.spacing.unit * 2,
[theme.breakpoints.down('xs')]: {
// boxShadow: '0 1px 2px 1px rgba(0, 0, 0, 0.05)',
// boxShadow: '0 1px 3px 0px rgba(0, 0, 0, 0.05)',
// marginBottom: theme.spacing.unit * 1,
boxShadow: 'none',
},
},
},
// MuiButton: {
// outlined: {
// borderRadius: 0,
// border: '1px #015978 solid',
// },
// },
},
palette: {
primary: {
main: '#00B9F7',
contrastText: '#fff',
},
secondary: red,
background: {
default: '#f3f4f7',
},
},
typography: {
htmlFontSize: '14px',
fontFamily: [
'PingFang SC',
'Roboto',
'Microsoft Yahei',
'sans-serif',
].join(','),
// 'PingFang SC,sans-serif',
// fontWeightLight: 200,
// fontWeightRegular: 300,
// fontWeightMedium: 400,
},
nowrap: {
whiteSpace: 'nowrap',
textOverflow: 'ellipsis',
overflow: 'hidden',
},
centerBlock: {
display: 'block',
margin: '0 auto',
},
container: {
maxWidth: 1110,
width: '100%',
margin: 'auto',
[theme.breakpoints.down('md')]: {
paddingLeft: 16,
paddingRight: 16,
},
},
});
<file_sep>import React, { PureComponent, Fragment } from 'react';
import { CopyToClipboard } from 'react-copy-to-clipboard';
import { withStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import CardActions from '@material-ui/core/CardActions';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import Snackbar from '@/components/snackbar';
const styles = theme => ({
});
@withStyles(styles)
export default class Index extends PureComponent {
render() {
const { classes, timetable } = this.props;
const url = `https://www.mengmengliu.me/timetable/detail?_id=${timetable._id}`;
return (
<Card className={classes.card}>
<CardContent>
<Typography gutterBottom variant="headline" component="h2">
Successful realease!
</Typography>
<Typography component="p">
Your schedule[
{timetable.title}
】 has been created successfully! Please share the following address with your friends:
</Typography>
<Typography component="p">
<pre style={{ padding: 16, background: 'rgba(0,0,0,0.05)' }} href="https://www.mengmengliu.me">
{url}
</pre>
</Typography>
<p />
</CardContent>
<CardActions>
<CopyToClipboard
text={url}
onCopy={() => {
Snackbar.success('Copied to clipboard !!');
}}
>
<Button
size="small"
color="primary"
>
Copy to clipboard
</Button>
</CopyToClipboard>
<Button
size="small"
color="primary"
onClick={() => {
window.location.href = url;
}}
>
View the booking information
</Button>
</CardActions>
</Card>
);
}
}
<file_sep>import React, { PureComponent } from 'react';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Snackbar from '@material-ui/core/Snackbar';
const styles = theme => ({
root: {
// background: 'red',
// height: 36,
},
close: {
width: theme.spacing.unit * 4,
height: theme.spacing.unit * 4,
},
});
@withStyles(styles)
export default class MySnackbar extends PureComponent {
state = {
open: true,
};
componentWillUnmount() {
// setTimeout(() => {
// this.props.removeChild();
// }, 2000);
}
handleExited = () => {
this.props.removeChild();
}
handleClose = (event, reason) => {
if (reason === 'clickaway') {
return;
}
this.setState({ open: false });
// setTimeout(() => {
// this.props.removeChild();
// }, 2000);
};
render() {
const {
classes,
message = 'OK',
actionText = 'OK',
} = this.props;
const action = [<Button
key="undo"
color="inherit"
dense="true"
onClick={this.handleClose}
>
{actionText}
</Button>];
return (
<Snackbar
anchorOrigin={{
vertical: 'bottom',
horizontal: 'left',
}}
open={this.state.open}
autoHideDuration={2000}
onClose={this.handleClose}
onExited={this.handleExited}
// SnackbarContentProps={{
// className: classes.root,
// 'aria-describedby': 'message-id',
// }}
snackbarcontentprops={{
className: classes.root,
'aria-describedby': 'message-id',
}}
message={message}
action={action}
/>
);
}
}
<file_sep>import React, { PureComponent, Fragment } from 'react';
import { Query } from 'react-apollo';
import { connect } from 'react-redux';
import Router from 'next/router';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import IconButton from '@material-ui/core/IconButton';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import { TIMETABLE_DETAIL } from '@/graphql/timetable';
import { withStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import Button from '@material-ui/core/Button';
import Book from '../book/book';
const styles = theme => ({
root: {
maxWidth: 700,
margin: '0px auto 0px',
},
submitButton: {
marginTop: 16,
margin: '0 auto',
display: 'block',
padding: '16px 32px',
},
});
@connect(({ book }) => ({ book }))
@withStyles(styles)
export default class ArticleDetail extends PureComponent {
render() {
const _id = this.props.query._id;
const { classes, book = {} } = this.props;
const { ibooktimes = {} } = book;
const buttonActive = Object.keys(ibooktimes).length > 0;
return (
<Query query={TIMETABLE_DETAIL} variables={{ _id }}>
{({ loading, error, data = {} }) => {
const { timetable = {} } = data;
console.log('timetable');
console.log(timetable);
if (loading) return 'Loading...';
if (error) return `Error! ${error.message}`;
return (
<Fragment>
<AppBar position="static" className={classes.appbar}>
<Toolbar>
<IconButton
className={classes.menuButton}
color="inherit"
aria-label="Menu"
onClick={() => {
Router.push('/timetable/create');
}}
>
<ArrowBackIcon />
</IconButton>
<Typography variant="title" color="inherit" className={classes.flex}>
{timetable.title}
</Typography>
</Toolbar>
</AppBar>
<div className={classes.root}>
<div>
<CardContent>
<Typography variant="title" color="inherit" className={classes.flex}>
meeting title:
{timetable.title}
</Typography>
<br />
<Typography variant="subheading" gutterBottom>
introduction:
{timetable.description}
</Typography>
<Typography variant="subheading" gutterBottom>
time:
{`${timetable.startOfDay} ~ ${timetable.endOfDay}`}
</Typography>
<Book
onChange={(value) => {
const { dispatch } = this.props;
dispatch({
type: 'book/save',
payload: {
ibooktimes: value,
},
});
}}
setting={timetable}
/>
<Button
variant="contained"
color="primary"
className={classes.submitButton}
disabled={!buttonActive}
onClick={() => {
Router.push(`/timetable/book?_id=${_id}`);
}}
>
submit
</Button>
</CardContent>
</div>
</div>
</Fragment>
);
}}
</Query>
);
}
}
<file_sep>import React, { PureComponent, Fragment } from 'react';
import Button from '@material-ui/core/Button';
import Card from '@material-ui/core/Card';
import Link from 'next/link';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import Typography from '@material-ui/core/Typography';
import { withStyles } from '@material-ui/core/styles';
import Me from '@/view/me';
import Layout from '@/components/layout';
const styles = theme => ({
input: {
display: 'none',
},
card: {
maxWidth: 500,
margin: '50px auto',
paddingBottom: 16,
},
media: {
height: 0,
paddingTop: '56.25%', // 16:9
},
button: {
// fontSize: 20,
// marginBottom: 16,
background: 'rgba(22,200,200,0.05)',
},
});
@withStyles(styles)
export default class Index extends PureComponent {
render() {
const { classes } = this.props;
return (
<Fragment>
<Layout>
<Me />
</Layout>
</Fragment>
);
}
}
<file_sep>import { createStore, applyMiddleware } from 'redux';
import effect from './utils/effect';
import reducers from './reducers';
import effects from './effects';
const bindMiddleware = (middleware) => {
if (process.env.NODE_ENV !== 'production') {
const { composeWithDevTools } = require('redux-devtools-extension');
return composeWithDevTools(applyMiddleware(...middleware));
}
return applyMiddleware(...middleware);
};
export function configureStore(initialState = {}) {
const store = createStore(
reducers,
initialState,
bindMiddleware([effect(effects)]),
);
return store;
}
<file_sep>import React, { PureComponent, Fragment } from 'react';
import { withStyles } from '@material-ui/core/styles';
import { connect } from 'react-redux';
const styles = theme => ({
root: {
maxWidth: 700,
margin: '92px auto 32px',
},
submitButton: {
marginTop: 16,
margin: '0 auto',
display: 'block',
// padding: '16px 32px',
},
});
@connect(({ user }) => ({ user }))
@withStyles(styles)
export default class Index extends PureComponent {
render() {
const { classes } = this.props;
return (
<Fragment>
<div className={classes.root}>
888
</div>
</Fragment>
);
}
}
|
e189063c8ac7106f04520e37fcc9e24a35589d0f
|
[
"JavaScript",
"Markdown",
"Shell"
] | 34
|
JavaScript
|
monameng/frontend
|
cf0573d0ca3e8fe3e0a24ecbf10681222b4f4a4c
|
6a46412759996688b88c7ee96017bbb94e8ba881
|
refs/heads/main
|
<repo_name>http-rs/http-client<file_sep>/src/h1/tls.rs
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use async_std::net::TcpStream;
use async_trait::async_trait;
use deadpool::managed::{Manager, Object, RecycleResult};
use futures::io::{AsyncRead, AsyncWrite};
use futures::task::{Context, Poll};
cfg_if::cfg_if! {
if #[cfg(feature = "rustls")] {
use async_tls::client::TlsStream;
} else if #[cfg(feature = "native-tls")] {
use async_native_tls::TlsStream;
}
}
use crate::{Config, Error};
#[derive(Clone)]
#[cfg_attr(not(feature = "rustls"), derive(std::fmt::Debug))]
pub(crate) struct TlsConnection {
host: String,
addr: SocketAddr,
config: Arc<Config>,
}
impl TlsConnection {
pub(crate) fn new(host: String, addr: SocketAddr, config: Arc<Config>) -> Self {
Self { host, addr, config }
}
}
pub(crate) struct TlsConnWrapper {
conn: Object<TlsStream<TcpStream>, Error>,
}
impl TlsConnWrapper {
pub(crate) fn new(conn: Object<TlsStream<TcpStream>, Error>) -> Self {
Self { conn }
}
}
impl AsyncRead for TlsConnWrapper {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<Result<usize, std::io::Error>> {
Pin::new(&mut *self.conn).poll_read(cx, buf)
}
}
impl AsyncWrite for TlsConnWrapper {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
Pin::new(&mut *self.conn).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut *self.conn).poll_flush(cx)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut *self.conn).poll_close(cx)
}
}
#[async_trait]
impl Manager<TlsStream<TcpStream>, Error> for TlsConnection {
async fn create(&self) -> Result<TlsStream<TcpStream>, Error> {
let raw_stream = async_std::net::TcpStream::connect(self.addr).await?;
raw_stream.set_nodelay(self.config.tcp_no_delay)?;
let tls_stream = add_tls(&self.host, raw_stream, &self.config).await?;
Ok(tls_stream)
}
async fn recycle(&self, conn: &mut TlsStream<TcpStream>) -> RecycleResult<Error> {
let mut buf = [0; 4];
let mut cx = Context::from_waker(futures::task::noop_waker_ref());
conn.get_ref()
.set_nodelay(self.config.tcp_no_delay)
.map_err(Error::from)?;
match Pin::new(conn).poll_read(&mut cx, &mut buf) {
Poll::Ready(Err(error)) => Err(error),
Poll::Ready(Ok(bytes)) if bytes == 0 => Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"connection appeared to be closed (EoF)",
)),
_ => Ok(()),
}
.map_err(Error::from)?;
Ok(())
}
}
cfg_if::cfg_if! {
if #[cfg(feature = "rustls")] {
#[allow(unused_variables)]
pub(crate) async fn add_tls(host: &str, stream: TcpStream, config: &Config) -> Result<TlsStream<TcpStream>, std::io::Error> {
let connector = if let Some(tls_config) = config.tls_config.as_ref().cloned() {
tls_config.into()
} else {
async_tls::TlsConnector::default()
};
connector.connect(host, stream).await
}
} else if #[cfg(feature = "native-tls")] {
#[allow(unused_variables)]
pub(crate) async fn add_tls(
host: &str,
stream: TcpStream,
config: &Config,
) -> Result<TlsStream<TcpStream>, async_native_tls::Error> {
let connector = config.tls_config.as_ref().cloned().unwrap_or_default();
connector.connect(host, stream).await
}
}
}
<file_sep>/src/h1/tcp.rs
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use async_std::net::TcpStream;
use async_trait::async_trait;
use deadpool::managed::{Manager, Object, RecycleResult};
use futures::io::{AsyncRead, AsyncWrite};
use futures::task::{Context, Poll};
use crate::Config;
#[derive(Clone)]
#[cfg_attr(not(feature = "rustls"), derive(std::fmt::Debug))]
pub(crate) struct TcpConnection {
addr: SocketAddr,
config: Arc<Config>,
}
impl TcpConnection {
pub(crate) fn new(addr: SocketAddr, config: Arc<Config>) -> Self {
Self { addr, config }
}
}
pub(crate) struct TcpConnWrapper {
conn: Object<TcpStream, std::io::Error>,
}
impl TcpConnWrapper {
pub(crate) fn new(conn: Object<TcpStream, std::io::Error>) -> Self {
Self { conn }
}
}
impl AsyncRead for TcpConnWrapper {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut [u8],
) -> Poll<Result<usize, std::io::Error>> {
Pin::new(&mut *self.conn).poll_read(cx, buf)
}
}
impl AsyncWrite for TcpConnWrapper {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &[u8],
) -> Poll<std::io::Result<usize>> {
Pin::new(&mut *self.conn).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut *self.conn).poll_flush(cx)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut *self.conn).poll_close(cx)
}
}
#[async_trait]
impl Manager<TcpStream, std::io::Error> for TcpConnection {
async fn create(&self) -> Result<TcpStream, std::io::Error> {
let tcp_stream = TcpStream::connect(self.addr).await?;
tcp_stream.set_nodelay(self.config.tcp_no_delay)?;
Ok(tcp_stream)
}
async fn recycle(&self, conn: &mut TcpStream) -> RecycleResult<std::io::Error> {
let mut buf = [0; 4];
let mut cx = Context::from_waker(futures::task::noop_waker_ref());
conn.set_nodelay(self.config.tcp_no_delay)?;
match Pin::new(conn).poll_read(&mut cx, &mut buf) {
Poll::Ready(Err(error)) => Err(error),
Poll::Ready(Ok(bytes)) if bytes == 0 => Err(std::io::Error::new(
std::io::ErrorKind::UnexpectedEof,
"connection appeared to be closed (EoF)",
)),
_ => Ok(()),
}?;
Ok(())
}
}
<file_sep>/src/wasm.rs
//! http-client implementation for fetch
use std::convert::{Infallible, TryFrom};
use std::pin::Pin;
use futures::prelude::*;
use send_wrapper::SendWrapper;
use crate::Config;
use super::{http_types::Headers, Body, Error, HttpClient, Request, Response};
/// WebAssembly HTTP Client.
#[derive(Debug)]
pub struct WasmClient {
config: Config,
}
impl WasmClient {
/// Create a new instance.
pub fn new() -> Self {
Self {
config: Config::default(),
}
}
}
impl Default for WasmClient {
fn default() -> Self {
Self::new()
}
}
impl HttpClient for WasmClient {
fn send<'a, 'async_trait>(
&'a self,
req: Request,
) -> Pin<Box<dyn Future<Output = Result<Response, Error>> + Send + 'async_trait>>
where
'a: 'async_trait,
Self: 'async_trait,
{
let config = self.config.clone();
wrap_send(async move {
let req: fetch::Request = fetch::Request::new(req).await?;
let conn = req.send();
let mut res = if let Some(timeout) = config.timeout {
async_std::future::timeout(timeout, conn).await??
} else {
conn.await?
};
let body = res.body_bytes();
let mut response =
Response::new(http_types::StatusCode::try_from(res.status()).unwrap());
response.set_body(Body::from(body));
for (name, value) in res.headers() {
let name: http_types::headers::HeaderName = name.parse().unwrap();
response.append_header(&name, value);
}
Ok(response)
})
}
/// Override the existing configuration with new configuration.
///
/// Config options may not impact existing connections.
fn set_config(&mut self, config: Config) -> http_types::Result<()> {
self.config = config;
Ok(())
}
/// Get the current configuration.
fn config(&self) -> &Config {
&self.config
}
}
impl TryFrom<Config> for WasmClient {
type Error = Infallible;
fn try_from(config: Config) -> Result<Self, Self::Error> {
Ok(Self { config })
}
}
// This should not panic because WASM doesn't have threads yet. Once WASM supports threads
// we can use a thread to park the blocking implementation until it's been completed.
fn wrap_send<Fut, O>(f: Fut) -> Pin<Box<dyn Future<Output = O> + Send + Sync + 'static>>
where
Fut: Future<Output = O> + 'static,
{
Box::pin(SendWrapper::new(f))
}
mod fetch {
use js_sys::{Array, ArrayBuffer, Reflect, Uint8Array};
use wasm_bindgen::{prelude::*, JsCast};
use wasm_bindgen_futures::JsFuture;
use web_sys::{RequestInit, Window, WorkerGlobalScope};
use std::iter::{IntoIterator, Iterator};
use std::pin::Pin;
use http_types::StatusCode;
use crate::Error;
enum WindowOrWorker {
Window(Window),
Worker(WorkerGlobalScope),
}
impl WindowOrWorker {
fn new() -> Self {
#[wasm_bindgen]
extern "C" {
type Global;
#[wasm_bindgen(method, getter, js_name = Window)]
fn window(this: &Global) -> JsValue;
#[wasm_bindgen(method, getter, js_name = WorkerGlobalScope)]
fn worker(this: &Global) -> JsValue;
}
let global: Global = js_sys::global().unchecked_into();
if !global.window().is_undefined() {
Self::Window(global.unchecked_into())
} else if !global.worker().is_undefined() {
Self::Worker(global.unchecked_into())
} else {
panic!("Only supported in a browser or web worker");
}
}
}
/// Create a new fetch request.
/// An HTTP Fetch Request.
pub(crate) struct Request {
request: web_sys::Request,
/// This field stores the body of the request to ensure it stays allocated as long as the request needs it.
#[allow(dead_code)]
body_buf: Pin<Vec<u8>>,
}
impl Request {
/// Create a new instance.
pub(crate) async fn new(mut req: super::Request) -> Result<Self, Error> {
// create a fetch request initaliser
let mut init = RequestInit::new();
// set the fetch method
init.method(req.method().as_ref());
let uri = req.url().to_string();
let body = req.take_body();
// convert the body into a uint8 array
// needs to be pinned and retained inside the Request because the Uint8Array passed to
// js is just a portal into WASM linear memory, and if the underlying data is moved the
// js ref will become silently invalid
let body_buf = body.into_bytes().await.map_err(|_| {
Error::from_str(StatusCode::BadRequest, "could not read body into a buffer")
})?;
let body_pinned = Pin::new(body_buf);
if body_pinned.len() > 0 {
let uint_8_array = unsafe { js_sys::Uint8Array::view(&body_pinned) };
init.body(Some(&uint_8_array));
}
let request = web_sys::Request::new_with_str_and_init(&uri, &init).map_err(|e| {
Error::from_str(
StatusCode::BadRequest,
format!("failed to create request: {:?}", e),
)
})?;
// add any fetch headers
let headers: &mut super::Headers = req.as_mut();
for (name, value) in headers.iter() {
let name = name.as_str();
let value = value.as_str();
request.headers().set(name, value).map_err(|_| {
Error::from_str(
StatusCode::BadRequest,
format!("could not add header: {} = {}", name, value),
)
})?;
}
Ok(Self {
request,
body_buf: body_pinned,
})
}
/// Submit a request
// TODO(yoshuawuyts): turn this into a `Future` impl on `Request` instead.
pub(crate) async fn send(self) -> Result<Response, Error> {
// Send the request.
let scope = WindowOrWorker::new();
let promise = match scope {
WindowOrWorker::Window(window) => window.fetch_with_request(&self.request),
WindowOrWorker::Worker(worker) => worker.fetch_with_request(&self.request),
};
let resp = JsFuture::from(promise)
.await
.map_err(|e| Error::from_str(StatusCode::BadRequest, format!("{:?}", e)))?;
debug_assert!(resp.is_instance_of::<web_sys::Response>());
let res: web_sys::Response = resp.dyn_into().unwrap();
// Get the response body.
let promise = res.array_buffer().unwrap();
let resp = JsFuture::from(promise).await.unwrap();
debug_assert!(resp.is_instance_of::<js_sys::ArrayBuffer>());
let buf: ArrayBuffer = resp.dyn_into().unwrap();
let slice = Uint8Array::new(&buf);
let mut body: Vec<u8> = vec![0; slice.length() as usize];
slice.copy_to(&mut body);
Ok(Response::new(res, body))
}
}
/// An HTTP Fetch Response.
pub(crate) struct Response {
res: web_sys::Response,
body: Option<Vec<u8>>,
}
impl Response {
fn new(res: web_sys::Response, body: Vec<u8>) -> Self {
Self {
res,
body: Some(body),
}
}
/// Access the HTTP headers.
pub(crate) fn headers(&self) -> Headers {
Headers {
headers: self.res.headers(),
}
}
/// Get the request body as a byte vector.
///
/// Returns an empty vector if the body has already been consumed.
pub(crate) fn body_bytes(&mut self) -> Vec<u8> {
self.body.take().unwrap_or_else(|| vec![])
}
/// Get the HTTP return status code.
pub(crate) fn status(&self) -> u16 {
self.res.status()
}
}
/// HTTP Headers.
pub(crate) struct Headers {
headers: web_sys::Headers,
}
impl IntoIterator for Headers {
type Item = (String, String);
type IntoIter = HeadersIter;
fn into_iter(self) -> Self::IntoIter {
HeadersIter {
iter: js_sys::try_iter(&self.headers).unwrap().unwrap(),
}
}
}
/// HTTP Headers Iterator.
pub(crate) struct HeadersIter {
iter: js_sys::IntoIter,
}
impl Iterator for HeadersIter {
type Item = (String, String);
fn next(&mut self) -> Option<Self::Item> {
let pair = self.iter.next()?;
let array: Array = pair.unwrap().into();
let vals = array.values();
let prop = String::from("value").into();
let key = Reflect::get(&vals.next().unwrap(), &prop).unwrap();
let value = Reflect::get(&vals.next().unwrap(), &prop).unwrap();
Some((
key.as_string().to_owned().unwrap(),
value.as_string().to_owned().unwrap(),
))
}
}
}
<file_sep>/src/h1/mod.rs
//! http-client implementation for async-h1, with connection pooling ("Keep-Alive").
use std::convert::{Infallible, TryFrom};
use std::fmt::Debug;
use std::net::SocketAddr;
use std::sync::Arc;
use async_h1::client;
use async_std::net::TcpStream;
use dashmap::DashMap;
use deadpool::managed::Pool;
use http_types::StatusCode;
cfg_if::cfg_if! {
if #[cfg(feature = "rustls")] {
use async_tls::client::TlsStream;
} else if #[cfg(feature = "native-tls")] {
use async_native_tls::TlsStream;
}
}
use crate::Config;
use super::{async_trait, Error, HttpClient, Request, Response};
mod tcp;
#[cfg(any(feature = "native-tls", feature = "rustls"))]
mod tls;
use tcp::{TcpConnWrapper, TcpConnection};
#[cfg(any(feature = "native-tls", feature = "rustls"))]
use tls::{TlsConnWrapper, TlsConnection};
type HttpPool = DashMap<SocketAddr, Pool<TcpStream, std::io::Error>>;
#[cfg(any(feature = "native-tls", feature = "rustls"))]
type HttpsPool = DashMap<SocketAddr, Pool<TlsStream<TcpStream>, Error>>;
/// async-h1 based HTTP Client, with connection pooling ("Keep-Alive").
pub struct H1Client {
http_pools: HttpPool,
#[cfg(any(feature = "native-tls", feature = "rustls"))]
https_pools: HttpsPool,
config: Arc<Config>,
}
impl Debug for H1Client {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let https_pools = if cfg!(any(feature = "native-tls", feature = "rustls")) {
self.http_pools
.iter()
.map(|pool| {
let status = pool.status();
format!(
"Connections: {}, Available: {}, Max: {}",
status.size, status.available, status.max_size
)
})
.collect::<Vec<String>>()
} else {
vec![]
};
f.debug_struct("H1Client")
.field(
"http_pools",
&self
.http_pools
.iter()
.map(|pool| {
let status = pool.status();
format!(
"Connections: {}, Available: {}, Max: {}",
status.size, status.available, status.max_size
)
})
.collect::<Vec<String>>(),
)
.field("https_pools", &https_pools)
.field("config", &self.config)
.finish()
}
}
impl Default for H1Client {
fn default() -> Self {
Self::new()
}
}
impl H1Client {
/// Create a new instance.
pub fn new() -> Self {
Self {
http_pools: DashMap::new(),
#[cfg(any(feature = "native-tls", feature = "rustls"))]
https_pools: DashMap::new(),
config: Arc::new(Config::default()),
}
}
/// Create a new instance.
#[deprecated(
since = "6.5.0",
note = "This function is misnamed. Prefer `Config::max_connections_per_host` instead."
)]
pub fn with_max_connections(max: usize) -> Self {
#[cfg(features = "h1_client")]
assert!(max > 0, "max_connections_per_host with h1_client must be greater than zero or it will deadlock!");
let config = Config {
max_connections_per_host: max,
..Default::default()
};
Self {
http_pools: DashMap::new(),
#[cfg(any(feature = "native-tls", feature = "rustls"))]
https_pools: DashMap::new(),
config: Arc::new(config),
}
}
}
#[async_trait]
impl HttpClient for H1Client {
async fn send(&self, mut req: Request) -> Result<Response, Error> {
req.insert_header("Connection", "keep-alive");
// Insert host
#[cfg(any(feature = "native-tls", feature = "rustls"))]
let host = req
.url()
.host_str()
.ok_or_else(|| Error::from_str(StatusCode::BadRequest, "missing hostname"))?
.to_string();
let scheme = req.url().scheme();
if scheme != "http"
&& (scheme != "https" || cfg!(not(any(feature = "native-tls", feature = "rustls"))))
{
return Err(Error::from_str(
StatusCode::BadRequest,
format!("invalid url scheme '{}'", scheme),
));
}
let addrs = req.url().socket_addrs(|| match req.url().scheme() {
"http" => Some(80),
#[cfg(any(feature = "native-tls", feature = "rustls"))]
"https" => Some(443),
_ => None,
})?;
log::trace!("> Scheme: {}", scheme);
let max_addrs_idx = addrs.len() - 1;
for (idx, addr) in addrs.into_iter().enumerate() {
let has_another_addr = idx != max_addrs_idx;
if !self.config.http_keep_alive {
match scheme {
"http" => {
let stream = async_std::net::TcpStream::connect(addr).await?;
req.set_peer_addr(stream.peer_addr().ok());
req.set_local_addr(stream.local_addr().ok());
let tcp_conn = client::connect(stream, req);
return if let Some(timeout) = self.config.timeout {
async_std::future::timeout(timeout, tcp_conn).await?
} else {
tcp_conn.await
};
}
#[cfg(any(feature = "native-tls", feature = "rustls"))]
"https" => {
let raw_stream = async_std::net::TcpStream::connect(addr).await?;
req.set_peer_addr(raw_stream.peer_addr().ok());
req.set_local_addr(raw_stream.local_addr().ok());
let tls_stream = tls::add_tls(&host, raw_stream, &self.config).await?;
let tsl_conn = client::connect(tls_stream, req);
return if let Some(timeout) = self.config.timeout {
async_std::future::timeout(timeout, tsl_conn).await?
} else {
tsl_conn.await
};
}
_ => unreachable!(),
}
}
match scheme {
"http" => {
let pool_ref = if let Some(pool_ref) = self.http_pools.get(&addr) {
pool_ref
} else {
let manager = TcpConnection::new(addr, self.config.clone());
let pool = Pool::<TcpStream, std::io::Error>::new(
manager,
self.config.max_connections_per_host,
);
self.http_pools.insert(addr, pool);
self.http_pools.get(&addr).unwrap()
};
// Deadlocks are prevented by cloning an inner pool Arc and dropping the original locking reference before we await.
let pool = pool_ref.clone();
std::mem::drop(pool_ref);
let stream = match pool.get().await {
Ok(s) => s,
Err(_) if has_another_addr => continue,
Err(e) => return Err(Error::from_str(400, e.to_string())),
};
req.set_peer_addr(stream.peer_addr().ok());
req.set_local_addr(stream.local_addr().ok());
let tcp_conn = client::connect(TcpConnWrapper::new(stream), req);
return if let Some(timeout) = self.config.timeout {
async_std::future::timeout(timeout, tcp_conn).await?
} else {
tcp_conn.await
};
}
#[cfg(any(feature = "native-tls", feature = "rustls"))]
"https" => {
let pool_ref = if let Some(pool_ref) = self.https_pools.get(&addr) {
pool_ref
} else {
let manager = TlsConnection::new(host.clone(), addr, self.config.clone());
let pool = Pool::<TlsStream<TcpStream>, Error>::new(
manager,
self.config.max_connections_per_host,
);
self.https_pools.insert(addr, pool);
self.https_pools.get(&addr).unwrap()
};
// Deadlocks are prevented by cloning an inner pool Arc and dropping the original locking reference before we await.
let pool = pool_ref.clone();
std::mem::drop(pool_ref);
let stream = match pool.get().await {
Ok(s) => s,
Err(_) if has_another_addr => continue,
Err(e) => return Err(Error::from_str(400, e.to_string())),
};
req.set_peer_addr(stream.get_ref().peer_addr().ok());
req.set_local_addr(stream.get_ref().local_addr().ok());
let tls_conn = client::connect(TlsConnWrapper::new(stream), req);
return if let Some(timeout) = self.config.timeout {
async_std::future::timeout(timeout, tls_conn).await?
} else {
tls_conn.await
};
}
_ => unreachable!(),
}
}
Err(Error::from_str(
StatusCode::BadRequest,
"missing valid address",
))
}
/// Override the existing configuration with new configuration.
///
/// Config options may not impact existing connections.
fn set_config(&mut self, config: Config) -> http_types::Result<()> {
#[cfg(features = "h1_client")]
assert!(config.max_connections_per_host > 0, "max_connections_per_host with h1_client must be greater than zero or it will deadlock!");
self.config = Arc::new(config);
Ok(())
}
/// Get the current configuration.
fn config(&self) -> &Config {
&*self.config
}
}
impl TryFrom<Config> for H1Client {
type Error = Infallible;
fn try_from(config: Config) -> Result<Self, Self::Error> {
#[cfg(features = "h1_client")]
assert!(config.max_connections_per_host > 0, "max_connections_per_host with h1_client must be greater than zero or it will deadlock!");
Ok(Self {
http_pools: DashMap::new(),
#[cfg(any(feature = "native-tls", feature = "rustls"))]
https_pools: DashMap::new(),
config: Arc::new(config),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use async_std::prelude::*;
use async_std::task;
use http_types::url::Url;
use http_types::Result;
use std::time::Duration;
fn build_test_request(url: Url) -> Request {
let mut req = Request::new(http_types::Method::Post, url);
req.set_body("hello");
req.append_header("test", "value");
req
}
#[async_std::test]
async fn basic_functionality() -> Result<()> {
let port = portpicker::pick_unused_port().unwrap();
let mut app = tide::new();
app.at("/").all(|mut r: tide::Request<()>| async move {
let mut response = tide::Response::new(http_types::StatusCode::Ok);
response.set_body(r.body_bytes().await.unwrap());
Ok(response)
});
let server = task::spawn(async move {
app.listen(("localhost", port)).await?;
Result::Ok(())
});
let client = task::spawn(async move {
task::sleep(Duration::from_millis(100)).await;
let request =
build_test_request(Url::parse(&format!("http://localhost:{}/", port)).unwrap());
let mut response: Response = H1Client::new().send(request).await?;
assert_eq!(response.body_string().await.unwrap(), "hello");
Ok(())
});
server.race(client).await?;
Ok(())
}
#[async_std::test]
async fn https_functionality() -> Result<()> {
task::sleep(Duration::from_millis(100)).await;
// Send a POST request to https://httpbin.org/post
// The result should be a JSon string similar to what you get with:
// curl -X POST "https://httpbin.org/post" -H "accept: application/json" -H "Content-Type: text/plain;charset=utf-8" -d "hello"
let request = build_test_request(Url::parse("https://httpbin.org/post").unwrap());
let mut response: Response = H1Client::new().send(request).await?;
let json_val: serde_json::value::Value =
serde_json::from_str(&response.body_string().await.unwrap())?;
assert_eq!(*json_val.get("data").unwrap(), serde_json::json!("hello"));
Ok(())
}
}
<file_sep>/CHANGELOG.md
# Changelog
All notable changes to surf will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://book.async.rs/overview/stability-guarantees.html).
## [Unreleased]
## [6.5.3]
### Deps
- `h1-client` now uses `dashmap` at version `5.x >`, fixing an unsoundness issue.
## [6.5.2]
### Deps
- Now only uses `dashmap` for `h1-client`.
## [6.5.1]
Same as 6.5.0 with one change:
`Config::max_connections_per_host()` is now properly named `Config::set_max_connections_per_host()`.
## [6.5.0]
(Yanked)
### Added
- `Config` has been stabilized and is now available by default!
- `wasm_client` support for `Config` (only timeouts).
- `Config::max_connections_per_host` (Supported on `h1_client` and `curl_client`.)
### Deprecated
- `H1Client::with_max_connections()` will be superseded by `Config::max_connections_per_host`.
## [6.4.1] - 2021-05-19
### Docs
- Added `"unstable-config"` to the docs builds.
## [6.4.0] - 2021-05-17
### Added
- Added a new `unstable-config` feature, which exposes runtime configuration via a new `Config` struct.
## [6.3.5] - 2021-03-12
### Fixed
- Multiple headers of the same name are now present with any client backend and not just `h1_client`.
- Connection when multiple IPs are present for a hostname not function with the `h1_client` backend.
## [6.3.4] - 2021-03-06
### Fixed
- `h1_client` connection pools now properly check if connections are still alive before recycling them.
- Like, actually properly this time.
- There is a test now to ensure closed connections don't cause errors.
## [6.3.3] - 2021-03-01
### Fixed
- `h1_client` connection pools now properly check if connections are still alive before recycling them.
## [6.3.2] - 2021-03-01
_(This was the same thing as 6.3.1 released by git accident.)_
## [6.3.1] - 2021-02-15
### Fixed
- Allow http-client to build & run properly when `h1_client` is enabled without either tls option.
- Prefer `rustls` if both tls features are enabled.
### Internal
- More exhaustive CI for feature combinations.
## [6.3.0] - 2021-02-12
### Added
- Connection pooling (HTTP/1.1 `keep-alive`) for `h1_client` (default).
- `native-tls` (default) and `rustls` feature flags.
- Only works with `h1_client`.
- Isahc metrics as a response extension for `curl_client`.
### Fixed
- `Box<dyn HttpClient>` no longer infinitely recurses.
- `curl_client` now always correctly reads the response body.
- `hyper_client` should now build correctly.
- `WasmClient` fetch from worker scope now works correctly.
### Internal
- Improved CI
## [6.2.0] - 2020-10-26
This release implements `HttpClient` for `Box<dyn HttpClient>`.
### Added
- `impl HttpClient for Box<dyn HttpClient>`
## [6.1.0] - 2020-10-09
This release brings improvements for `HyperClient` (`hyper_client` feature).
### Added
- `HyperClient` now impls `Default`.
- `HyperClient::from_client(hyper::Client<C>)`.
### Changed
- `HyperClient` now re-uses the internal client, allowing connection pooling.
## [6.0.0] - 2020-09-25
This release moves the responsibility of any client sharing to the user.
### Changed
- `HttpClient` implementations no longer `impl Clone`.
- The responsibility for sharing is the user's.
- `H1Client` can no longer be instatiated via `H1Client {}`.
- `::new()` should be used.
## [5.0.1] - 2020-09-18
### Fixed
- Fixed a body stream translation bug in the `hyper_client`.
## [5.0.0] - 2020-09-18
This release includes an optional backend using [hyper.rs](https://hyper.rs/), and uses [async-trait](https://crates.io/crates/async-trait) for `HttpClient`.
### Added
- `hyper_client` feature, for using [hyper.rs](https://hyper.rs/) as the client backend.
### Changed
- `HttpClient` now uses [async-trait](https://crates.io/crates/async-trait).
- This attribute is also re-exported as `http_client::async_trait`.
### Fixed
- Fixed WASM compilation.
- Fixed Isahc (curl) client translation setting duplicate headers incorrectly.
## [4.0.0] - 2020-07-09
This release allows `HttpClient` to be used as a dynamic Trait object.
- `HttpClient`: removed `Clone` bounds.
- `HttpClient`: removed `Error` type.
## [3.0.0] - 2020-05-29
This patch updates `http-client` to `http-types 2.0.0` and a new version of `async-h1`.
### Changes
- http types and async-h1 for 2.0.0 #27
## [2.0.0] - 2020-04-17
### Added
- Added a new backend: `h1-client` https://github.com/http-rs/http-client/pull/22
### Changed
- All types are now based from `hyperium/http` to `http-types` https://github.com/http-rs/http-client/pull/22
<file_sep>/src/hyper.rs
//! http-client implementation for reqwest
use std::convert::{Infallible, TryFrom};
use std::fmt::Debug;
use std::io;
use std::str::FromStr;
use futures_util::stream::TryStreamExt;
use http_types::headers::{HeaderName, HeaderValue};
use http_types::StatusCode;
use hyper::body::HttpBody;
use hyper::client::connect::Connect;
use hyper_tls::HttpsConnector;
use crate::Config;
use super::{async_trait, Error, HttpClient, Request, Response};
type HyperRequest = hyper::Request<hyper::Body>;
// Avoid leaking Hyper generics into HttpClient by hiding it behind a dynamic trait object pointer.
trait HyperClientObject: Debug + Send + Sync + 'static {
fn dyn_request(&self, req: hyper::Request<hyper::Body>) -> hyper::client::ResponseFuture;
}
impl<C: Clone + Connect + Debug + Send + Sync + 'static> HyperClientObject for hyper::Client<C> {
fn dyn_request(&self, req: HyperRequest) -> hyper::client::ResponseFuture {
self.request(req)
}
}
/// Hyper-based HTTP Client.
#[derive(Debug)]
pub struct HyperClient {
client: Box<dyn HyperClientObject>,
config: Config,
}
impl HyperClient {
/// Create a new client instance.
pub fn new() -> Self {
let https = HttpsConnector::new();
let client = hyper::Client::builder().build(https);
Self {
client: Box::new(client),
config: Config::default(),
}
}
/// Create from externally initialized and configured client.
pub fn from_client<C>(client: hyper::Client<C>) -> Self
where
C: Clone + Connect + Debug + Send + Sync + 'static,
{
Self {
client: Box::new(client),
config: Config::default(),
}
}
}
impl Default for HyperClient {
fn default() -> Self {
Self::new()
}
}
#[async_trait]
impl HttpClient for HyperClient {
async fn send(&self, req: Request) -> Result<Response, Error> {
let req = HyperHttpRequest::try_from(req).await?.into_inner();
let conn_fut = self.client.dyn_request(req);
let response = if let Some(timeout) = self.config.timeout {
match tokio::time::timeout(timeout, conn_fut).await {
Err(_elapsed) => Err(Error::from_str(400, "Client timed out")),
Ok(Ok(try_res)) => Ok(try_res),
Ok(Err(e)) => Err(e.into()),
}?
} else {
conn_fut.await?
};
let res = HttpTypesResponse::try_from(response).await?.into_inner();
Ok(res)
}
/// Override the existing configuration with new configuration.
///
/// Config options may not impact existing connections.
fn set_config(&mut self, config: Config) -> http_types::Result<()> {
let connector = HttpsConnector::new();
let mut builder = hyper::Client::builder();
if !config.http_keep_alive {
builder.pool_max_idle_per_host(1);
}
self.client = Box::new(builder.build(connector));
self.config = config;
Ok(())
}
/// Get the current configuration.
fn config(&self) -> &Config {
&self.config
}
}
impl TryFrom<Config> for HyperClient {
type Error = Infallible;
fn try_from(config: Config) -> Result<Self, Self::Error> {
let connector = HttpsConnector::new();
let mut builder = hyper::Client::builder();
if !config.http_keep_alive {
builder.pool_max_idle_per_host(1);
}
Ok(Self {
client: Box::new(builder.build(connector)),
config,
})
}
}
struct HyperHttpRequest(HyperRequest);
impl HyperHttpRequest {
async fn try_from(mut value: Request) -> Result<Self, Error> {
// UNWRAP: This unwrap is unjustified in `http-types`, need to check if it's actually safe.
let uri = hyper::Uri::try_from(&format!("{}", value.url())).unwrap();
// `HyperClient` depends on the scheme being either "http" or "https"
match uri.scheme_str() {
Some("http") | Some("https") => (),
_ => return Err(Error::from_str(StatusCode::BadRequest, "invalid scheme")),
};
let mut request = hyper::Request::builder();
// UNWRAP: Default builder is safe
let req_headers = request.headers_mut().unwrap();
for (name, values) in &value {
// UNWRAP: http-types and http have equivalent validation rules
let name = hyper::header::HeaderName::from_str(name.as_str()).unwrap();
for value in values.iter() {
// UNWRAP: http-types and http have equivalent validation rules
let value =
hyper::header::HeaderValue::from_bytes(value.as_str().as_bytes()).unwrap();
req_headers.append(&name, value);
}
}
let body = value.body_bytes().await?;
let body = hyper::Body::from(body);
let request = request
.method(value.method())
.version(value.version().map(|v| v.into()).unwrap_or_default())
.uri(uri)
.body(body)?;
Ok(HyperHttpRequest(request))
}
fn into_inner(self) -> hyper::Request<hyper::Body> {
self.0
}
}
struct HttpTypesResponse(Response);
impl HttpTypesResponse {
async fn try_from(value: hyper::Response<hyper::Body>) -> Result<Self, Error> {
let (parts, body) = value.into_parts();
let size_hint = body.size_hint().upper().map(|s| s as usize);
let body = body.map_err(|err| io::Error::new(io::ErrorKind::Other, err.to_string()));
let body = http_types::Body::from_reader(body.into_async_read(), size_hint);
let mut res = Response::new(parts.status);
res.set_version(Some(parts.version.into()));
for (name, value) in parts.headers {
let value = value.as_bytes().to_owned();
let value = HeaderValue::from_bytes(value)?;
if let Some(name) = name {
let name = name.as_str();
let name = HeaderName::from_str(name)?;
res.append_header(name, value);
}
}
res.set_body(body);
Ok(HttpTypesResponse(res))
}
fn into_inner(self) -> Response {
self.0
}
}
#[cfg(test)]
mod tests {
use crate::{Error, HttpClient};
use http_types::{Method, Request, Url};
use hyper::service::{make_service_fn, service_fn};
use std::time::Duration;
use tokio::sync::oneshot::channel;
use super::HyperClient;
async fn echo(
req: hyper::Request<hyper::Body>,
) -> Result<hyper::Response<hyper::Body>, hyper::Error> {
Ok(hyper::Response::new(req.into_body()))
}
#[tokio::test]
async fn basic_functionality() {
let (send, recv) = channel::<()>();
let recv = async move { recv.await.unwrap_or(()) };
let addr = ([127, 0, 0, 1], portpicker::pick_unused_port().unwrap()).into();
let service = make_service_fn(|_| async { Ok::<_, hyper::Error>(service_fn(echo)) });
let server = hyper::Server::bind(&addr)
.serve(service)
.with_graceful_shutdown(recv);
let client = HyperClient::new();
let url = Url::parse(&format!("http://localhost:{}", addr.port())).unwrap();
let mut req = Request::new(Method::Get, url);
req.set_body("hello");
let client = async move {
tokio::time::delay_for(Duration::from_millis(100)).await;
let mut resp = client.send(req).await?;
send.send(()).unwrap();
assert_eq!(resp.body_string().await?, "hello");
Result::<(), Error>::Ok(())
};
let (client_res, server_res) = tokio::join!(client, server);
assert!(client_res.is_ok());
assert!(server_res.is_ok());
}
}
<file_sep>/tests/test.rs
use mockito::mock;
use http_client::HttpClient;
use http_types::{Body, Request, Response, Url};
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(not(feature = "hyper_client"))] {
use async_std::test as atest;
} else {
use tokio::test as atest;
}
}
cfg_if! {
if #[cfg(feature = "curl_client")] {
use http_client::isahc::IsahcClient as DefaultClient;
} else if #[cfg(feature = "wasm_client")] {
use http_client::wasm::WasmClient as DefaultClient;
} else if #[cfg(any(feature = "h1_client", feature = "h1_client_rustls"))] {
use http_client::h1::H1Client as DefaultClient;
} else if #[cfg(feature = "hyper_client")] {
use http_client::hyper::HyperClient as DefaultClient;
}
}
#[atest]
async fn post_json() -> Result<(), http_types::Error> {
#[derive(serde::Deserialize, serde::Serialize)]
struct Cat {
name: String,
}
let cat = Cat {
name: "Chashu".to_string(),
};
let m = mock("POST", "/")
.with_status(200)
.match_body(&serde_json::to_string(&cat)?[..])
.with_body(&serde_json::to_string(&cat)?[..])
.create();
let mut req = Request::new(
http_types::Method::Post,
Url::parse(&mockito::server_url()).unwrap(),
);
req.append_header("Accept", "application/json");
req.set_body(Body::from_json(&cat)?);
let res: Response = DefaultClient::new().send(req).await?;
m.assert();
assert_eq!(res.status(), http_types::StatusCode::Ok);
Ok(())
}
#[atest]
async fn get_json() -> Result<(), http_types::Error> {
#[derive(serde::Deserialize)]
struct Message {
message: String,
}
let m = mock("GET", "/")
.with_status(200)
.with_body(r#"{"message": "hello, world!"}"#)
.create();
let req = Request::new(
http_types::Method::Get,
Url::parse(&mockito::server_url()).unwrap(),
);
let mut res: Response = DefaultClient::new().send(req).await?;
let msg: Message = serde_json::from_str(&res.body_string().await?)?;
m.assert();
assert_eq!(msg.message, "hello, world!");
Ok(())
}
#[atest]
async fn get_google() -> Result<(), http_types::Error> {
let url = "https://www.google.com";
let req = Request::new(http_types::Method::Get, Url::parse(url).unwrap());
let mut res: Response = DefaultClient::new().send(req).await?;
assert_eq!(res.status(), http_types::StatusCode::Ok);
let msg = res.body_bytes().await?;
let msg = String::from_utf8_lossy(&msg);
println!("recieved: '{}'", msg);
assert!(msg.contains("<!doctype html>"));
assert!(msg.contains("<title>Google</title>"));
assert!(msg.contains("<head>"));
assert!(msg.contains("</head>"));
assert!(msg.contains("</script>"));
assert!(msg.contains("</script>"));
assert!(msg.contains("<body"));
assert!(msg.contains("</body>"));
assert!(msg.contains("</html>"));
Ok(())
}
#[atest]
async fn get_github() -> Result<(), http_types::Error> {
let url = "https://raw.githubusercontent.com/http-rs/surf/6627d9fc15437aea3c0a69e0b620ae7769ea6765/LICENSE-MIT";
let req = Request::new(http_types::Method::Get, Url::parse(url).unwrap());
let mut res: Response = DefaultClient::new().send(req).await?;
assert_eq!(res.status(), http_types::StatusCode::Ok, "{:?}", &res);
let msg = res.body_string().await?;
assert_eq!(
msg,
"The MIT License (MIT)
Copyright (c) 2019 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the \"Software\"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"
);
Ok(())
}
#[atest]
async fn keep_alive() {
let _mock_guard = mockito::mock("GET", "/report")
.with_status(200)
.expect_at_least(2)
.create();
let client = DefaultClient::new();
let url: Url = format!("{}/report", mockito::server_url()).parse().unwrap();
let req = Request::new(http_types::Method::Get, url);
client.send(req.clone()).await.unwrap();
client.send(req.clone()).await.unwrap();
}
#[atest]
async fn fallback_to_ipv4() {
let client = DefaultClient::new();
let _mock_guard = mock("GET", "/")
.with_status(200)
.expect_at_least(2)
.create();
// Kips the initial "http://127.0.0.1:" to get only the port number
let mock_port = &mockito::server_url()[17..];
let url = &format!("http://localhost:{}", mock_port);
let req = Request::new(http_types::Method::Get, Url::parse(url).unwrap());
client.send(req.clone()).await.unwrap();
}
<file_sep>/src/isahc.rs
//! http-client implementation for isahc
use std::convert::TryFrom;
use async_std::io::BufReader;
use isahc::config::Configurable;
use isahc::{http, ResponseExt};
use crate::Config;
use super::{async_trait, Body, Error, HttpClient, Request, Response};
/// Curl-based HTTP Client.
#[derive(Debug)]
pub struct IsahcClient {
client: isahc::HttpClient,
config: Config,
}
impl Default for IsahcClient {
fn default() -> Self {
Self::new()
}
}
impl IsahcClient {
/// Create a new instance.
pub fn new() -> Self {
Self::from_client(isahc::HttpClient::new().unwrap())
}
/// Create from externally initialized and configured client.
pub fn from_client(client: isahc::HttpClient) -> Self {
Self {
client,
config: Config::default(),
}
}
}
#[async_trait]
impl HttpClient for IsahcClient {
async fn send(&self, mut req: Request) -> Result<Response, Error> {
let mut builder = http::Request::builder()
.uri(req.url().as_str())
.method(http::Method::from_bytes(req.method().to_string().as_bytes()).unwrap());
for (name, value) in req.iter() {
builder = builder.header(name.as_str(), value.as_str());
}
let body = req.take_body();
let body = match body.len() {
Some(len) => isahc::Body::from_reader_sized(body, len as u64),
None => isahc::Body::from_reader(body),
};
let request = builder.body(body).unwrap();
let res = self.client.send_async(request).await.map_err(Error::from)?;
let maybe_metrics = res.metrics().cloned();
let (parts, body) = res.into_parts();
let body = Body::from_reader(BufReader::new(body), None);
let mut response = http_types::Response::new(parts.status.as_u16());
for (name, value) in &parts.headers {
response.append_header(name.as_str(), value.to_str().unwrap());
}
if let Some(metrics) = maybe_metrics {
response.ext_mut().insert(metrics);
}
response.set_body(body);
Ok(response)
}
/// Override the existing configuration with new configuration.
///
/// Config options may not impact existing connections.
fn set_config(&mut self, config: Config) -> http_types::Result<()> {
let mut builder =
isahc::HttpClient::builder().max_connections_per_host(config.max_connections_per_host);
if !config.http_keep_alive {
builder = builder.connection_cache_size(0);
}
if config.tcp_no_delay {
builder = builder.tcp_nodelay();
}
if let Some(timeout) = config.timeout {
builder = builder.timeout(timeout);
}
self.client = builder.build()?;
self.config = config;
Ok(())
}
/// Get the current configuration.
fn config(&self) -> &Config {
&self.config
}
}
impl TryFrom<Config> for IsahcClient {
type Error = isahc::Error;
fn try_from(config: Config) -> Result<Self, Self::Error> {
let mut builder = isahc::HttpClient::builder();
if !config.http_keep_alive {
builder = builder.connection_cache_size(0);
}
if config.tcp_no_delay {
builder = builder.tcp_nodelay();
}
if let Some(timeout) = config.timeout {
builder = builder.timeout(timeout);
}
Ok(Self {
client: builder.build()?,
config,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use async_std::prelude::*;
use async_std::task;
use http_types::url::Url;
use http_types::Result;
use std::time::Duration;
fn build_test_request(url: Url) -> Request {
let mut req = Request::new(http_types::Method::Post, url);
req.set_body("hello");
req.append_header("test", "value");
req
}
#[async_std::test]
async fn basic_functionality() -> Result<()> {
let port = portpicker::pick_unused_port().unwrap();
let mut app = tide::new();
app.at("/").all(|mut r: tide::Request<()>| async move {
let mut response = tide::Response::new(http_types::StatusCode::Ok);
response.set_body(r.body_bytes().await.unwrap());
Ok(response)
});
let server = task::spawn(async move {
app.listen(("localhost", port)).await?;
Result::Ok(())
});
let client = task::spawn(async move {
task::sleep(Duration::from_millis(100)).await;
let request =
build_test_request(Url::parse(&format!("http://localhost:{}/", port)).unwrap());
let mut response: Response = IsahcClient::new().send(request).await?;
assert_eq!(response.body_string().await.unwrap(), "hello");
Ok(())
});
server.race(client).await?;
Ok(())
}
}
<file_sep>/src/config.rs
//! Configuration for `HttpClient`s.
use std::fmt::Debug;
use std::time::Duration;
/// Configuration for `HttpClient`s.
#[non_exhaustive]
#[derive(Clone)]
pub struct Config {
/// HTTP/1.1 `keep-alive` (connection pooling).
///
/// Default: `true`.
///
/// Note: Does nothing on `wasm_client`.
pub http_keep_alive: bool,
/// TCP `NO_DELAY`.
///
/// Default: `false`.
///
/// Note: Does nothing on `wasm_client`.
pub tcp_no_delay: bool,
/// Connection timeout duration.
///
/// Default: `Some(Duration::from_secs(60))`.
pub timeout: Option<Duration>,
/// Maximum number of simultaneous connections that this client is allowed to keep open to individual hosts at one time.
///
/// Default: `50`.
/// This number is based on a few random benchmarks and see whatever gave decent perf vs resource use in Orogene.
///
/// Note: The behavior of this is different depending on the backend in use.
/// - `h1_client`: `0` is disallowed and asserts as otherwise it would cause a semaphore deadlock.
/// - `curl_client`: `0` allows for limitless connections per host.
/// - `hyper_client`: No effect. Hyper does not support such an option.
/// - `wasm_client`: No effect. Web browsers do not support such an option.
pub max_connections_per_host: usize,
/// TLS Configuration (Rustls)
#[cfg_attr(feature = "docs", doc(cfg(feature = "h1_client")))]
#[cfg(all(feature = "h1_client", feature = "rustls"))]
pub tls_config: Option<std::sync::Arc<rustls_crate::ClientConfig>>,
/// TLS Configuration (Native TLS)
#[cfg_attr(feature = "docs", doc(cfg(feature = "h1_client")))]
#[cfg(all(feature = "h1_client", feature = "native-tls", not(feature = "rustls")))]
pub tls_config: Option<std::sync::Arc<async_native_tls::TlsConnector>>,
}
impl Debug for Config {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let mut dbg_struct = f.debug_struct("Config");
dbg_struct
.field("http_keep_alive", &self.http_keep_alive)
.field("tcp_no_delay", &self.tcp_no_delay)
.field("timeout", &self.timeout)
.field("max_connections_per_host", &self.max_connections_per_host);
#[cfg(all(feature = "h1_client", feature = "rustls"))]
{
if self.tls_config.is_some() {
dbg_struct.field("tls_config", &"Some(rustls::ClientConfig)");
} else {
dbg_struct.field("tls_config", &"None");
}
}
#[cfg(all(feature = "h1_client", feature = "native-tls", not(feature = "rustls")))]
{
dbg_struct.field("tls_config", &self.tls_config);
}
dbg_struct.finish()
}
}
impl Config {
/// Construct new empty config.
pub fn new() -> Self {
Self {
http_keep_alive: true,
tcp_no_delay: false,
timeout: Some(Duration::from_secs(60)),
max_connections_per_host: 50,
#[cfg(all(feature = "h1_client", any(feature = "rustls", feature = "native-tls")))]
tls_config: None,
}
}
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}
impl Config {
/// Set HTTP/1.1 `keep-alive` (connection pooling).
pub fn set_http_keep_alive(mut self, keep_alive: bool) -> Self {
self.http_keep_alive = keep_alive;
self
}
/// Set TCP `NO_DELAY`.
pub fn set_tcp_no_delay(mut self, no_delay: bool) -> Self {
self.tcp_no_delay = no_delay;
self
}
/// Set connection timeout duration.
pub fn set_timeout(mut self, timeout: Option<Duration>) -> Self {
self.timeout = timeout;
self
}
/// Set the maximum number of simultaneous connections that this client is allowed to keep open to individual hosts at one time.
pub fn set_max_connections_per_host(mut self, max_connections_per_host: usize) -> Self {
self.max_connections_per_host = max_connections_per_host;
self
}
/// Set TLS Configuration (Rustls)
#[cfg_attr(feature = "docs", doc(cfg(feature = "h1_client")))]
#[cfg(all(feature = "h1_client", feature = "rustls"))]
pub fn set_tls_config(
mut self,
tls_config: Option<std::sync::Arc<rustls_crate::ClientConfig>>,
) -> Self {
self.tls_config = tls_config;
self
}
/// Set TLS Configuration (Native TLS)
#[cfg_attr(feature = "docs", doc(cfg(feature = "h1_client")))]
#[cfg(all(feature = "h1_client", feature = "native-tls", not(feature = "rustls")))]
pub fn set_tls_config(
mut self,
tls_config: Option<std::sync::Arc<async_native_tls::TlsConnector>>,
) -> Self {
self.tls_config = tls_config;
self
}
}
<file_sep>/examples/print_client_debug.rs
use http_client::HttpClient;
use http_types::{Method, Request};
#[cfg(any(feature = "h1_client", feature = "docs"))]
use http_client::h1::H1Client as Client;
#[cfg(all(feature = "hyper_client", not(feature = "docs")))]
use http_client::hyper::HyperClient as Client;
#[cfg(all(feature = "curl_client", not(feature = "docs")))]
use http_client::isahc::IsahcClient as Client;
#[cfg(all(feature = "wasm_client", not(feature = "docs")))]
use http_client::wasm::WasmClient as Client;
#[async_std::main]
async fn main() {
let client = Client::new();
let req = Request::new(Method::Get, "http://example.org");
client.send(req).await.unwrap();
dbg!(client);
}
<file_sep>/src/lib.rs
//! Types and traits for http clients.
//!
//! This crate has been extracted from `surf`'s internals, but can be used by any http client impl.
//! The purpose of this crate is to provide a unified interface for multiple HTTP client backends,
//! so that they can be abstracted over without doing extra work.
#![forbid(future_incompatible, rust_2018_idioms)]
#![deny(missing_debug_implementations, nonstandard_style)]
#![warn(missing_docs, missing_doc_code_examples, unreachable_pub)]
#![cfg_attr(feature = "docs", feature(doc_cfg))]
// Forbid `unsafe` for the native & curl features, but allow it (for now) under the WASM backend
#![cfg_attr(
not(all(feature = "wasm_client", target_arch = "wasm32")),
forbid(unsafe_code)
)]
mod config;
pub use config::Config;
#[cfg_attr(feature = "docs", doc(cfg(feature = "curl_client")))]
#[cfg(all(feature = "curl_client", not(target_arch = "wasm32")))]
pub mod isahc;
#[cfg_attr(feature = "docs", doc(cfg(feature = "wasm_client")))]
#[cfg(all(feature = "wasm_client", target_arch = "wasm32"))]
pub mod wasm;
#[cfg_attr(feature = "docs", doc(cfg(feature = "native_client")))]
#[cfg(any(feature = "curl_client", feature = "wasm_client"))]
pub mod native;
#[cfg_attr(feature = "docs", doc(cfg(feature = "h1_client")))]
#[cfg_attr(feature = "docs", doc(cfg(feature = "default")))]
#[cfg(any(feature = "h1_client", feature = "h1_client_rustls"))]
pub mod h1;
#[cfg_attr(feature = "docs", doc(cfg(feature = "hyper_client")))]
#[cfg(feature = "hyper_client")]
pub mod hyper;
/// An HTTP Request type with a streaming body.
pub type Request = http_types::Request;
/// An HTTP Response type with a streaming body.
pub type Response = http_types::Response;
pub use async_trait::async_trait;
pub use http_types;
/// An abstract HTTP client.
///
/// __note that this is only exposed for use in middleware. Building new backing clients is not
/// recommended yet. Once it is we'll likely publish a new `http_client` crate, and re-export this
/// trait from there together with all existing HTTP client implementations.__
///
/// ## Spawning new request from middleware
///
/// When threading the trait through a layer of middleware, the middleware must be able to perform
/// new requests. In order to enable this efficiently an `HttpClient` instance may want to be passed
/// though middleware for one of its own requests, and in order to do so should be wrapped in an
/// `Rc`/`Arc` to enable reference cloning.
#[async_trait]
pub trait HttpClient: std::fmt::Debug + Unpin + Send + Sync + 'static {
/// Perform a request.
async fn send(&self, req: Request) -> Result<Response, Error>;
/// Override the existing configuration with new configuration.
///
/// Config options may not impact existing connections.
fn set_config(&mut self, _config: Config) -> http_types::Result<()> {
unimplemented!(
"{} has not implemented `HttpClient::set_config()`",
type_name_of(self)
)
}
/// Get the current configuration.
fn config(&self) -> &Config {
unimplemented!(
"{} has not implemented `HttpClient::config()`",
type_name_of(self)
)
}
}
fn type_name_of<T: ?Sized>(_val: &T) -> &'static str {
std::any::type_name::<T>()
}
/// The raw body of an http request or response.
pub type Body = http_types::Body;
/// Error type.
pub type Error = http_types::Error;
#[async_trait]
impl HttpClient for Box<dyn HttpClient> {
async fn send(&self, req: Request) -> http_types::Result<Response> {
self.as_ref().send(req).await
}
fn set_config(&mut self, config: Config) -> http_types::Result<()> {
self.as_mut().set_config(config)
}
fn config(&self) -> &Config {
self.as_ref().config()
}
}
<file_sep>/Cargo.toml
[package]
name = "http-client"
version = "6.5.3"
license = "MIT OR Apache-2.0"
repository = "https://github.com/http-rs/http-client"
documentation = "https://docs.rs/http-client"
description = "Types and traits for http clients."
keywords = ["http", "service", "client", "futures", "async"]
categories = ["asynchronous", "web-programming", "web-programming::http-client", "web-programming::websocket"]
authors = [
"<NAME> <<EMAIL>>",
"dignifiedquire <<EMAIL>>",
"<NAME> <<EMAIL>>"
]
readme = "README.md"
edition = "2018"
[package.metadata.docs.rs]
features = ["docs"]
rustdoc-args = ["--cfg", "feature=\"docs\""]
[features]
default = ["h1_client", "native-tls"]
docs = ["h1_client", "curl_client", "wasm_client", "hyper_client"]
h1_client = ["async-h1", "async-std", "dashmap", "deadpool", "futures"]
native_client = ["curl_client", "wasm_client"]
curl_client = ["isahc", "async-std"]
wasm_client = ["js-sys", "web-sys", "wasm-bindgen", "wasm-bindgen-futures", "futures", "async-std"]
hyper_client = ["hyper", "hyper-tls", "http-types/hyperium_http", "futures-util", "tokio"]
native-tls = ["async-native-tls"]
rustls = ["async-tls", "rustls_crate"]
unstable-config = [] # deprecated
[dependencies]
async-trait = "0.1.37"
http-types = "2.3.0"
log = "0.4.7"
cfg-if = "1.0.0"
# h1_client
async-h1 = { version = "2.0.0", optional = true }
async-std = { version = "1.6.0", default-features = false, optional = true }
async-native-tls = { version = "0.3.1", optional = true }
dashmap = { version = "5.3.4", optional = true }
deadpool = { version = "0.7.0", optional = true }
futures = { version = "0.3.8", optional = true }
# h1_client_rustls
async-tls = { version = "0.11", optional = true }
rustls_crate = { version = "0.19", optional = true, package = "rustls" }
# hyper_client
hyper = { version = "0.13.6", features = ["tcp"], optional = true }
hyper-tls = { version = "0.4.3", optional = true }
futures-util = { version = "0.3.5", features = ["io"], optional = true }
tokio = { version = "0.2", features = ["time"], optional = true }
# curl_client
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
isahc = { version = "0.9", optional = true, default-features = false, features = ["http2"] }
# wasm_client
[target.'cfg(target_arch = "wasm32")'.dependencies]
js-sys = { version = "0.3.25", optional = true }
wasm-bindgen = { version = "0.2.48", optional = true }
wasm-bindgen-futures = { version = "0.4.5", optional = true }
futures = { version = "0.3.1", optional = true }
send_wrapper = { version = "0.6.0", features = ["futures"] }
[target.'cfg(target_arch = "wasm32")'.dependencies.web-sys]
version = "0.3.25"
optional = true
features = [
"AbortSignal",
"Headers",
"ObserverCallback",
"ReferrerPolicy",
"Request",
"RequestCache",
"RequestCredentials",
"RequestInit",
"RequestMode",
"RequestRedirect",
"Response",
"Window",
"WorkerGlobalScope",
]
[dev-dependencies]
async-std = { version = "1.6.0", features = ["unstable", "attributes"] }
portpicker = "0.1.0"
tide = { version = "0.15.0", default-features = false, features = ["h1-server"] }
tide-rustls = { version = "0.1.4" }
tokio = { version = "0.2.21", features = ["macros"] }
serde = "1.0"
serde_json = "1.0"
mockito = "0.23.3"
[dev-dependencies.getrandom]
version = "0.2"
features = ["js"]
<file_sep>/src/native.rs
//! http-client implementation for curl + fetch
#[cfg(all(feature = "curl_client", not(target_arch = "wasm32")))]
pub use super::isahc::IsahcClient as NativeClient;
#[cfg(all(feature = "wasm_client", target_arch = "wasm32"))]
pub use super::wasm::WasmClient as NativeClient;
|
b2013d8b0859216b9c9f2ea95ae9e67c336aa2b4
|
[
"Markdown",
"Rust",
"TOML"
] | 13
|
Rust
|
http-rs/http-client
|
c776e32a5e4c37160b0c522fc4502c5d6a6ac6fe
|
44a5c58f5b88726dcf262485d6828ea6ba29c32c
|
refs/heads/master
|
<repo_name>Nikita-Poltavets/Homework_4<file_sep>/conversation-view/src/main/java/ua/com/alevel/nix/fileconversation/view/config/StorageProperties.java
package ua.com.alevel.nix.fileconversation.view.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties("storage")
public class StorageProperties {
private String locationIdentityDir = "identity-dir";
private String locationSplitDir = "split-dir";
private String locationReplaceDir = "replace-dir";
private String locationCountSymbolsDir = "countSymbols-dir";
private String locationCountWordsDir = "countWords-dir";
private String locationReverseDir = "reverse-dir";
private String locationFindRootsDir = "findRoots-dir";
public String getLocationIdentityDir() {
return locationIdentityDir;
}
public void setLocationIdentityDir(String locationIdentityDir) {
this.locationIdentityDir = locationIdentityDir;
}
public String getLocationSplitDir() {
return locationSplitDir;
}
public void setLocationSplitDir(String locationSplitDir) {
this.locationSplitDir = locationSplitDir;
}
public String getLocationReplaceDir() {
return locationReplaceDir;
}
public void setLocationReplaceDir(String locationReplaceDir) {
this.locationReplaceDir = locationReplaceDir;
}
public String getLocationCountSymbolsDir() {
return locationCountSymbolsDir;
}
public void setLocationCountSymbolsDir(String locationCountSymbolsDir) {
this.locationCountSymbolsDir = locationCountSymbolsDir;
}
public String getLocationCountWordsDir() {
return locationCountWordsDir;
}
public void setLocationCountWordsDir(String locationCountWordsDir) {
this.locationCountWordsDir = locationCountWordsDir;
}
public String getLocationReverseDir() {
return locationReverseDir;
}
public void setLocationReverseDir(String locationReverseDir) {
this.locationReverseDir = locationReverseDir;
}
public String getLocationFindRootsDir() {
return locationFindRootsDir;
}
public void setLocationFindRootsDir(String locationFindRootsDir) {
this.locationFindRootsDir = locationFindRootsDir;
}
}
<file_sep>/conversation-view/src/main/java/ua/com/alevel/nix/fileconversation/view/config/ConversationType.java
package ua.com.alevel.nix.fileconversation.view.config;
public enum ConversationType {
IDENTITY, SPLIT, REPLACE, COUNTSYMBOLS, COUNTWORDS, REVERSE, FINDROOTS
}
<file_sep>/conversation-view/src/test/java/ua/com/alevel/nix/fileconversation/view/util/SpeedStringBuilderAndBufferUtil.java
package ua.com.alevel.nix.fileconversation.view.util;
public class SpeedStringBuilderAndBufferUtil {
public static void run(Appendable obj) throws java.io.IOException {
long before = System.currentTimeMillis();
for (int i = 0; i++ < Integer.MAX_VALUE; ) {
obj.append("");
}
long after = System.currentTimeMillis();
System.out.println(obj.getClass().getSimpleName() + ": " + (after - before) + "ms.");
}
}
<file_sep>/conversation-view/src/test/java/ua/com/alevel/nix/fileconversation/view/ConversationViewApplicationTests.java
package ua.com.alevel.nix.fileconversation.view;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class ConversationViewApplicationTests {
@Test
void contextLoads() {
}
}
<file_sep>/conversation-view/src/test/java/ua/com/alevel/nix/fileconversation/view/ApacheStringMethodTest.java
package ua.com.alevel.nix.fileconversation.view;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class ApacheStringMethodTest implements AbstractStringMethodTest {
@Test
@Override
public void frequentlyUsedMethods() {
String stringTest = "JavaStringTest";
if (StringUtils.isNotBlank(stringTest)) {
System.out.println("stringTest is not blank");
} else {
System.out.println("stringTest is blank");
}
if (StringUtils.isNotEmpty(stringTest)) {
System.out.println("stringTest is not empty");
} else {
System.out.println("stringTest is empty");
}
String stringNumericTest = "1r";
if (StringUtils.isNumeric(stringNumericTest)) {
System.out.println("stringNumericTest is numeric");
} else {
System.out.println("stringNumericTest is not numeric");
}
String stringWhitespaceTest = " ";
if (StringUtils.isWhitespace(stringWhitespaceTest)) {
System.out.println("stringWhitespaceTest is whitespace");
} else {
System.out.println("stringWhitespaceTest is not whitespace");
}
String stringJoinWithTest = StringUtils.joinWith(stringTest, "-", "-");
System.out.println("stringJoinWithTest = " + stringJoinWithTest);
}
}
<file_sep>/conversation-util/src/main/java/ua/com/alevel/nix/fileconversation/util/ConversationUtil.java
package ua.com.alevel.nix.fileconversation.util;
import org.apache.commons.lang3.StringUtils;
import java.util.*;
import java.util.stream.Collectors;
public class ConversationUtil {
public static String splitConversation(String file) {
return Arrays.stream(file.split(" ")).map(s -> s.concat("\n")).collect(Collectors.joining());
}
public static String replaceConversation(String file) {
return file.replaceAll("\\?", "X");
}
public static String countSymbolsConversation(String file){
String result = "";
Map<Character, Integer> map = new HashMap<>();
int occurrence;
for (int i = 0; i < file.length(); i++) {
if(!map.containsKey(file.charAt(i))) {
occurrence = StringUtils.countMatches(file, file.charAt(i));
map.put(file.charAt(i), occurrence);
}
}
Map <Character, Integer> mapResult = sortMapByValueForSymbol(map);
for (Map.Entry<Character, Integer> pair: mapResult.entrySet()) {
result += pair.getValue() + " ---> " + pair.getKey() + "\r\n";
}
return result;
}
public static String countWordsConversation(String file){
String result = "", newFile;
Map<String, Integer> map = new HashMap<>();
ArrayList<String> arrayWords = new ArrayList<>();
int occurrence;
newFile = file.replaceAll("\\pP|\\s{2,}|\r\n|\n", "");
for (String word : newFile.split(" ")){
arrayWords.add(word);
}
for (int i = 0; i < arrayWords.size(); i++) {
if(!map.containsKey(arrayWords.get(i))) {
occurrence = StringUtils.countMatches(file, arrayWords.get(i));
map.put(arrayWords.get(i), occurrence);
}
}
Map <String, Integer> mapResult = sortMapByValueForWord(map);
for (Map.Entry<String, Integer> pair: mapResult.entrySet()) {
result += pair.getValue() + " ---> " + pair.getKey() + "\r\n";
}
return result;
}
public static String reverseConversation(String file){
String result = "";
ArrayList<String> arrayWords = new ArrayList<>();
List<Integer> indexSlashN = new ArrayList<>();
for (int pos = file.indexOf("\r\n"); pos != -1; pos = file.indexOf("\r\n", pos + 1)) {
indexSlashN.add(pos);
}
for (String word : file.split("\\s")){
arrayWords.add(word);
}
for (int i = arrayWords.size() - 1; i >= 0; i--) {
result += arrayWords.get(i) + " ";
}
for (int i = 0; i < result.length(); i++) {
for (int j = 0; j < indexSlashN.size(); j++) {
if(indexSlashN.get(j) == i){
result = result.substring(0, i) + "\r\n" + result.substring(i);
}
}
}
return result;
}
public static String findRootsConversation(String file){
String result = "";
ArrayList<String> arrayWords = new ArrayList<>();
Map<String, Integer> map = new HashMap<>();
int occurrence;
String[] roots = {"ama", "astr", "aud", "auto", "belli", "bio", "brev", "cap", "centri", "chrono", "cide", "cor", "cardi", "cred", "deca", "derm", "dorm", "duct", "fac", "fic", "fid", "fin", "flex", "fort", "fract", "frag", "gam", "gen", "geo", "gress", "grad", "graph", "gram",
"greg", "hema", "hemo", "hydra", "hydro", "ject", "loqu", "magna", "mania", "mar", "mega", "meter", "micro", "migra", "mit", "mis", "multi", "nov", "omni", "onym", "ortho", "pan", "ped", "pod", "pel", "puls", "phil", "phobia", "port", "proto", "psych", "rupt",
"scope", "scrib", "script", "spir", "struct", "tele", "temp", "terra", "therm", "tox", "tract", "uni", "vent", "vera", "veri", "vict", "vinc", "voc", "vor", "zo"};
for (String word : roots){
arrayWords.add(word);
}
for (int i = 0; i < arrayWords.size(); i++) {
if(!map.containsKey(arrayWords.get(i))) {
occurrence = StringUtils.countMatches(file, arrayWords.get(i));
if(occurrence != 0) {
map.put(arrayWords.get(i), occurrence);
}
}
}
Map <String, Integer> mapResult = sortMapByValueForWord(map);
for (Map.Entry<String, Integer> pair: mapResult.entrySet()) {
result += pair.getValue() + " ---> " + pair.getKey() + "\r\n";
}
return result;
}
public static Map<Character, Integer> sortMapByValueForSymbol(final Map<Character, Integer> charCounts) {
return charCounts.entrySet()
.stream()
.sorted((Map.Entry.<Character, Integer>comparingByValue().reversed()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}
public static Map<String, Integer> sortMapByValueForWord(final Map<String, Integer> charCounts) {
return charCounts.entrySet()
.stream()
.sorted((Map.Entry.<String, Integer>comparingByValue().reversed()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
}
}
<file_sep>/conversation-view/src/test/java/ua/com/alevel/nix/fileconversation/view/JavaStringMemoryTest.java
package ua.com.alevel.nix.fileconversation.view;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import ua.com.alevel.nix.fileconversation.view.util.ApproximateAddressUtil;
import java.util.logging.Logger;
@SpringBootTest
public class JavaStringMemoryTest {
private final static Logger LOGGER = Logger.getLogger(JavaStringMemoryTest.class.getName());
@Test
public void initString() {
String stringTest = "JavaStringTest";
System.out.println("stringTest value: = " + stringTest);
System.out.println("stringTest length: = " + stringTest.length());
System.out.println("stringTest hashCode: = " + System.identityHashCode(stringTest));
ApproximateAddressUtil.printAddresses("stringTest address: = ", stringTest);
LOGGER.info("-----------------------------------------------------------------");
String stringTest2 = "JavaStringTest";
System.out.println("stringTest2 value: = " + stringTest2);
System.out.println("stringTest2 length: = " + stringTest2.length());
System.out.println("stringTest2 hashCode: = " + System.identityHashCode(stringTest2));
ApproximateAddressUtil.printAddresses("stringTest2 address: = ", stringTest2);
LOGGER.info("-----------------------------------------------------------------");
String stringTest3 = "JavaStringTest3";
System.out.println("stringTest3 value: = " + stringTest3);
System.out.println("stringTest3 length: = " + stringTest3.length());
System.out.println("stringTest3 hashCode: = " + System.identityHashCode(stringTest3));
ApproximateAddressUtil.printAddresses("stringTest3 address: = ", stringTest3);
LOGGER.info("-----------------------------------------------------------------");
char[] stringTestArray = { 'J','a','v','a','S','t','r','i','n','g','T','e','s','t' };
String stringTest4 = new String(stringTestArray);
System.out.println("stringTest4 value: = " + stringTest4);
System.out.println("stringTest4 length: = " + stringTest4.length());
System.out.println("stringTest4 hashCode: = " + System.identityHashCode(stringTest4));
ApproximateAddressUtil.printAddresses("stringTest4 address: = ", stringTest4);
LOGGER.info("-----------------------------------------------------------------");
String stringTest5 = "JavaStringTest";
System.out.println("stringTest5 value: = " + stringTest5);
System.out.println("stringTest5 length: = " + stringTest5.length());
System.out.println("stringTest5 hashCode: = " + System.identityHashCode(stringTest5));
ApproximateAddressUtil.printAddresses("stringTest5 address: = ", stringTest5);
LOGGER.info("-----------------------------------------------------------------");
String stringTest6 = new String(stringTestArray, 0, 4);
System.out.println("stringTest6 value: = " + stringTest6);
System.out.println("stringTest6 length: = " + stringTest6.length());
System.out.println("stringTest6 hashCode: = " + System.identityHashCode(stringTest6));
ApproximateAddressUtil.printAddresses("stringTest6 address: = ", stringTest6);
}
}
<file_sep>/conversation-view/src/main/java/ua/com/alevel/nix/fileconversation/view/data/FileData.java
package ua.com.alevel.nix.fileconversation.view.data;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.util.UriComponents;
import ua.com.alevel.nix.fileconversation.view.config.ConversationType;
import ua.com.alevel.nix.fileconversation.view.controller.files.*;
import java.nio.file.Path;
public class FileData {
private final UriComponents uri;
private final String fileName;
public FileData(Path path, ConversationType conversationType) {
this.fileName = path.getFileName().toString();
this.uri = initUriComponents(this.fileName, conversationType);
}
public UriComponents getUri() {
return uri;
}
public String getFileName() {
return fileName;
}
private UriComponents initUriComponents(String fileName, ConversationType conversationType) {
switch (conversationType) {
case IDENTITY : return MvcUriComponentsBuilder.fromMethodName(IdentityFileController.class,
"serveFile", fileName).build();
case SPLIT : return MvcUriComponentsBuilder.fromMethodName(SplitFileController.class,
"serveFile", fileName).build();
case REPLACE : return MvcUriComponentsBuilder.fromMethodName(ReplaceFileController.class,
"serveFile", fileName).build();
case COUNTSYMBOLS: return MvcUriComponentsBuilder.fromMethodName(CountSymbolsFileController.class,
"serveFile", fileName).build();
case COUNTWORDS: return MvcUriComponentsBuilder.fromMethodName(CountWordsFileController.class,
"serveFile", fileName).build();
case REVERSE: return MvcUriComponentsBuilder.fromMethodName(ReverseFileController.class,
"serveFile", fileName).build();
case FINDROOTS: return MvcUriComponentsBuilder.fromMethodName(FindRootsFileController.class,
"serveFile", fileName).build();
}
return null;
}
}
<file_sep>/conversation-view/src/main/java/ua/com/alevel/nix/fileconversation/view/controller/strings/JavaStringController.java
package ua.com.alevel.nix.fileconversation.view.controller.strings;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = { "/", "/java_string"})
public class JavaStringController {
@GetMapping
public String index() {
return "page/strings/java_string";
}
}
|
7518942f68875747d8af4e530621d33860b5ae89
|
[
"Java"
] | 9
|
Java
|
Nikita-Poltavets/Homework_4
|
4f5d0b032d75b71d922bf7a876f865b272876309
|
f24185ff94e9e3443f8d65623cf015308807d9e0
|
refs/heads/master
|
<repo_name>Fyodir/wsmmGroup<file_sep>/matrix.py
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import csv
import os
import random
import seaborn as sns
# path to file
path = os.path.join(
os.sep,
"media",
"sf_W_DRIVE",
"OneDrive - UOM",
"MSc",
"Year 3",
"wsmmGroup",
"Cardiomyopathies - including childhood onset",
)
matrixFile = os.path.join(path, "All_Genes_Matrix.csv")
df = pd.read_csv(matrixFile, index_col=0)
dfTranspose = df.transpose()
# print(dfTranspose)
print(" ")
print(df.dot(dfTranspose))
geneMatrix = df.dot(dfTranspose)
# coreGeneMatrix.to_csv(path+os.sep+"coreGeneMatrix.csv")
hpoMatrix = dfTranspose.dot(df)
# coreHpoMatrix.to_csv(path+os.sep+"coreHpoMatrix.csv")
print(" ")
print(dfTranspose.dot(df))
# result = np.dot(df, dfTranspose)
# print(result)
# result= np.dot(df, dfTranspose)
# print(dfTranspose.dtypes)
# print(df.transpose())
df = hpoMatrix
plt.pcolor(df)
plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)
plt.show()
<file_sep>/main.py
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import csv
import os
import random
from math import log
# path to file
path = os.path.join(
os.sep,
"home",
"andrew",
"Documents",
"MSc",
"wsmmGroup",
"Cardiomyopathies - including childhood onset",
"moduland",
)
bridgnessCentralityFile = os.path.join(path, "bridgness_centrality.csv")
# set up pandas DF
df = pd.read_csv(bridgnessCentralityFile)
df['moduland_betweenness'] = df['moduland_betweenness'].apply(lambda x: float(x))
df['moduland_centrality'] = df['moduland_centrality'].apply(lambda x: float(x))
# Pd series of gene names
genes = df.name
def regression(x,y):
a, b = np.polyfit(np.array(x), np.array(y), deg=1)
f = lambda x: a*np.array(x) + b
return f
def plotModule(df, moduleName, plotAxes, colour, marker="s"):
# Set variables
x = df.moduland_centrality
y = df.moduland_betweenness
subDf = df[(df['module'] == moduleName)]
xsubDf = subDf.moduland_centrality
ysubDf = subDf.moduland_betweenness
# xLog = xLog.sort()
fsubDf = regression(xsubDf,ysubDf)
# Plot chart
plotAxes.scatter(xsubDf, ysubDf, c=colour, marker=marker, label=moduleName)
# Plot regression line
# plotAxes.plot(xsubDf,fsubDf(xsubDf),lw=1.5, c=colour)
# Annotate points
# lstGenes=subDf.name.tolist()
# for i, gene in enumerate(genes):
# if gene in lstGenes:
# ax1.annotate(gene, (x[i], y[i]))
# Set-up plot
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.set_xlabel("Centrality")
ax1.set_ylabel("Betweeness")
# Plot moduland clusters (modules)
plotModule(df,"MLCYD", ax1, "royalblue")
plotModule(df,"NTRK1", ax1, "gold")
plotModule(df,"HCN1", ax1, "r")
# sub DF for panelApp Genes (green)
panelAppGreen = df[(df['panelAppGreen'] == 1)]
# plot panelApp Genes (Green)
x = df.moduland_centrality
y = df.moduland_betweenness
xPanelAppGreen = panelAppGreen.moduland_centrality
yPanelAppGreen = panelAppGreen.moduland_betweenness
ax1.scatter(xPanelAppGreen, yPanelAppGreen, c='limegreen', marker="x", label='panelAppGreen')
# ax1.plot(xPanelAppGreen,regression(xPanelAppGreen,yPanelAppGreen)(xPanelAppGreen),lw=1.5, c="limegreen")
# panelAppGreenGenes=panelAppGreen.name.tolist()
# for i, gene in enumerate(genes):
# if gene in panelAppGreenGenes:
# ax1.annotate(gene, (x[i], y[i]))
# Add legend
plt.legend(loc='upper left')
plt.xscale("log")
# plt.yscale("log")
plt.show()
##########################################
def extractHpoTerms(GeneSymbol):
"Extract HPO terms from HPO API with a given gene symbol"
import urllib.request
import json
entrezFromGene = "https://hpo.jax.org/api/hpo/search/?q={}" # gene symbol
hpoFromEntrez ="https://hpo.jax.org/api/hpo/gene/{}" # entrez id
data = json.load(urllib.request.urlopen(entrezFromGene.format(GeneSymbol)))
entrezId = data["genes"][0]["entrezGeneId"]
data = json.load(urllib.request.urlopen(hpoFromEntrez.format(entrezId)))
ontology = {}
for entry in data["termAssoc"]:
ontology[entry["name"]] = entry["ontologyId"]
return ontology
class Module:
def __init__(self, gene):
self.moduleGene = gene
self.geneObjects = ""
class Gene:
def __init__(self, gene):
self.gene = gene
self.hpoTerms = ""
self.hpoTermsDf = ""
def setHpoTerms(self):
try:
self.hpoTerms = extractHpoTerms(self.gene)
except:
print("Unable to extract HPO terms for {}".format(self.gene))
self.hpoTerms = {}
def setHpoDf(self):
data = {
"phenotype": self.hpoTerms.keys(),
"hpoId": self.hpoTerms.values(),
}
self.hpoTermsDf = pd.DataFrame.from_dict(data)
def setHpoClasses(df, moduleGene):
module = Module(moduleGene)
dfHPO = df[(df['module'] == moduleGene)]
hpoNames = dfHPO.name.to_list()
module.geneObjects = [Gene(i) for i in hpoNames]
return module
def moduleHpoTerms(moduleGene):
print(" ")
print("########################################################")
print(moduleGene)
print("########################################################")
print(" ")
module = setHpoClasses(df, moduleGene)
for item in module.geneObjects:
item.setHpoTerms()
item.setHpoDf()
# print(item.gene)
# print(item.hpoTermsDf.to_string())
# print(" ")
return module
# lstHpo = []
# geneList = df.name.to_list()
# for gene in geneList:
# try:
# dictHpo = extractHpoTerms(gene)
# # print(gene, "|".join(dictHpo.values()))
# for k,v in dictHpo.items():
# if v not in lstHpo:
# lstHpo.append(v)
# except:
# pass
# firstRow = [","]+lstHpo
# print(",".join(firstRow))
# geneList = df.name.to_list()
# for gene in geneList:
# try:
# dictHpo = extractHpoTerms(gene)
# row = [gene, "|".join(dictHpo.values())]
# print(",".join(row))
# except:
# pass
# print(",".join(lstHpo))
# print(" ")
# for gene in geneList:
# try:
# phenotypes, ids = extractHpoTerms(gene)
# print(gene, "|".join(ids))
# except:
# print("Unable to extract HPO terms for {}".format(gene))
# print(" ")
# for i in df.name.to_list():
# print("{},,".format(i))
# module1 = moduleHpoTerms("MLCYD")
# module2 = moduleHpoTerms("HCN1")
# module3 = moduleHpoTerms("NTRK1")
# genes = []
# for item in module1.geneObjects:
# genes.append(item.gene)
# for item in module2.geneObjects:
# genes.append(item.gene)
# for item in module3.geneObjects:
# genes.append(item.gene)
# phenotypeIds = []
# for item in module1.geneObjects:
# for hpoIdentifier in item.hpoTermsDf.hpoId:
# phenotypeIds.append(hpoIdentifier)
# for item in module2.geneObjects:
# for hpoIdentifier in item.hpoTermsDf.hpoId:
# phenotypeIds.append(hpoIdentifier)
# for item in module3.geneObjects:
# for hpoIdentifier in item.hpoTermsDf.hpoId:
# phenotypeIds.append(hpoIdentifier)
# for gene in genes:
# print(gene)
# print(",".join(phenotypeIds))
# print(genes)
# print(" ")
# print(phenotypeIds)
# plt.show()
|
50ce08bb7fa5c8c1a5d6555d85637eb74e8d9155
|
[
"Python"
] | 2
|
Python
|
Fyodir/wsmmGroup
|
7a8bd213e307e4e5f92368602a2e41e47e6df5ff
|
6b74475bb44263f4e9df87448c0718e6075eef31
|
refs/heads/master
|
<file_sep>fx_version "bodacious"
games {"gta5"}
server_script "bot.js"
|
408bd7b9a5b0e3bb90a44e970c8926d615d5a81a
|
[
"Lua"
] | 1
|
Lua
|
Pradip-Karmakar/Discord-bot
|
d29dcbcca6a6a4a3235ff062dc5e2abf4808cf5c
|
cad0476f47b465bdb529ef7beba8a04eb0929604
|
refs/heads/main
|
<repo_name>mohamedisakr/mastering-mongoose<file_sep>/06-Schema/indexes-sorting.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
require("../01-getting-started/1.2-connecting-to-mongodb");
let schema = Schema({ firstName: String, lastName: String });
// Build an index on `lastName` in reverse order
schema.index({ lastName: -1 });
const User = mongoose.model("User", schema);
const add200kUsers = async () => {
await User.deleteMany({});
const docs = [];
for (let i = 0; i < 200000; ++i) {
docs.push({ firstName: "Agent", lastName: "Smith" });
docs.push({ firstName: "Agent", lastName: "Brown" });
docs.push({ firstName: "Agent", lastName: "Thompson" });
}
await User.insertMany(docs);
};
const sortByFirstName = async () => {
let start = Date.now();
await User.find().sort({ firstName: 1 });
let elapsed = Date.now() - start;
console.log(`Sort by first name takes : ${elapsed}`); // Approximately 751
};
const sortByLastName = async () => {
start = Date.now();
await User.find().sort({ lastName: -1 });
elapsed = Date.now() - start;
console.log(`Sort by last name takes : ${elapsed}`); // Approximately 641, about 15% faster
};
add200kUsers();
sortByFirstName();
sortByLastName();
<file_sep>/04-Middleware/async-middleware.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const schema = Schema({ name: String });
schema.pre("save", async function () {
console.log("Waiting");
await new Promise((resolve) => setTimeout(resolve, 50));
console.log("First Done");
});
schema.pre("save", () => console.log("Second"));
const Model = mongoose.model("Test", schema);
const doc = new Model({ name: "test" });
// Prints
// "Waiting",
// "First Done",
// "Second"
await doc.save();
*/
const schema = Schema({ name: String });
schema.pre("save", function (next) {
console.log("1");
setTimeout(() => {
console.log("2");
next();
}, 50);
});
schema.pre("save", () => console.log("3"));
// For post hooks, `next()` is the 2nd parameter
schema.post("save", function (doc, next) {
console.log("4");
setTimeout(() => {
console.log("5");
next();
}, 50);
});
schema.post("save", () => console.log("6"));
const Model = mongoose.model("Test", schema);
const doc = new Model({ name: "test" });
// Prints "1", "2", "3", "4", "5", "6"
await doc.save();
<file_sep>/06-Schema/least-cardinality.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const personSchema = Schema({ name: String, rankId: ObjectId });
personSchema.virtual("rank", {
ref: "Rank",
localField: "rankId",
foreignField: "_id",
justOne: true,
});
const Person = mongoose.model("Person", personSchema);
const Rank = mongoose.model("Rank", Schema({ name: String }));
const rank1 = await Rank.create({ name: "Captain" });
const rank2 = await Rank.create({ name: "Lieutenant" });
await Person.create({ name: "<NAME>", rankId: rank1 });
await Person.create({ name: "<NAME>", rankId: rank2 });
let doc = await Person.findOne({ name: /Kirk/ }).populate("rank");
doc.rank.name; // 'Captain'
*/
/*
const personSchema = Schema({ name: String });
personSchema.virtual("rank", {
ref: "Rank",
localField: "_id",
foreignField: "peopleIds",
justOne: true,
});
const Person = mongoose.model("Person", personSchema);
const rankSchema = Schema({ name: String, peopleIds: [ObjectId] });
const Rank = mongoose.model("Rank", rankSchema);
let names = ["<NAME>", "Uhura", "<NAME>"];
let p = await Person.create(names.map((name) => ({ name })));
await Rank.create({ name: "Captain", peopleIds: [p[0]] });
await Rank.create({ name: "Lieutenant", peopleIds: [p[1], p[2]] });
let doc = await Person.findOne({ name: /Kirk/ }).populate("rank");
doc.rank.name; // 'Captain'
*/
/*
const docs = await Person.find().sort({ name: 1 }).populate("rank");
// Each `Person` has a `rank` document, and each `rank` document
// stores `peopleIds`. If you have thousands of captains, this data
// would be too bulky to send to a client.
docs[0].rank.peopleIds.length; // 1
docs[1].rank.peopleIds.length; // 2
docs[2].rank.peopleIds.length; // 2
*/
/*
const schema = Schema({ name: String, bId: ObjectId });
schema.virtual("b", {
ref: "B",
localField: "bId",
foreignField: "_id",
justOne: true,
});
const A = mongoose.model("A", schema);
const B = mongoose.model("B", Schema({ name: String }));
*/
/*
const schema = Schema({ name: String, showIds: [ObjectId] });
schema.virtual("shows", {
ref: "Show",
localField: "showIds",
foreignField: "_id",
justOne: false,
});
const Character = mongoose.model("Character", schema);
const Show = mongoose.model("Show", Schema({ name: String }));
const shows = await Show.create([
{ name: "Star Trek" },
{ name: "Star Trek: The Next Generation" },
]);
await Character.create([
{ name: "<NAME>", showIds: [shows[0]] },
{ name: "<NAME>", showIds: [shows[0], shows[1]] },
]);
let v = await Character.findOne({ name: /McCoy/ }).populate("shows");
v.shows[0].name; // 'Star Trek'
v.shows[1].name; // 'Star Trek: The Next Generation'
*/
const userSchema = Schema({ name: String });
userSchema.virtual("attended", {
ref: "Attendee",
localField: "_id",
foreignField: "user",
justOne: false,
// Recursively populate the `Attendee` model's 'event'
options: { populate: "event" },
});
const User = mongoose.model("User", userSchema);
const Event = mongoose.model("Event", Schema({ name: String }));
// A mapping collection: 1 doc per mapping from `Person` to `Event`
const Attendee = mongoose.model(
"Attendee",
Schema({
user: { type: ObjectId, ref: "User" },
event: { type: ObjectId, ref: "Event" },
})
);
const e1 = await Event.create({ name: "Khitomer Conference" });
const e2 = await Event.create({ name: "Enterprise-B Maiden Voyage" });
const users = await User.create([{ name: "Kirk" }, { name: "Spock" }]);
await Attendee.create({ event: e1, user: users[0] });
await Attendee.create({ event: e1, user: users[1] });
await Attendee.create({ event: e2, user: users[0] });
let doc = await User.findOne({ name: "Kirk" }).populate("attended");
doc.attended[0].event.name; // 'Khitomer Conference'
doc.attended[1].event.name; // 'Enterprise-B Maiden Voyage'
<file_sep>/06-Schema/denormalization.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
// If you want to change the rank 'Captain' to be 'Director',
// you would need to update every `Character` document.
const schema = Schema({ name: String, rank: String });
const Character = mongoose.model("Character", schema);
await Character.updateMany({ rank: "Captain" }, { rank: "Director" });
*/
/*
const User = mongoose.model(
"User",
Schema({
name: String,
rank: { type: ObjectId, ref: "Rank" },
})
);
const Rank = mongoose.model("Rank", Schema({ name: String }));
const captain = await Rank.create({ name: "Captain" });
const commander = await Rank.create({ name: "Commander" });
await User.create({ name: "<NAME>", rank: captain });
await User.create({ name: "Spock", rank: commander });
// The `match` option only affects the populated documents.
// This query says to find all users, sort them by name,
// and then populate their `rank` only if `name = 'Captain'`
const docs = await User.find()
.sort({ name: 1 })
.populate({
path: "rank",
match: { name: "Captain" },
});
docs.length; // 2
docs[1].name; // Spock
docs[1].rank; // null
*/
/*
const User = mongoose.model("User", Schema({ name: String }));
const Car = mongoose.model(
"Car",
Schema({
description: String,
licensePlate: String,
owner: { type: ObjectId, ref: "User" },
})
);
// Find users whose name contains 'Crockett'. What if you also
// want to filter by users that have a car whose license plate
// starts with 'ZAQ'?
await User.find({ name: /Crockett/ });
*/
const userSchema = Schema({ name: String, licensePlates: [String] });
const carSchema = Schema({
licensePlate: String,
owner: { type: ObjectId, ref: "User" },
});
// Use middleware to update the corresponding user's
// license plates whenever we update a vehicle.
carSchema.post("save", async function () {
const allCars = await Car.find({ owner: this.owner });
const licensePlates = allCars.map((car) => car.licensePlate);
await User.updateOne({ _id: this.owner }, { licensePlates });
});
const User = mongoose.model("User", userSchema);
const Car = mongoose.model("Car", carSchema);
const owner = await User.create({ name: "<NAME>" });
await User.create({ name: "<NAME>" });
await Car.create({ licensePlate: "ZAQ178", owner });
let doc = await User.findOne({ licensePlates: /ZAQ/ });
doc.name; // '<NAME>'
<file_sep>/06-Schema/explain-helper.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
let schema = Schema({ firstName: String, lastName: String });
schema.index({ firstName: 1, lastName: 1 });
const User = mongoose.model("User", schema);
const findUserByName = async () => {
const firstName = "Agent";
const lastName = "Smith";
const res = await User.findOne({ firstName, lastName }).explain();
// Object with properties like `queryPlanner` & `executionStats`
console.log(res);
};
connectToDB();
findUserByName();
// queryPlanner: {
// plannerVersion: 1,
// namespace: 'mydb.users',
// indexFilterSet: false,
// parsedQuery: { '$and': [Array] },
// winningPlan: { stage: 'LIMIT', limitAmount: 1, inputStage: [Object] },
// rejectedPlans: []
// }
<file_sep>/07-app-structure/validators-middleware.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const profileSchema = Schema({
photos: [String],
status: { type: String, enum: ["PENDING", "PUBLISHED"] },
});
*/
/*
const profileSchema = Schema({
photos: {
type: [String],
validate: function (v) {
return this.status !== "PUBLISHED" || (v && v.length > 1);
},
},
status: { type: String, enum: ["PENDING", "PUBLISHED"] },
});
*/
/*
const profileSchema = Schema({
photos: [String],
status: {
type: String,
enum: ["PENDING", "PUBLISHED"],
},
});
profileSchema.pre("save", function () {
if (this.status === "PUBLISHED" && this.photos.length < 2) {
throw Error("Published profile must have at least 2 photos");
}
});
*/
/*
const Profile = mongoose.model(
"Profile",
Schema({
photos: {
type: [String],
validate: function (v) {
if (this.status !== "PUBLISHED") return true;
return v != null && v.length >= 2;
},
},
status: {
type: String,
enum: ["PENDING", "PUBLISHED"],
},
})
);
const doc = await Profile.create({ status: "PENDING" });
doc.status = "PUBLISHED";
// Doesn't throw because `photos` is not modified.
await doc.save();
*/
/*
const Profile = mongoose.model(
"Profile",
Schema({
publishedAt: {
type: Date,
required: function () {
return this.status === "PUBLISHED";
},
},
status: {
type: String,
enum: ["PENDING", "PUBLISHED"],
},
})
);
const addProfile = async () => {
const doc = await Profile.create({ status: "PENDING" });
doc.status = "PUBLISHED";
const err = await doc.save().catch((err) => err);
console.log(err.message); // Profile validation failed: publishedAt: Path `publishedAt` is required.
};
connectToDB();
addProfile();
*/
<file_sep>/04-Middleware/intro.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
const schema = Schema({ name: String });
// `middleware` is a function that Mongoose will call for you
// when you call `save()`
schema.pre("save", function middleware() {
console.log("Saving", this.name);
});
const Model = mongoose.model("Test", schema);
const doc = new Model({ name: "test" });
// Prints "Saving test"
await doc.save();
<file_sep>/05-Populate/virtual-populate.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const Group = mongoose.model("Group", Schema({ name: String }));
const personSchema = Schema({
name: String,
groupId: mongoose.ObjectId,
});
personSchema.virtual("group", {
ref: "Group",
localField: "groupId",
foreignField: "_id",
justOne: true,
});
const Person = mongoose.model("Person", personSchema);
const groupId = await Group.create({ name: "Jedi Order" });
await Person.create({ name: "<NAME>", groupId });
const person = await Person.findOne().populate("group");
person.group.name; // 'Jedi Order'
*/
/*
const groupSchema = Schema({ name: String });
groupSchema.virtual("people", {
ref: "Person",
localField: "_id",
foreignField: "groupId",
justOne: false,
});
const Group = mongoose.model("Group", groupSchema);
const schema = Schema({ name: String, groupId: "ObjectId" });
const Person = mongoose.model("Person", schema);
const groupId = await Group.create({ name: "Jedi Order" });
await Person.create({ name: "<NAME>", groupId });
const jedi = await Group.findOne().populate("people");
jedi.people.map((doc) => doc.name); // ['<NAME>']
*/
/*
const groupSchema = Schema({ name: String });
const ref = "Person";
const localField = "_id";
const foreignField = "groupId";
// If `justOne` is true, the populated virtual will be either
// a document, or `null` if no document was found.
const opts = { ref, localField, foreignField, justOne: true };
groupSchema.virtual("people", opts);
// If `justOne` is false, the populated virtual will be an
// array containing zero or more documents.
opts.justOne = false;
groupSchema.virtual("people", opts);
*/
/*
let groupSchema = Schema({
name: String,
// Behaves like `justOne: false`
people: [{ type: mongoose.ObjectId, ref: "Person" }],
});
groupSchema = Schema({
name: String,
// Behaves like `justOne: true`
people: { type: mongoose.ObjectId, ref: "Person" },
});
*/
/*
const groupSchema = Schema({ name: String });
groupSchema.virtual("person", {
ref: "Person",
localField: "_id",
foreignField: "groupId",
justOne: true,
});
const Group = mongoose.model("Group", groupSchema);
const Person = mongoose.model(
"Person",
Schema({ name: String, groupId: mongoose.ObjectId })
);
const groupId = await Group.create({ name: "Jedi Order" });
await Person.create({ name: "<NAME>", groupId });
await Person.create({ name: "<NAME>", groupId });
let jedi = await Group.findOne().populate({
path: "person",
options: { sort: { name: 1 } },
});
jedi.person.name; // '<NAME>'
*/
const countrySchema = Schema({ name: String });
countrySchema.virtual("numCities", {
ref: "City",
localField: "_id",
foreignField: "countryId",
count: true, // `numCities` will be a number, not an array
});
const Country = mongoose.model("Country", countrySchema);
let citySchema = Schema({ name: String, countryId: "ObjectId" });
const City = mongoose.model("City", citySchema);
let country = await Country.create({ name: "Switzerland" });
const docs = [{ name: "Bern" }, { name: "Zurich" }].map((doc) =>
Object.assign(doc, { countryId: country._id })
);
await City.create(docs);
country = await Country.findOne().populate("numCities");
country.numCities; // 2
<file_sep>/04-Middleware/aggregation-middleware.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const schema = Schema({ name: String, age: Number });
const Model = mongoose.model("Character", schema);
await Model.create({ name: "<NAME>", age: 59 });
await Model.create({ name: "<NAME>", age: 29 });
await Model.create({ name: "<NAME>", age: 29 });
// The below is equivalent to `Model.find({ age: { $gte: 30 } })`
const docs = await Model.aggregate([
{
// To add a `$match` stage, you add an object to the array
// with a `$match` property. The value of the `$match` property
// is a filter. The aggregation framework only lets documents
// that match the filter pass the `$match` stage.
$match: { age: { $gte: 30 } },
},
]);
console.log(docs.length); // 1
console.log(docs[0].name); // '<NAME>'
*/
/*
// Note that there's no `await` here.
const aggregate = Model.aggregate([{ $match: { age: { $gte: 30 } } }]);
// Mongoose's `Aggregate` class is a tool for building
// aggregation pipelines using function call chaining.
aggregate instanceof mongoose.Aggregate; // true
*/
/*
const schema = Schema({ name: String, age: Number });
schema.pre("aggregate", function () {
this instanceof mongoose.Aggregate; // true
const pipeline = this.pipeline();
pipeline[0]; // { $match: { age: { $gte: 30 } } }
});
schema.post("aggregate", function (res) {
this instanceof mongoose.Aggregate; // true
res.length; // 1
res[0].name; // '<NAME>'
});
const Model = mongoose.model("Character", schema);
// Triggers `pre('aggregate')` and `post('aggregate')`
await Model.aggregate([{ $match: { age: { $gte: 30 } } }]);
*/
/*
const schema = Schema({ name: String, age: Number });
schema.pre("aggregate", function () {
console.log("Called");
});
const Model = mongoose.model("Character", schema);
// Does **not** trigger aggregation middleware
const agg = Model.aggregate([{ $match: { age: { $gte: 30 } } }]);
// Mongoose only runs aggregation middleware when you `exec()`
await agg.exec();
*/
/*
const s = Schema({ name: String, age: Number, isDeleted: Boolean });
s.pre("aggregate", function () {
// Prepend a `$match` stage to every aggregation pipeline that
// filters out documents whose `isDeleted` property is true
this.pipeline().unshift({
$match: {
isDeleted: { $ne: true },
},
});
});
*/
await User.create({ name: "<NAME>", age: 59 });
await User.create({ name: "<NAME>", age: 29 });
await User.create({ name: "<NAME>", isDeleted: true });
// Will **not** return the Tasha Yar doc, because
// that user is soft deleted.
const $match = { age: { $lte: 30 } };
const docs = await User.aggregate([{ $match }]);
docs.length; // 1
docs[0].name; // <NAME>
<file_sep>/constants/mongoose-connection.js
// https://docs.mongodb.com/drivers/node/current/fundamentals/connection/
// https://docs.mongodb.com/manual/reference/connection-string/
require("dotenv").config({ path: "../.env" });
const { env } = process;
// "mongodb://localhost:27017/mydb"
const uri = `${env.PROTOCOL}://${env.HOST}:${env.PORT}/${env.DATABASE_NAME}`;
const connectionOptions = {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
poolSize: 10, // default for MongoDB node.js driver
};
module.exports = { uri, connectionOptions };
<file_sep>/03-queries/limit-skip-project.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const schema = new Schema({ name: String, age: Number });
const Character = mongoose.model("Character", schema);
await Character.create({ name: "<NAME>", age: 59 });
await Character.create({ name: "<NAME>", age: 29 });
await Character.create({ name: "<NAME>", age: 29 });
// Sort by `age` ascending, and return at most 2 documents.
const docs = await Character.find().sort({ age: 1 }).limit(2);
*/
/*
await Character.create({ name: "<NAME>", age: 59 });
await Character.create({ name: "<NAME>", age: 40 });
await Character.create({ name: "<NAME>", age: 29 });
await Character.create({ name: "<NAME>", age: 29 });
const docs = await Character.find()
.sort({ age: 1 }) // Sort by `age` ascending
.skip(2) // Skip the 2 documents
.limit(2); // And return at most 2 documents
docs.map((doc) => doc.name); // ['<NAME>', '<NAME>']
*/
/*
const resultSchema = Schema({ title: String, order: Number });
const SearchResult = mongoose.model("SearchResult", resultSchema);
for (let i = 1; i <= 25; ++i) {
await SearchResult.create({ order: i, title: "test" + i });
}
function getResults(page, resultsPerPage) {
return SearchResult.find()
.sort({ order: 1 })
.skip(page * resultsPerPage)
.limit(resultsPerPage);
}
// Returns results 11-20
const docs = await getResults(1, 10);
*/
/*
let schema = Schema({ name: String, age: Number, rank: String });
const Character = mongoose.model("Character", schema);
await Character.create([{ name: "<NAME>", age: 29, rank: "Commander" }]);
// Include `name` and `age`, exclude `rank`
let projection = { name: 1, age: 1 };
let doc = await Character.findOne().select(projection);
doc.name; // '<NAME>'
doc.rank; // undefined
// Exclude `name` and `age`, include `rank`
projection = { name: false, age: false };
doc = await Character.findOne().select(projection);
doc.name; // undefined
doc.rank; // 'Commander'
*/
/*
const projection = { name: 1, age: 0 };
const err = await Character.findOne()
.select(projection)
.catch((err) => err);
// 'Projection cannot have a mix of inclusion and exclusion.'
err.message;
*/
/*
const update = { age: 44, rank: "Captain" };
const opts = { new: true };
const projection = { name: 1, age: 1 };
// Updates `rank`, but excludes it from the result document
const doc = await Character.findOneAndUpdate({}, update, opts).select(
projection
);
doc.age; // 44
doc.rank; // undefined
*/
/*
const update = { age: 44, rank: "Captain" };
const fields = { nModified: 0 };
const res = await Character.updateOne({}, update).select(fields);
res.nModified; // 1
*/
/*
const User = mongoose.model(
"User",
Schema({
name: String,
// Exclude `email` by default
email: { type: String, select: false },
})
);
await User.create({ name: "John", email: "<EMAIL>" });
await User.create({ name: "Bill", email: "<EMAIL>" });
const docs = await User.find().sort({ name: 1 });
docs[0].name; // 'Bill'
docs[1].name; // 'John'
docs[0].email; // undefined
docs[1].email; // undefined
*/
/*
const docs = await User.find().sort({ name: 1 }).select("email");
docs[0].name; // undefined
docs[1].name; // undefined
docs[0].email; // '<EMAIL>'
docs[1].email; // '<EMAIL>'
*/
/*
const docs = await User.find().sort({ name: 1 }).select("+email"); // Note the `+` here
docs[0].name; // <NAME>
docs[1].name; // <NAME>
docs[0].email; // '<EMAIL>'
docs[1].email; // '<EMAIL>'
*/
/*
const schema = Schema({ name: String });
const Character = mongoose.model("Character", schema);
const ObjectId = mongoose.Types.ObjectId;
const _id = "5dd57639649ce0bd87750caa";
await Character.create([{ _id: ObjectId(_id), name: "<NAME>" }]);
// Works even though `_id` is a string
const doc = await Character.findOne({ _id });
doc._id instanceof ObjectId; // true
doc._id === _id; // false
*/
/*
const schema = Schema({ name: String, age: Number });
const Character = mongoose.model("Character", schema);
await Character.create([{ name: "<NAME>", age: 29 }]);
const filter = { name: "<NAME>" };
// Even though `age` is a string, Mongoose will cast `age` to a
// number because that's the type in `schema`.
const update = { age: "30" };
const opts = { new: true };
const doc = await Character.findOneAndUpdate(filter, update, opts);
doc.age; // 30, as a number
*/
/*
// This `findOneAndUpdate()` will error out because Mongoose can't
// cast the string 'not a number' to a number.
const filter = { name: "<NAME>" };
const update = { age: "not a number" };
const opts = { new: true };
const err = await Character.findOneAndUpdate(filter, update, opts).catch(
(err) => err
);
// 'Cast to number failed for value "not a number" at path "age"'
err.message;
err.name; // 'CastError'
*/
/*
const filter = { age: { $gte: "fail" } };
const err = await Character.findOne(filter).catch((err) => err);
// 'Cast to number failed for value "fail" at path "age" for
// model "Character"'
err.message;
err.name; // 'CastError'
*/
/*
const schema = Schema({
name: String,
rank: { type: String, enum: ["Captain", "Commander"] },
});
const Character = mongoose.model("Character", schema);
await Character.create([{ name: "<NAME>", rank: "Commander" }]);
// By default, Mongoose will let the below update go through, even
// though 'Lollipop' is not in the `enum` of allowed values.
const update = { rank: "Lollipop" };
let opts = { new: true };
const doc = await Character.findOneAndUpdate({}, update, opts);
doc.rank; // 'Lollipop'
// But if you set `runValidators`, Mongoose will run the `enum`
// validator and reject because of an invalid `rank`.
opts = { runValidators: true };
const err = await Character.findOneAndUpdate({}, update, opts).catch(
(err) => err
);
// '`Lollipop` is not a valid enum value for path `rank`.'
err.message;
err.name; // 'ValidationError'
*/
/*
let opts = { runValidators: true };
// Mongoose executes the below query without error
await Character.findOne({ rank: "Lollipop" }).setOptions(opts);
*/
/*
// Mongoose will let the below upsert through, which will store
// an invalid `rank` in the database.
const filter = { rank: "Lollipop" };
const update = { name: "test" };
const opts = { runValidators: true, upsert: true, new: true };
const doc = await Character.findOneAndUpdate(filter, update, opts);
doc.rank; // 'Lollipop'
*/
/*
// Insert an invalid doc in the database
const doc = { _id: new mongoose.Types.ObjectId(), rank: "Lollipop" };
await Character.collection.insertOne(doc);
// Below update succeeds, even though the document in the database
// has an invalid `rank`
await Character.updateOne({ _id: doc._id }, { name: "Test" });
*/
/*
const schema = Schema({
name: String,
age: Number,
rank: { type: String, validate: ageRankValidator },
});
function ageRankValidator(v) {
const message = "Captains must be at least 30";
assert(v !== "Captain" || this.age >= 30, message);
}
const Character = mongoose.model("Character", schema);
const rank = "Captain";
const doc = new Character({ name: "<NAME>", age: 29, rank });
const err = await doc.save().catch((err) => err);
// 'Character validation failed: rank: Captains must be at least 30'
err.message;
*/
function ageRankValidator(v) {
const message = "Captains must be at least 30";
if (this instanceof mongoose.Query) {
const update = this.getUpdate();
assert(v !== "Captain" || update.$set.age >= 30, message);
} else {
assert(v !== "Captain" || this.age >= 30, message);
}
}
const update = { age: 29, rank: "Captain" };
// The `context` option tells Mongoose to set the value of `this`
// in the validator to the query. Otherwise `this` will be `null`
const opts = { runValidators: true, context: "query" };
// Throws 'Validation failed: rank: Captains must be at least 30'
await Character.findOneAndUpdate({}, update, opts);
<file_sep>/06-Schema/trains-aggregations.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
const uri = ``;
const conn = await mongoose.createConnection(uri, { poolSize: 1 });
const Model = conn.model("Test", Schema({ name: String }));
await Model.create({ name: "test" });
// First, run a slow query that will take about 1 sec, but don't
// `await` on it, so you can execute a 2nd query in parallel.
const p = Model.find({ $where: "sleep(1000) || true" }).exec();
// Run a 2nd query that _should_ be fast, but isn't.
const startTime = Date.now();
await Model.findOne();
Date.now() - startTime; // Slightly more than 1000
<file_sep>/05-Populate/manual-populate.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const countrySchema = Schema({
name: String,
capital: { type: "ObjectId", ref: "City" },
});
const Country = mongoose.model("Country", countrySchema);
const City = mongoose.model("City", Schema({ name: String }));
const country = await Country.create({ name: "Switzerland" });
country.capital = new City("Bern");
country.capital.name; // 'Bern'
!!country.populated("capital"); // true
*/
/*
const Country = mongoose.model(
"Country",
Schema({
name: String,
cities: [{ type: mongoose.ObjectId, ref: "City" }],
})
);
const City = mongoose.model("City", Schema({ name: String }));
const country = await Country.create({ name: "Switzerland" });
country.cities = [new City("Bern"), new City("Basel")];
country.cities[0].name; // 'Bern'
!!country.populated("cities"); // true
*/
const country = await Country.create({ name: "Switzerland" });
const city = await City.create({ name: "Bern" });
// The 2nd doc isn't a city, so Mongoose depopulates the array.
country.cities = [city, country];
country.cities[0].name; // undefined
!!country.populated("cities"); // false
<file_sep>/01-getting-started/1.3-defining-a-schema.js
const mongoose = require("mongoose");
const { Schema, model } = mongoose;
require("./1.2-connecting-to-mongodb");
const productSchema = new Schema({
// A product has two properties: `name` and `price`
name: { type: String, lowercase: true },
price: Number,
});
// The `mongoose.model()` function has 2 required parameters:
// The 1st param is the model's name, a string
// The 2nd param is the schema
const Product = model("product", productSchema);
const addNewProduct = async () => {
const product = new Product({
name: "iPhone",
price: "800", // Note that this is a string, not a number
notInSchema: "foo",
});
await product.save();
};
addNewProduct();
<file_sep>/04-Middleware/document-middleware.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const schema = Schema({ name: String });
schema.pre("save", function () {
const condition = doc === this; // true
console.log(`doc === this : ${condition}`);
});
const Model = mongoose.model("Test", schema);
const doc = new Model({ name: "test" });
// When you call `doc.save()`, Mongoose calls your pre save middleware
// with `this` equal to `doc`.
await doc.save();
*/
/*
const schema = Schema({ name: String });
schema.post("save", function (res) {
let condition = res === this;
console.log(`res === this : ${condition}`); // true
condition = res === doc;
console.log(`res === doc : ${condition}`); // true
});
const Model = mongoose.model("Test", schema);
const doc = new Model({ name: "test" });
// When you call `doc.save()`, Mongoose calls your post save middleware
// with `res` equal to `doc`.
await doc.save();
*/
const schema = Schema({ name: String });
schema.post(["save", "validate", "remove"], function (res) {
let condition = res === this;
console.log(`res === this : ${condition}`); // true
condition = res === doc;
console.log(`res === doc : ${condition}`); // true
});
const Model = mongoose.model("Test", schema);
const doc = new Model({ name: "test" });
// Triggers post('validate') hook
await doc.validate();
// Triggers post('save') **and** post('validate') hook
await doc.save();
// Triggers post('remove') hook
await doc.remove();
<file_sep>/06-Schema/index-specificity.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
let userSchema = Schema({
firstName: String,
lastName: String,
test: String,
});
userSchema.index({ firstName: 1, lastName: 1 });
const User = mongoose.model("User", userSchema);
const firstName = "Agent";
const lastName = "Smith";
const add120kUser = async () => {
// Insert 120k + 1 documents. 2 documents are different.
const docs = [];
for (let i = 0; i < 120000 - 1; ++i) {
docs.push({ firstName, lastName });
}
docs.push({ firstName, lastName, test: "test" });
docs.push({ firstName, lastName: "Brown" });
await User.insertMany(docs);
};
const findOneUserWithIndex = async () => {
let res = await User.find({ firstName, lastName: "Brown" }).explain();
// { stage: 'IXSCAN', nReturned: 1, ... }
console.log(res[0].executionStats.executionStages.inputStage);
};
const findOneUserWithOutIndex = async () => {
// Only one result, but has to scan 120000 documents to get it!
const filter = { firstName, lastName, test: "test" };
res = await User.find(filter).explain();
// { stage: 'IXSCAN', nReturned: 120000, ... }
console.log(res[0].executionStats.executionStages.inputStage);
};
connectToDB();
add120kUser();
findOneUserWithIndex();
findOneUserWithOutIndex();
<file_sep>/01-getting-started/product.model.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
require("./1.2-connecting-to-mongodb");
const productSchema = new Schema({
sku: { type: String },
title: { type: String, lowercase: true },
price: Number,
});
const Product = model("product", productSchema);
const newProduct = {
sku: "lap1337",
title: "awesome laptop",
price: 3.99,
};
/*
// 1. Instantiate a model instance to create a new document
const addNewProduct = async () => {
const product = new Product(newProduct);
await product.save();
};
*/
/*
// 2. Use model class create method
const addNewProduct = async () => {
const productToCreate = await Product.create(newProduct);
return productToCreate;
};
*/
// addNewProduct();
/*
// using findOne
const findProduct = async () => {
try {
const productToFind = await Product.findOne({ sku: "lap1337" })
.lean()
.exec();
console.log(productToFind); // print newProduct
return productToFind;
} catch (e) {
console.error(e);
}
};
const productToFind = findProduct();
console.log(productToFind.then((product) => product)); // return Promise { <pending> } WHY ??
console.log(productToFind); // return Promise { <pending> } WHY ??
*/
// using findOne
const findProduct = async () => {
try {
const products = await Product.find().lean().exec();
const { sku, title, price } = products[0];
console.log({ sku, title, price }); // print newProduct
return products[0];
} catch (e) {
console.error(e);
}
};
const productToFind = findProduct();
// console.log(productToFind.then((product) => product)); // return Promise { <pending> } WHY ??
console.log(productToFind); // return Promise { <pending> } WHY ??
<file_sep>/02-core-concepts/2.2-Documents-Casting-Validation-Change-Tracking.js
const mongoose = require("mongoose");
const MyModel = mongoose.model("MyModel", new mongoose.Schema({}));
// `MyModel` is a class that extends from `mongoose.Model`, _not_
// an instance of `mongoose.Model`.
let condition = MyModel instanceof mongoose.Model; // false
console.log(`MyModel instanceof mongoose.Model ${condition}`);
condition = Object.getPrototypeOf(MyModel) === mongoose.Model; // true
console.log(`Object.getPrototypeOf(MyModel) === mongoose.Model ${condition}`);
//=============================================
const productSchema = new Schema({ name: String, price: Number });
const Product = model("product", productSchema);
//================================================
const connection = mongoose.createConnection(uri, connectionOptions);
const productSchema = new Schema({ name: String, price: Number });
const Product = connection.model("product", productSchema);
//===========================================
// `mongoose.model()` uses the default connection
mongoose.model("product", productSchema);
// So the below function call does the same thing
mongoose.connection.model("product", productSchema);
//========================================
const Product = connection.model("product", productSchema);
// `MyModel` is a class that extends from `mongoose.Model`, _not_
// an instance of `mongoose.Model`.
let condition = Product instanceof mongoose.Model;
console.log(`Product instanceof mongoose.Model ${condition}`); // false
condition = Object.getPrototypeOf(Product) === mongoose.Model; // true
console.log(`Object.getPrototypeOf(Product) === mongoose.Model ${condition}`); // true
<file_sep>/04-Middleware/error-handling-middleware.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const schema = Schema({ name: String, age: Number });
// This is normal post middleware.
schema.post("save", () => console.log("this wont print"));
// If a post middleware function takes exactly 3 parameters, Mongoose
// will treat it as error handling middleware.
schema.post("save", function errorHandler(err, doc, next) {
console.log("Error:", err.message);
next(err);
});
const Model = mongoose.model("UserModel", schema);
try {
// Prints "Error: UserModel validation failed..." because
// of the `errorHandler()` function
await Model.create({ age: "not a number" });
} catch (error) {
error.message; // "UserModel validation failed..."
}
*/
/*
// Errors in pre hooks will trigger error handling middleware
schema.pre("save", () => {
throw new Error("Oops!)");
});
// Wrapped function errors trigger error handling middleware
await Model.create({ age: "not a number" });
// Errors in post hooks also trigger error handling, but only if the
// error handler is defined after the hook that errors out.
schema.post("save", () => {
throw new Error("Oops!");
});
*/
const Model = mongoose.model("UserModel", schema);
schema.post("save", function errorHandler(err, doc, next) {
// By default, duplicate `_id` errors look like this:
// "E11000 duplicate key error collection: test.usermodels"
// Error handling middleware can make the error more readable
if (err.code === 11000) return next(Error("Duplicate _id"));
next(err);
});
const Model = mongoose.model("UserModel", schema);
const doc = await Model.create({ name: "test" });
await Model.create({ _id: doc._id }); // Throws "Duplicate _id"
<file_sep>/03-queries/update-operators.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const schema = Schema({ name: String, age: Number, rank: String });
const Character = mongoose.model('Character', schema);
await Character.create({ name: '<NAME>', age: 29 });
const filter = { name: '<NAME>' };
let update = { rank: 'Commander' };
const opts = { new: true };
let doc = await Character.findOneAndUpdate(filter, update, opts);
doc.rank; // 'Commander'
// By default, Mongoose wraps your update in `$set`, so the
// below update is equivalent to the previous update.
update = { $set: { rank: 'Captain' } };
doc = await Character.findOneAndUpdate(filter, update, opts);
doc.rank; // 'Captain'
*/
/*
const Character = mongoose.model(
"Character",
Schema({
name: { first: String, last: String },
age: Number,
rank: String,
})
);
const name = { first: "Will", last: "Riker" };
await Character.create({ name, age: 29, rank: "Commander" });
// Update `name.first` without touching `name.last`
const $set = { "name.first": "Thomas", rank: "Lieutenant" };
let doc = await Character.findOneAndUpdate({}, { $set }, { new: true });
doc.name.first; // 'Thomas'
doc.name.last; // 'Riker'
doc.rank; // 'Lieutenant'
*/
/*
const schema = Schema({ name: String, age: Number, rank: String });
const Character = mongoose.model("Character", schema);
await Character.create({ name: "<NAME>", age: 29 });
const filter = { name: "<NAME>" };
// Delete the `age` property
const update = { $unset: { age: 1 } };
const opts = { new: true };
let doc = await Character.findOneAndUpdate(filter, update, opts);
doc.age; // undefined
*/
/*
await Character.create({ name: "<NAME>", age: 29 });
let filter = { name: "<NAME>" };
// Set `rank` if inserting a new document
const update = { $setOnInsert: { rank: "Captain" } };
// If `upsert` option isn't set, `$setOnInsert` does nothing
const opts = { new: true, upsert: true };
let doc = await Character.findOneAndUpdate(filter, update, opts);
doc.rank; // undefined
filter = { name: "<NAME>" };
doc = await Character.findOne(filter);
doc; // null, so upsert will insert a new document
doc = await Character.findOneAndUpdate(filter, update, opts);
doc.name; // '<NAME>'
doc.rank; // 'Captain'
*/
/*
await Character.create({ name: "<NAME>", age: 29 });
const filter = { name: "<NAME>" };
const update = { $min: { age: 30 } };
const opts = { new: true, upsert: true };
let doc = await Character.findOneAndUpdate(filter, update, opts);
doc.age; // 29
update.$min.age = 28;
doc = await Character.findOneAndUpdate(filter, update, opts);
doc.age; // 28
*/
/*
// Increment `age` by 1 using `$inc`
const filter = { name: "<NAME>" };
let update = { $inc: { age: 1 } };
const opts = { new: true };
let doc = await Character.findOneAndUpdate(filter, update, opts);
doc.age; // 30
// Decrement `age` by 1
update.$inc.age = -1;
doc = await Character.findOneAndUpdate(filter, update, opts);
doc.age; // 29
// Multiply `age` by 2
update = { $mul: { age: 2 } };
doc = await Character.findOneAndUpdate(filter, update, opts);
doc.age; // 58
*/
/*
const schema = Schema({ title: String, tags: [String] });
const Post = mongoose.model("BlogPost", schema);
const title = "Introduction to Mongoose";
await Post.create({ title, tags: ["Node.js"] });
// Add 'MongoDB' to the blog post's list of tags
const update = { $push: { tags: "MongoDB" } };
const opts = { new: true };
let doc = await Post.findOneAndUpdate({ title }, update, opts);
doc.tags; // ['Node.js', 'MongoDB']
*/
/*
const title = 'Introduction to Mongoose';
await Post.create({ title, tags: ['Node.js'] });
// 'MongoDB' isn't in `tags`, so `$addToSet` behaves like `$push`
const update = { $addToSet: { tags: 'MongoDB' } };
const opts = { new: true };
let doc = await Post.findOneAndUpdate({ title }, update, opts);
doc.tags; // ['Node.js', 'MongoDB']
// Since 'MongoDB' is in `tags`, `$addToSet` will be a no-op.
doc = await Post.findOneAndUpdate({ title }, update, opts);
doc.tags; // ['Node.js', 'MongoDB']
*/
// Make sure to add `_id: false`, otherwise Mongoose adds a unique
// unique `_id` to every subdoc, and then `$addToSet` will always
// add a new doc.
const commentSchema = Schema({ user: String, comment: String }, { _id: false });
const schema = Schema({ comments: [commentSchema] });
const Post = mongoose.model("BlogPost", schema);
const comment = { user: "jpicard", comment: "Make it so!" };
await Post.create({ comments: [comment] });
const update = { $addToSet: { comments: comment } };
const opts = { new: true };
// Skips adding, the new and old comments are deeply equal
let doc = await Post.findOneAndUpdate({}, update, opts);
doc.comments.length; // 1
// Adds a new comment, because the `comment` property is different
update.$addToSet.comments.comment = "Engage!";
doc = await Post.findOneAndUpdate({}, update, opts);
doc.comments.length; // 2
// Adds a new comment, the new comment has different keys
delete update.$addToSet.comments.comment;
doc = await Post.findOneAndUpdate({}, update, opts);
doc.comments.length; // 3
<file_sep>/05-Populate/one2one.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const Country = mongoose.model(
"Country",
Schema({
name: String,
capital: { type: "ObjectId", ref: "City" },
})
);
const City = mongoose.model("City", Schema({ name: String }));
const dc = await City.create({ name: "Washington, D.C." });
const manila = await City.create({ name: "Manila" });
const [{ name }] = await Country.create([
{ name: "United States", capital: dc },
{ name: "Phillipines", capital: manila },
]);
const usa = await Country.findOne({ name }).populate("capital");
usa.capital.name; // 'Washington, D.C.'
*/
const schema = Schema({ name: String, capitalId: ObjectId });
schema.virtual("capital", {
ref: "City",
localField: "capitalId",
foreignField: "_id",
justOne: true,
});
const Country = mongoose.model("Country", schema);
const City = mongoose.model("City", Schema({ name: String }));
const oslo = await City.create({ name: "Oslo" });
const bern = await City.create({ name: "Bern" });
await Country.create({ name: "Norway", capitalId: oslo });
await Country.create({ name: "Switzerland", capitalId: bern });
let v = await Country.findOne({ name: "Norway" }).populate("capital");
v.capital.name; // 'Oslo'
<file_sep>/02-core-concepts/virtuals-json-stringify.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
// Opt in to Mongoose putting virtuals in `toJSON()` output
// for `JSON.stringify()`, and in `toObject()` output.
const options = { toJSON: { virtuals: true } };
const userSchema = Schema({ email: String }, options);
userSchema.virtual("domain").get(function () {
return this.email.slice(this.email.indexOf("@") + 1);
});
const User = model("user", userSchema);
const addNewUser = async () => {
const doc = await User.create({ email: "<EMAIL>" });
// { _id: ..., email: '<EMAIL>', domain: 'gmail.com' }
console.log(doc.toJSON());
// {"_id":...,"email":"<EMAIL>","domain":"gmail.com"}
console.log(JSON.stringify(doc));
};
connectToDB();
addNewUser();
*/
// -----------------------------------------
const myObject = {
toJSON: function () {
// Will print once when you call `JSON.stringify()`.
console.log("Called!");
return 42;
},
};
// `{"prop":42}`. That is because `JSON.stringify()` uses the result
// of the `toJSON()` function.
console.log(JSON.stringify({ prop: myObject }));
// configure the toJSON schema option globally
mongoose.set("toJSON", { virtuals: true });
<file_sep>/02-core-concepts/2.3-schemas-schematypes.js
const mongoose = require("mongoose");
const { Schema, SchemaType, model } = mongoose;
const schema = Schema({ name: String, age: Number });
console.log(Object.keys(schema.paths)); // ['name', 'age', '_id']
console.log(schema.path("name")); // SchemaString { path: 'name', ... }
let condition = schema.path("name") instanceof SchemaType; // true
console.log(`schema.path("name") instanceof SchemaType is ${condition}`);
// The `SchemaString` class inherits from `SchemaType`.
condition = schema.path("name") instanceof Schema.Types.String; // true
console.log(
`schema.path("name") instanceof Schema.Types.String is ${condition}`
);
console.log(schema.path("age")); // SchemaNumber { path: 'age', ... }
condition = schema.path("age") instanceof SchemaType; // true
console.log(`schema.path("age") instanceof SchemaType is ${condition}`);
condition = schema.path("age") instanceof Schema.Types.Number; // true
console.log(
`schema.path("age") instanceof Schema.Types.Number is ${condition}`
);
<file_sep>/02-core-concepts/virtuals.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
const userSchema = Schema({ email: String });
userSchema.virtual("domain").get(function () {
return this.email.slice(this.email.indexOf("@") + 1);
});
const User = model("user", userSchema);
const addNewUser = async () => {
let doc = await User.create({ email: "<EMAIL>" });
console.log(doc.domain); // 'gmail.com'
// Mongoose ignores setting virtuals that don't have a setter
doc.set({ email: "<EMAIL>", domain: "foo" });
console.log(doc.domain); // 'test.com
};
connectToDB();
addNewUser();
await User.create({ email: "<EMAIL>" });
// `doc` will be null, because the document in the database
// does **not** have a `domain` property
const doc = await User.findOne({ domain: "gmail.com" });
<file_sep>/06-Schema/index-unique.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
let schema = Schema({
email: {
type: String,
unique: true,
},
});
const User = mongoose.model("User", schema);
const addUser = async () => {
await User.init();
// Unique index means MongoDB throws an 'E11000 duplicate key
// error' if there are two documents with the same `email`.
const err = await User.create([
{ email: "<EMAIL>" },
{ email: "<EMAIL>" },
]).catch((err) => err);
console.log(err.message); // 'E11000 duplicate key error...'
};
connectToDB();
addUser();
*/
let schema = Schema({ firstName: String, lastName: String });
// A compound unique index on { firstName, lastName }
schema.index({ firstName: 1, lastName: 1 }, { unique: true });
const indexes = schema.indexes();
console.log(indexes.length); // 1
console.log(indexes[0][0]); // { firstName: 1, lastName: 1 }
console.log(indexes[0][1].unique); // true
<file_sep>/02-core-concepts/adv-getters-setters.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId } = mongoose;
const assert = require("assert/strict");
/*
const str = "5d124083fc741d44eca250fd";
const schema = Schema({ objectid: ObjectId });
const Model = model("ObjectIdTest", schema);
const doc1 = new Model({ objectid: str });
const doc2 = new Model({ objectid: str });
// Mongoose casted the string `str` to an ObjectId
console.log(`typeof doc1.objectid : ${typeof doc1.objectid}`); // 'object'
let condition = doc1.objectid instanceof Types.ObjectId; // true
console.log(`doc1.objectid instanceof Types.ObjectId : ${condition}`);
condition = doc1.objectid === doc2.objectid; // false
console.log(`doc1.objectid === doc2.objectid : ${condition}`);
condition = doc1.objectid == doc2.objectid; // false
console.log(`doc1.objectid == doc2.objectid : ${condition}`);
condition = doc1.objectid.toString() == doc2.objectid.toString(); // true
console.log(
`doc1.objectid.toString() == doc2.objectid.toString() : ${condition}`
);
// */
// -------------------
/*
const str = "5d124083fc741d44eca250fd";
const s = Schema({ objectid: ObjectId }, { _id: false });
// Add a custom getter that converts ObjectId values to strings
s.path("objectid").get((v) => v.toString());
const Model = model("ObjectIdTest", s);
const doc1 = new Model({ objectid: str });
const doc2 = new Model({ objectid: str });
// Mongoose now converts `objectid` to a string for you
console.log(`typeof doc1.objectid : ${typeof doc1.objectid}`); // 'string'
// The raw value stored in MongoDB is still an ObjectId
let theType = typeof doc1.get("objectid", null, { getters: false }); // 'object'
console.log(
`typeof doc1.get("objectid", null, { getters: false }) : ${theType}`
);
let condition = doc1.objectid === doc2.objectid; // true
console.log(`doc1.objectid === doc2.objectid : ${condition}`);
condition = doc1.objectid == doc2.objectid; // true
console.log(`doc1.objectid == doc2.objectid : ${condition}`);
assert.deepEqual(doc1.toObject(), doc2.toObject()); // passes
// */
/*
const accountSchema = Schema({ balance: mongoose.Decimal128 });
const Account = model("Account", accountSchema);
await Account.create({ balance: 0.1 });
await Account.updateOne({}, { $inc: { balance: 0.2 } });
const account = await Account.findOne();
account.balance.toString(); // 0.3
// The MongoDB Node driver currently doesn't support
// addition and subtraction with Decimals
account.balance + 0.5;
*/
/*
const accountSchema = Schema({
balance: {
type: mongoose.Decimal128,
// Convert the raw decimal value to a native JS number
// when accessing the `balance` property
get: (v) => parseFloat(v.toString()),
// When setting the `balance` property, round to 2
// decimal places and convert to a MongoDB decimal
set: (v) => mongoose.Types.Decimal128.fromString(v.toFixed(2)),
},
});
const Account = model("Account", accountSchema);
const account = new Account({ balance: 0.1 });
account.balance += 0.2;
console.log(account.balance); // 0.3
*/
<file_sep>/04-Middleware/query-middleware.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const schema = Schema({ name: String, age: Number });
// Attach pre('find') middleware
schema.pre("find", function () {
console.log("Find", this.getQuery());
});
const Model = mongoose.model("Model", schema);
// Doesn't print anything
const query = Model.find({ age: { $lte: 30 } });
// Prints "Find { age: { $lte: 30 } }" from the `find()` middleware
await query;
*/
/*
const schema = Schema({ name: String, age: Number });
schema.pre("findOneAndUpdate", () => console.log("update"));
schema.post("findOne", () => console.log("findOne"));
const Model = mongoose.model("Model", schema);
// Doesn't trigger any middleware
const query = Model.findOneAndUpdate({}, { name: "test" });
// Prints "update"
await query.exec();
// Prints "findOne"
await Model.findOne({});
*/
/*
const schema = Schema({ name: String, age: Number });
schema.pre("find", () => console.log("find"));
schema.pre("updateOne", () => console.log("updateOne"));
const Model = mongoose.model("Model", schema);
const query = Model.find({ name: "<NAME>" });
query.updateOne({}, { age: 70 });
query.op; // 'updateOne'
// Triggers `updateOne` middleware, **not** `find` middleware.
await query.exec();
*/
/*
const schema = Schema({ name: String, age: Number });
schema.pre("findOne", () => console.log("findOne"));
const Model = mongoose.model("Model", schema);
// Prints "findOne". There is no middleware for `findById()`.
await Model.findById(new mongoose.Types.ObjectId());
*/
/*
const schema = Schema({ name: String, age: Number });
schema.pre("updateOne", function () {
console.log("updateOne", this.constructor.name);
});
const Model = mongoose.model("UserModel", schema);
const doc = await Model.create({ name: "<NAME>", age: 59 });
// Prints "updateOne model" followed by "updateOne Query".
// `Document#updateOne()` triggers both document and query hooks
await doc.updateOne({ age: 60 });
// Prints "updateOne Query"
await Model.updateOne({ _id: doc._id }, { age: 61 });
*/
/*
const schema = Schema({ name: String, age: Number });
// The `options.document` parameter tells Mongoose to call
// 'updateOne' hooks as both document and query middleware
schema.pre("updateOne", { document: true }, function () {
console.log("updateOne", this.constructor.name);
});
const Model = mongoose.model("UserModel", schema);
const doc = await Model.create({ name: "<NAME>", age: 59 });
// Prints "updateOne model" followed by "updateOne Query"
await doc.updateOne({ age: 60 });
*/
/*
const schema = Schema({ name: String, age: Number });
// Only call this middleware function as document middleware for
// updateOne, not as query middleware.
schema.post("updateOne", { document: true, query: false }, function () {
console.log("updateOne", this.constructor.name);
});
const Model = mongoose.model("UserModel", schema);
const doc = await Model.create({ name: "<NAME>", age: 59 });
// Prints "updateOne model"
await doc.updateOne({ age: 60 });
*/
/*
const schema = Schema({ name: String, age: Number });
// By default, `schema.pre('remove')` only registers document
// middleware, **not** query middleware.
schema.pre("remove", function () {
console.log("remove", this.constructor.name);
});
const Model = mongoose.model("UserModel", schema);
const doc = await Model.create({ name: "<NAME>", age: 59 });
// Prints "remove model"
await doc.remove({ age: 60 });
*/
<file_sep>/07-app-structure/schema-pattern.js
/*
const { Schema } = require("mongoose");
module.exports = Schema({
name: String,
email: String,
});
*/
/*
const mongoose = require("mongoose");
mongoose.model("User", require("./User.schema.js"));
mongoose.model("Photo", require("./Photo.schema.js"));
let opts = { useUnifiedTopology: true, useNewUrlParser: true };
mongoose.connect(process.env.MONGODB_URI, opts);
module.exports = mongoose.connection;
*/
const db = require("path/to/models");
// Get the `User` model and use it
const User = db.model("User");
User.findOne().then((user) => console.log(user));
<file_sep>/05-Populate/intro.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const Group = mongoose.model("Group", Schema({ name: String }));
const Person = mongoose.model(
"Person",
Schema({
name: String,
group: {
type: mongoose.ObjectId,
// `ref` means `group` references the 'Group' model
ref: "Group",
},
})
);
const jedi = await Group.create({ name: "Jedi Order" });
await Person.create({ name: "<NAME>", group: jedi._id });
const doc = await Person.findOne().populate("group");
doc.group.name; // 'Jedi Order'
*/
/*
const Group = mongoose.model(
"Group",
Schema({
_id: Number,
name: String,
})
);
const Person = mongoose.model(
"Person",
Schema({
name: String,
group: { type: Number, ref: "Group" },
})
);
await Group.create({ _id: 66, name: "Jedi Order" });
await Person.create({ name: "<NAME>", group: 66 });
const doc = await Person.findOne().populate("group");
doc.group.name; // 'Jedi Order'
*/
/*
const Group = mongoose.model(
"Group",
Schema({
_id: Number,
name: String,
})
);
const Person = mongoose.model(
"Person",
Schema({
name: String,
// `ref` can also be a Mongoose model as opposed to a string
group: { type: Number, ref: Group },
})
);
await Group.create({ _id: 66, name: "Jedi Order" });
await Person.create({ name: "<NAME>", group: 66 });
const doc = await Person.findOne().populate("group");
doc.group.name; // 'Jedi Order'
*/
/*
const Person = mongoose.model(
"Person",
Schema({
name: String,
groupKind: String,
// `ref` can also be a function that takes the document being
// populated as a parameter. That means you can make `ref`
// conditional based on the document's properties.
group: { type: Number, ref: (doc) => doc.groupKind },
})
);
*/
const Group = mongoose.model(
"Group",
Schema({
_id: Number,
name: String,
})
);
const Person = mongoose.model(
"Person",
Schema({
name: String,
groupKind: String,
group: { type: Number, ref: (doc) => doc.groupKind },
})
);
const companySchema = Schema({ _id: Number, name: String });
const Company = mongoose.model("Company", companySchema);
await Group.create({ _id: 66, name: "Jedi Order" });
await Company.create({ _id: 5, name: "Cloud City Mining" });
await Person.create([
{ name: "<NAME>", groupKind: "Group", group: 66 },
{ name: "<NAME>", groupKind: "Company", group: 5 },
]);
const docs = await Person.find().sort({ name: 1 }).populate("group");
// The `group` property now contains multiple unrelated models.
docs[0].group instanceof Company; // true
docs[1].group instanceof Group; // true
docs[0].group.name; // 'Cloud City Mining'
docs[1].group.name; // 'Jedi Order'
<file_sep>/05-Populate/many2many.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const Group = mongoose.model(
"Group",
Schema({
name: String,
members: [{ type: mongoose.ObjectId, ref: "Person" }],
})
);
const Person = mongoose.model("Person", Schema({ name: String }));
const luke = await Person.create({ name: "<NAME>" });
const han = await Person.create({ name: "<NAME>" });
// Each `Group` has multiple members, and the Luke Skywalker
// document is part of multiple groups.
await Group.create({ name: "Jedi Order", members: [luke] });
const name = "Rebel Alliance";
await Group.create({ name, members: [luke, han] });
const group = await Group.findOne({ name }).populate("members");
group.members[0].name; // '<NAME>'
group.members[1].name; // '<NAME>'
*/
/*
const Group = mongoose.model(
"Group",
Schema({
name: String,
members: [{ type: mongoose.ObjectId, ref: "Person" }],
})
);
const personSchema = Schema({ name: String });
personSchema.virtual("groups", {
ref: "Group",
localField: "_id",
// `populate()` is smart enough to drill into `foreignField` if
// `foreignField` is an array
foreignField: "members",
});
const Person = mongoose.model("Person", personSchema);
const doc = await Person.findOne({ name: "<NAME>" }).populate({
path: "groups",
options: { sort: { name: 1 } },
});
doc.groups[0].name; // 'Jedi Order'
doc.groups[1].name; // 'Rebel Alliance'
*/
/*
const userSchema = Schema({
// Won't work well if a user has millions of followers - might
// run into the 16 MB document size limit.
followers: [
{
type: mongoose.ObjectId,
ref: "User",
},
],
});
*/
// `Follow` represents `follower` following `followee`.
// No risk of `Follow` documents growing to 16MB.
const Follow = mongoose.model(
"Follow",
Schema({
follower: { type: ObjectId, ref: "User" },
followee: { type: ObjectId, ref: "User" },
})
);
const userSchema = Schema({ name: String });
userSchema.virtual("followers", {
ref: "Follow",
localField: "_id",
foreignField: "followee",
});
const User = mongoose.model("User", userSchema);
const user1 = await User.create({ name: "<NAME>" });
const user2 = await User.create({ name: "<NAME>" });
const user3 = await User.create({ name: "<NAME>" });
await Follow.create({ follower: user2, followee: user1 });
await Follow.create({ follower: user3, followee: user1 });
// Find all of Mark Hamill's followers by populating
// `followers` and then `followers.follower`
const populate = { path: "follower" };
const opts = { path: "followers", populate };
let doc = await User.findOne({ name: /Hamill/ }).populate(opts);
doc.followers[0].follower.name; // '<NAME>'
doc.followers[1].follower.name; // '<NAME>'
<file_sep>/05-Populate/one2many.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const countrySchema = Schema({ name: String });
const Country = mongoose.model("Country", countrySchema);
const City = mongoose.model(
"City",
Schema({
name: String,
country: { type: mongoose.ObjectId, ref: "Country" },
})
);
const country = await Country.create({ name: "United States" });
const { name } = await City.create({ name: "NYC", country });
await City.create({ name: "Miami", country });
const nyc = await City.findOne({ name }).populate("country");
nyc.country.name; // 'United States'
*/
/*
const countrySchema = Schema({ name: String });
countrySchema.virtual("cities", {
ref: "City",
localField: "_id",
foreignField: "country",
justOne: false,
});
const Country = mongoose.model("Country", countrySchema);
const schema = Schema({ name: String, country: "ObjectId" });
const City = mongoose.model("City", schema);
let usa = await Country.create({ name: "United States" });
let canada = await Country.create({ name: "Canada" });
await City.create({ name: "New York", country: usa });
await City.create({ name: "Miami", country: usa });
await City.create({ name: "Vancouver", country: canada });
usa = await Country.findById(usa._id).populate("cities");
usa.cities.map((city) => city.name); // ['New York', 'Miami']
*/
const countrySchema = Schema({
name: String,
// You can also represent one-to-many as an array of ObjectIds
cities: [{ type: ObjectId, ref: "City" }],
});
const Country = mongoose.model("Country", countrySchema);
const City = mongoose.model("City", Schema({ name: String }));
<file_sep>/04-Middleware/Save-triggers-validate.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const schema = Schema({ name: String });
schema.pre("validate", () => console.log("pre validate"));
const Model = mongoose.model("Test", schema);
const doc = new Model({ name: "test" });
// Prints "pre validate"
await doc.save();
*/
const schema = Schema({ name: String });
schema.pre("validate", () => console.log("pre validate"));
schema.post("validate", () => console.log("post validate"));
schema.pre("save", () => console.log("pre save"));
schema.post("save", () => console.log("post save"));
const Model = mongoose.model("Test", schema);
const doc = new Model({ name: "test" });
// Prints
// "pre validate",
// "post validate",
// "pre save",
// "post save"
await doc.save();
<file_sep>/05-Populate/ref-arrays.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const Group = mongoose.model(
"Group",
Schema({
name: String,
// `members` is an array of ObjectIds with `ref = 'Person'`
members: [{ type: mongoose.ObjectId, ref: "Person" }],
})
);
let Person = mongoose.model("Person", Schema({ name: String }));
const luke = await Person.create({ name: "<NAME>" });
await Group.create({ name: "Jedi Order", members: [luke._id] });
const jedi = await Group.findOne().populate("members");
jedi.members[0] instanceof Person; // true
jedi.members[0].name; // '<NAME>'
*/
/*
const Group = mongoose.model(
"Group",
Schema({
name: String,
members: [
{
person: { type: mongoose.ObjectId, ref: "Person" },
rank: String,
},
],
})
);
const luke = await Person.create({ name: "<NAME>" });
const members = [{ person: luke._id, rank: "Jedi Knight" }];
await Group.create({ name: "Jedi Order", members });
// `populate()` can "drill down" into document arrays. It loops
// though each element in `members` and populates the `person` path.
const jedi = await Group.findOne().populate("members.person");
jedi.members[0].rank; // 'Jedi Knight'
jedi.members[0].person.name; // '<NAME>'
*/
/*
await Group.create({ _id: 66, name: "Jedi Order" });
await Person.create({ name: "<NAME>", group: 66 });
const doc = await Person.findOne().populate({ path: "group" });
doc.group.name; // 'Jedi Order'
*/
/*
const groupSchema = Schema({ _id: Number, name: String });
const Group = mongoose.model("Group", groupSchema);
const Person = mongoose.model(
"Person",
Schema({
name: String,
// Note that 'ref' points to a model that isn't 'Group'
group: { type: Number, ref: "OtherModel" },
})
);
await Group.create({ _id: 66, name: "Jedi Order" });
await Person.create({ name: "<NAME>", group: 66 });
// The `model` option overrides the model Mongoose populates
const doc = await Person.findOne().populate({
path: "group",
model: Group,
});
doc.group.name; // 'Jedi Order'
*/
/*
const Group = mongoose.model(
"Group",
Schema({
name: String,
members: [{ type: mongoose.ObjectId, ref: "Person" }],
})
);
let personSchema = Schema({ name: String, isDeleted: Boolean });
const Person = mongoose.model("Person", personSchema);
const members = await Person.create([
{ name: "<NAME>" },
{ name: "<NAME>", isDeleted: true },
]);
const name = "Jedi Order";
await Group.create({ name, members });
// Mongoose doesn't know to filter out documents with `isDeleted`
let doc = await Group.findOne({ name }).populate("members");
doc.members.length; // 2
doc.members[1].name; // '<NAME>'
// You can use `match` to filter out docs with `isDeleted` set
const match = { isDeleted: { $ne: true } };
const path = "members";
doc = await Group.findOne({ name }).populate({ path, match });
doc.members.length; // 1
doc.members[0].name; // '<NAME>'
*/
/*
const people = await Person.create([
{ name: "<NAME>" },
{ name: "<NAME>" },
{ name: "Yoda" },
{ name: "<NAME>" },
]);
await Group.create({ name: "Jedi Order", members: people });
const path = "members";
const opts = { path, sort: { name: 1 }, skip: 1, limit: 2 };
const doc = await Group.findOne().populate(opts);
// ['<NAME>', '<NAME>']
doc.members.map((doc) => doc.name);
*/
/*
const Group = mongoose.model(
"Group",
Schema({
name: String,
leader: { type: mongoose.ObjectId, ref: "Person" },
people: [{ type: mongoose.ObjectId, ref: "Person" }],
})
);
const mace = await Person.create({ name: "<NAME>" });
const adi = await Person.create({ name: "<NAME>" });
const people = [mace, adi];
await Group.create({ name: "Jedi Order", leader: mace, people });
let doc = await Group.findOne().populate(["leader", "people"]);
doc.leader.name; // '<NAME>'
doc.people.map((doc) => doc.name); // ['<NAME>', '<NAME>']
*/
const Group = mongoose.model(
"Group",
Schema({
name: String,
leader: { type: mongoose.ObjectId, ref: "Person" },
people: [{ type: mongoose.ObjectId, ref: "Person" }],
})
);
const schema = Schema({ name: String, age: Number });
const Person = mongoose.model("Person", schema);
let mace = await Person.create({ name: "<NAME>", age: 53 });
let yoda = await Person.create({ name: "Yoda", age: 90 });
let anakin = await Person.create({ name: "<NAME>" });
const people = [mace, yoda, anakin];
await Group.create({ name: "Jedi Order", leader: mace, people });
const match = { age: { $gte: 80 } };
const opts = ["leader", { path: "people", match }];
const doc = await Group.findOne().populate(opts);
doc.leader.name; // '<NAME>'
doc.people.map((doc) => doc.name); // ['Yoda']
<file_sep>/05-Populate/populating-across-databases.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const host = "mongodb://localhost:27017";
const db1 = await mongoose.createConnection(`${host}/db1`);
const db2 = await mongoose.createConnection(`${host}/db2`);
const M1 = db1.model("Test", Schema({ name: String }));
// Note that `ref` below is a **Model**, not a string!
const M2 = db2.model(
"Test",
Schema({
name: String,
doc: { type: mongoose.ObjectId, ref: Model1 },
})
);
const doc1 = await M1.create({ name: "model 1" });
await M2.create({ name: "model 2", doc: doc1._id });
const doc2 = await M2.findOne().populate("doc");
doc2.doc.name; // model 1
*/
/*
const schema = Schema({
// If populated, `user` will either be a document or `null`
user: { type: mongoose.ObjectId, ref: "User" },
// If `populated`, `friends` will be an array of documents
friends: [{ type: mongoose.ObjectId, ref: "User" }],
});
*/
const groupSchema = Schema({
leaderId: mongoose.ObjectId,
memberIds: [mongoose.ObjectId],
});
const ref = "Person";
const foreignField = "_id";
// If populated, `leader` will be a document, or `null` if no
// document was found, because `justOne` is true.
groupSchema.virtual("leader", {
ref,
localField: "leaderId",
foreignField,
justOne: true,
});
// If populated, `members` will be an array of zero or more
// documents, because `justOne` is false.
groupSchema.virtual("members", {
ref,
localField: "memberIds",
foreignField,
justOne: false,
});
<file_sep>/03-queries/query-operations.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
await Model.create([
{ name: "<NAME>", age: 59 },
{ name: "<NAME>", age: 29 },
{ name: "<NAME>", age: 29 },
]);
const filter = { age: { $lt: 30 } };
let res = await Model.find(filter);
res[0].name; // '<NAME>'
res[1].name; // '<NAME>'
res = await Model.findOne(filter);
res.name; // '<NAME>'
res = await Model.countDocuments(filter);
res; // 2
*/
/*
await Model.insertMany([
{ name: "<NAME>", age: 59 },
{ name: "<NAME>", age: 29 },
{ name: "<NAME>", age: 29 },
]);
const filter = { age: { $lt: 30 } };
let res = await Model.deleteOne(filter);
res.deletedCount; // 1
await Model.create({ name: "<NAME>", age: 29 });
res = await Model.deleteMany(filter);
res.deletedCount; // 2
await Model.insertMany([
{ name: "<NAME>", age: 29 },
{ name: "<NAME>", age: 29 },
]);
// `remove()` deletes all docs that match `filter` by default
res = await Model.remove(filter);
res.deletedCount; // 2
*/
/*
const schema = Schema({ name: String, age: Number, rank: String });
const Model = mongoose.model("Model", schema);
await Model.insertMany([
{ name: "<NAME>", age: 59 },
{ name: "<NAME>", age: 29 },
{ name: "<NAME>", age: 29 },
]);
const filter = { age: { $lt: 30 } };
const update = { rank: "Commander" };
// `updateOne()`
let res = await Model.updateOne(filter, update);
res.nModified; // 1
let docs = await Model.find(filter);
docs[0].rank; // 'Commander'
docs[1].rank; // undefined
// `updateMany()`
res = await Model.updateMany(filter, update);
res.nModified; // 2
docs = await Model.find(filter);
docs[0].rank; // 'Commander'
docs[1].rank; // 'Commander'
// `update()` behaves like `updateOne()` by default
res = await Model.update(filter, update);
res.nModified; // 1
*/
/*
const filter = { age: { $lt: 30 } };
const replacement = { name: "<NAME>", rank: "Commander" };
// Sets `rank`, unsets `age`
let res = await Model.replaceOne(filter, replacement);
res.nModified; // 1
let docs = await Model.find({ name: "<NAME>" });
!!docs[0]._id; // true
docs[0].name; // '<NAME>'
docs[0].rank; // 'Commander'
docs[0].age; // undefined
*/
/*
const filter = { name: "<NAME>" };
const update = { rank: "Commander" };
// MongoDB will return the matched doc as it was **before**
// applying `update`
let doc = await Model.findOneAndUpdate(filter, update);
doc.name; // '<NAME>'
doc.rank; // undefined
const replacement = { name: "<NAME>", rank: "Commander" };
doc = await Model.findOneAndReplace(filter, replacement);
// `doc` still has an `age` key, because `findOneAndReplace()`
// returns the document as it was before it was replaced.
doc.rank; // 'Commander'
doc.age; // 29
// Delete the doc and return the doc as it was before the
// MongoDB server deleted it.
doc = await Model.findOneAndDelete(filter);
doc.name; // '<NAME>'
doc.rank; // 'Commander'
doc.age; // undefined
*/
/*
const filter = { name: "<NAME>" };
const update = { rank: "Commander" };
const options = { new: true };
// MongoDB will return the matched doc **after** the update
// was applied if you set the `new` option
let doc = await Model.findOneAndUpdate(filter, update, options);
doc.name; // '<NAME>'
doc.rank; // 'Commander'
const replacement = { name: "<NAME>", rank: "Commander" };
doc = await Model.findOneAndReplace(filter, replacement, options);
doc.rank; // 'Commander'
doc.age; // void 0
*/
/*
// Return an array containing the distinct values of the `age`
// property. The values in the array can be in any order.
let values = await Model.distinct("age");
values.sort(); // [29, 59]
const filter = { age: { $lte: 29 } };
values = await Model.distinct("name", filter);
values.sort(); // ['<NAME>', '<NAME>']
*/
// Unlike `countDocuments()`, `estimatedDocumentCount()` does **not**
// take a `filter` parameter. It only returns the number of documents
// in the collection.
const count = await Model.estimatedDocumentCount();
count; // 3
<file_sep>/02-core-concepts/casting.js
const mongoose = require("mongoose");
const { Schema, model } = mongoose;
require("../01-getting-started/1.2-connecting-to-mongodb");
// const schema = Schema({ name: String, age: Number });
// const MyModel = model("MyModel", schema);
// const doc = new MyModel({});
// doc.age = "not a number";
// // Throws CastError: Cast to Number failed for value
// // "not a number" at path "age"
// doc.save();
//====================================================
/*
const schema = Schema({ name: String, age: Number });
const Person = mongoose.model("Person", schema);
const doc = new Person({ name: "<NAME>", age: 59 });
doc.age = null;
doc.name = undefined;
// Succeeds, because Mongoose casting lets `null` and `undefined`.
// `name` and `age` will _both_ be `null` in the database.
await doc.save();
*/
//====================================================
/*
const personSchema = Schema({ name: String, age: Number });
const Student = model("student", schema);
const doc = new Student({});
doc.age = "NaN";
// Throws CastError: Cast to Number failed for value
// "not a number" at path "age"
await doc.save();
*/
//====================================================
const productSchema = new Schema({ name: String, price: Number });
const Product = model("product", productSchema);
// MongoDB Node.js driver does not support undefined
// const newProduct = Product.create({ name: null, price: undefined });
const newProduct = Product.create({ name: null, price: null });
const foundProduct = Product.findOne().lean().exec();
console.log(foundProduct); // returns Promise { <pending> }
<file_sep>/02-core-concepts/mongoose-global-multiple-connections.js
// const mongoose = require("mongoose");
// const { Schema, Types, model, ObjectId } = mongoose;
// const {
// connectToDB,
// } = require("../01-getting-started/1.2-connecting-to-mongodb");
// // Mongoose exports an instance of the `Mongoose` class
let condition = mongoose instanceof mongoose.Mongoose; // true
console.log(`mongoose instanceof mongoose.Mongoose : ${condition}`);
/*
const { Mongoose } = require("mongoose");
const mongoose1 = new Mongoose();
const mongoose2 = new Mongoose();
mongoose1.set("toJSON", { virtuals: true });
mongoose1.get("toJSON"); // { virtuals: true }
mongoose2.get("toJSON"); // null
*/
/*
const mongoose = require("mongoose");
const mongoose1 = new mongoose.Mongoose();
const mongoose2 = new mongoose.Mongoose();
let instance = mongoose1.connection instanceof mongoose.Connection; // true
console.log(
`mongoose1.connection instanceof mongoose.Connection : ${instance}`
);
instance = mongoose2.connection instanceof mongoose.Connection; // true
console.log(
`mongoose2.connection instanceof mongoose.Connection : ${instance}`
);
const length = mongoose1.connections.length; // 1
console.log(`mongoose1.connections.length : ${length}`);
mongoose1.connections[0] === mongoose1.connection; // true
let readyState = mongoose1.connection.readyState; // 0, 'disconnected'
console.log(`mongoose1.connection.readyState : ${readyState}`);
mongoose1.connect("mongodb://localhost:27017/test", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
readyState = mongoose1.connection.readyState; // 2, 'connecting'
console.log(`mongoose1.connection.readyState : ${readyState}`);
*/
/*
const mongoose = require("mongoose");
const mongoose1 = new mongoose.Mongoose();
const conn = mongoose1.createConnection("mongodb://localhost:27017/test", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const length = mongoose1.connections.length; // 2
console.log(`mongoose1.connections.length : ${length}`);
let condition = mongoose1.connections[1] === conn; // true
console.log(`mongoose1.connections[1] === conn : ${condition}`);
*/
const mongoose = require("mongoose");
const conn1 = mongoose.createConnection("mongodb://localhost:27017/db1", {
useNewUrlParser: true,
});
const conn2 = mongoose.createConnection("mongodb://localhost:27017/db2", {
useNewUrlParser: true,
});
// Will store data in the 'db1' database's 'tests' collection
const Model1 = conn1.model("Test", mongoose.Schema({ name: String }));
// Will store data in the 'db2' database's 'tests' collection
const Model2 = conn2.model("Test", mongoose.Schema({ name: String }));
<file_sep>/02-core-concepts/change-tracking.js
const mongoose = require("mongoose");
const { Schema, model } = mongoose;
const MyModel = model(
"MyModel",
Schema({
name: String,
age: Number,
})
);
const doc = new MyModel({});
doc.name = "<NAME>";
doc.age = 27;
await doc.save(); // Persist `doc` to MongoDB
// Mongoose loads the document from MongoDB and then _hydrates_ it
// into a full Mongoose document.
const doc = await MyModel.findOne();
doc.name; // "<NAME>"
doc.name = "<NAME>";
doc.modifiedPaths(); // ['name']
// `save()` only sends updated paths to MongoDB. Mongoose doesn't
// send `age`.
await doc.save();
<file_sep>/06-Schema/index-define.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
// `schema` has 2 indexes: one on `name`, and one on `email`.
const schema = new Schema({
name: { type: String, index: true },
email: { type: String, index: true },
});
*/
const schema = new Schema({ name: String, email: String });
// Add 2 separate indexes to `schema`
schema.index({ name: 1 });
schema.index({ email: 1 });
<file_sep>/07-app-structure/module-pattern.js
/*
const mongoose = require("mongoose");
module.exports = mongoose.model(
"User",
mongoose.Schema({
name: String,
email: String,
})
);
*/
/*
const mongoose = require("mongoose");
require("./connect");
module.exports = mongoose.model(
"User",
mongoose.Schema({
name: String,
email: String,
})
);
*/
const opts = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
require("mongoose")
.connect(process.env.MONGODB_URI, opts)
.catch((err) => {
// If there's an error connecting to MongoDB, throw an uncaught error
// that kills the process.
process.nextTick(() => {
throw err;
});
});
<file_sep>/01-getting-started/1.4-storing-and-querying-documents.js
const mongoose = require("mongoose");
const { Schema, model } = mongoose;
require("./1.2-connecting-to-mongodb");
const productSchema = new Schema({
// A product has two properties: `name` and `price`
name: { type: String, lowercase: true },
price: Number,
});
// The `mongoose.model()` function has 2 required parameters:
// The 1st param is the model's name, a string
// The 2nd param is the schema
const Product = model("product", productSchema);
const addNewProduct = async () => {
const productToCreate = await Product.create({
name: "honor 7c",
price: "280", // Note that this is a string, not a number
notInSchema: "foo",
});
return productToCreate;
};
const getProduct = async () => {
const productToFind = await Product.findOne().lean().exec();
return productToFind;
};
const getProductList = async () => {
const productToFind = await Product.find({}).lean().exec();
return productToFind;
};
// connectToDB();
// addNewProduct();
// console.log(getProduct());
// const result = await getProductList();
// console.log(getProductList());
// let product = await Product.findOne();
// product.name; // "iPhone"
// product.price; // 800
// console.log(product);
// const products = await Product.find();
// product = products[0];
// product.name; // "iPhone"
// product.price; // 800
// console.log(product);
<file_sep>/03-queries/query-execution.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const schema = Schema({ name: String, age: Number });
const Model = model("Model", schema);
const query = Model.find({ age: { $lte: 30 } });
let condition = query instanceof Query; // true
console.log(`query instanceof Query : ${condition}`);
*/
/*
const query = Model.findOne();
// Execute the query 3 times, in 3 different ways
await query; // 1
query.then((res) => {}); // 2
await query.exec(); // 3
*/
// Chaining makes it easier to visually break up complex updates
await Model.find({ name: "<NAME>" }).updateOne({}, { rank: "Commander" });
// Equivalent, without using chaining syntax
await Model.updateOne({ name: "<NAME>" }, { rank: "Commander" });
<file_sep>/06-Schema/data-locality.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const blogPostSchema = Schema({
title: String,
content: String,
authorId: String,
// Denormalize all the details to render the blog post,
// avoiding extra `populate()` calls.
author: userSchema.pick(["name", "email"]),
tags: [String],
});
*/
/*
const userSchema = Schema({ name: String, email: String, age: Number });
// When updating a user, update all blog posts and comments.
userSchema.post("save", async function () {
const update = { $set: { author: this } };
await BlogPost.updateMany({ authorId: this._id }, update);
});
const User = mongoose.model("User", userSchema);
const blogPostSchema = Schema({
title: String,
content: String,
authorId: mongoose.ObjectId,
author: userSchema.pick(["name", "email"]),
tags: [String],
});
// `BlogPost.author` embeds information from 'User'
const BlogPost = mongoose.model("BlogPost", blogPostSchema);
*/
const vehicleSchema = Schema({
make: String,
model: String,
plate: String,
ownerId: mongoose.ObjectId,
});
const parkingSchema = Schema({
endsAt: Date,
vehicleId: mongoose.ObjectId,
vehicle: vehicleSchema.pick(["plate"]),
});
<file_sep>/04-Middleware/model-middleware.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
const schema = Schema({ name: String });
schema.post("insertMany", function (res) {
let condition = this === Model;
console.log(`this === Model : ${condition}`); // true
condition = res[0] instanceof Model; // true
console.log(`res[0] instanceof Model : ${condition}`);
res[0].name; // 'test'
});
const Model = mongoose.model("Test", schema);
// Triggers `post('insertMany')` hooks
await Model.insertMany([{ name: "test" }]);
<file_sep>/03-queries/sort-order.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const schema = new Schema({ name: String, age: Number });
const Character = mongoose.model("Character", schema);
await Character.create({ name: "<NAME>", age: 59 });
await Character.create({ name: "<NAME>", age: 29 });
// `doc` may be either of the 2 documents inserted above.
// Natural order means MongoDB may return whichever one.
const doc = await Character.findOne();
*/
/*
// The 3rd parameter to `findOne()` is an `options` parameter.
// `options.sort` lets you specify what order MongoDB should
// use when checking which documents match `filter`
const options = { sort: { name: 1 } };
// `doc` will always be the doc with name '<NAME>'
let doc = await Character.findOne({}, null, options);
// You can also set the `sort` option using `Query#sort()`.
doc = await Character.findOne({}).sort({ name: 1 });
*/
/*
// Update the character with the highest `age`. The `sort` option
// can be a string property name, or an object.
await Character.updateOne({}, { rank: "Captain" }).sort("-age");
// Find all characters, sorted by `age`
const docs = await Character.find().sort({ age: 1 });
// Delete the character whose name comes first alphabetically
// out of all the characters whose age is greater than 25.
await Character.deleteOne({ age: { $gt: 25 } }).sort("name");
*/
/*
const schema = new Schema({ value: String });
const TestString = mongoose.model("TestString", schema);
await TestString.create([
{ value: "A" },
{ value: "a" },
{ value: "Z" },
{ value: "z" },
{ value: "" },
{ value: "aa" },
]);
let docs = await TestString.find().sort({ value: 1 });
docs.map((v) => v.value); // ['', 'A', 'Z', 'a', 'aa', 'z']
*/
/*
// `value: {}` means Mongoose skips casting the `value` property
const schema = new Schema({ value: {} });
const Test = mongoose.model("Test", schema);
await Test.create([
{ value: 42 },
{ value: "test string" },
{ value: true },
{ value: null },
]);
const docs = await Test.find().sort({ value: 1 });
docs.map((v) => v.value); // [null, 42, 'test string', true]
*/
/*
// `value: {}` means Mongoose skips casting the `value` property,
// so `value` can be of any type.
const schema = new Schema({ value: {} });
const Test = mongoose.model("Test", schema);
await Test.create([{ value: 42 }]);
const opts = { new: true };
// Does nothing because 'a' > 42 in MongoDB's sort order
let doc = await Test.findOneAndUpdate({}, { $min: { value: "a" } }, opts);
doc.value; // 42
// Sets `value` to `null` because `null` is smaller than
// any other value in MongoDB's sort order.
doc = await Test.findOneAndUpdate({}, { $min: { value: null } }, opts);
doc.value; // null
*/
const schema = new Schema({ value: {} });
const Test = mongoose.model("Test", schema);
await Test.create([{ value: 42 }]);
// Does **not** find the doc. 42 is greater than null in MongoDB
// sort order, but `$gte` only compares values with the same type
let doc = await Test.findOne({ value: { $gte: null } });
// Also doesn't find the doc. `$lte` will only compare docs
// whose `value` is the same type as the given value (string).
doc = await Test.findOne({ value: { $lte: "42" } });
<file_sep>/07-app-structure/schemas-models.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const userSchema = new mongoose.Schema({
name: String,
email: String,
// ... other properties
});
module.exports = mongoose.model("User", userSchema);
*/
/*
const userSchema = new mongoose.Schema({
name: String,
email: String,
// ... other properties
});
mongoose.model("User", userSchema);
// Equivalent:
mongoose.connection.model("User", userSchema);
*/
// `user.js` queries should be on the "fast connection"
const fastConn = require("../connections/fast.js");
const { Schema } = require("mongoose");
const schema = Schema({ name: String, email: String /*...*/ });
module.exports = fastConn.model("User", schema);
// On the other hand, `pageView.js` queries are for slow
// analytics queries, and should be on the "slow connection"
// to avoid slowing down fast queries.
const slowConn = require("../connections/slow.js");
const { Schema } = require("mongoose");
const schema = Schema({ url: String, time: Date /*...*/ });
module.exports = slowConn.model("PageView", schema);
<file_sep>/06-Schema/connection-pool.js
const mongoose = require("mongoose");
const { Schema, Types, model, ObjectId, Query } = mongoose;
const {
connectToDB,
} = require("../01-getting-started/1.2-connecting-to-mongodb");
/*
const uri = ``;
const conn1 = await mongoose.createConnection(uri, { poolSize: 1 });
const conn2 = await mongoose.createConnection(uri, { poolSize: 1 });
const Model1 = conn1.model("Test", Schema({ name: String }));
const Model2 = conn2.model("Test", Schema({ name: String }));
await Model1.create({ name: "test" });
// Because this operation is on a separate connection, it won't
// slow down operations on `Model2`
const p = Model1.find({ $where: "sleep(1000) || true" }).exec();
const startTime = Date.now();
const doc = await Model2.findOne();
doc.name; // 'test'
const elapsed = Date.now() - startTime; // Much less than 1000
console.log(elapsed);
*/
/*
const parentSchema = Schema({ _id: Number });
const Parent = mongoose.model("Parent", parentSchema);
const childSchema = Schema({ name: String, parentId: Number });
const Child = mongoose.model("Child", childSchema);
const parents = [];
for (let i = 0; i < 10000; ++i) {
parents.push({ _id: i });
}
await Parent.insertMany(parents);
const cs = [];
for (let i = 0; i < 10000; ++i) {
cs.push({ name: i, parentId: i });
}
await Child.insertMany(cs);
const startTime = Date.now();
await Parent.aggregate([
{
$lookup: {
from: "Bar",
localField: "_id",
foreignField: "fooId",
as: "bars",
},
},
]);
// Takes about 200ms on my laptop even though there's only 10k
// documents. Performance degrades as O(N^2) because of $lookup.
const elapsed = Date.now() - startTime;
console.log(elapsed);
*/
const parentSchema = Schema({ _id: Number });
const Parent = mongoose.model("Parent", parentSchema);
const childSchema = Schema({ name: String, parentId: Number });
const Child = mongoose.model("Child", childSchema);
const parents = [];
for (let i = 0; i < 10000; ++i) {
parents.push({ _id: i });
}
await Parent.insertMany(parents);
const cs = [];
for (let i = 0; i < 10000; ++i) {
cs.push({ name: i, parentId: i });
}
await Child.insertMany(cs);
const startTime = Date.now();
const err = await Parent.aggregate([
{
$lookup: {
from: "Bar",
localField: "_id",
foreignField: "fooId",
as: "bars",
},
},
])
.option({ maxTimeMS: 10 })
.catch((err) => err);
err.message; // 'operation exceeded time limit'
const elapsed = Date.now() - startTime; // About 10
console.log(elapsed);
|
39bd1f8d8c81ee87568020e685388f0f23ce9bea
|
[
"JavaScript"
] | 47
|
JavaScript
|
mohamedisakr/mastering-mongoose
|
4f108a1c9dd0dcf1908c74c36bc8afdbc331e8a1
|
6e60874b5c8bd312521ddf75f636f54e4b126ce8
|
refs/heads/master
|
<file_sep>// This #include statement was automatically added by the Particle IDE.
#include "Robot.h"
// This #include statement was automatically added by the Particle IDE.
#include "Command.h"
void setup()
{
setupSteppers();
// Listen for commands from the web!
Particle.function("command", processCommand);
/*
* ==================================
* Add your commands below this line!
* ==================================
*/
addCommand(forward);
addCommand(back);
addCommand(left);
addCommand(right);
}
void loop()
{
if(isDoneMoving() && commands.size())
{
runCommand(commands.front());
commands.pop();
}
stepperLeft.run();
stepperRight.run();
}<file_sep>#ifndef robot_h_
#define robot_h_
#include "AccelStepperSpark/AccelStepperSpark.h"
#include <math.h>
#define STEPPER_MAX_SPEED 2000.0
#define STEPPER_ACCELERATION 150.0
#define WHEEL_SEPARATION_RADIUS 54
#define WHEEL_RADIUS 30
#define STEPS_FULL_TURN 4076
#define WHEEL_TURN_DISTANCE (2 * M_PI * WHEEL_RADIUS)
#define WHEEL_STEP_DISTANCE (WHEEL_TURN_DISTANCE / STEPS_FULL_TURN)
#define TURN_ACTION_DISTANCE (M_PI * WHEEL_SEPARATION_RADIUS / 4)
#define TURN_ACTION_STEPS (TURN_ACTION_DISTANCE / WHEEL_STEP_DISTANCE)
extern AccelStepper stepperLeft;
extern AccelStepper stepperRight;
void setupSteppers();
#endif
|
61f685fe153201604427183155e1f2b7a2f3bfe1
|
[
"C",
"C++"
] | 2
|
C++
|
CircuitGrind/SnappyPhoton
|
f1c9bf1bdd59e5e6b4a8deef0407d89248dd2fc1
|
cb21ba09d6ca720211a2eea1aaaafe34b332bccc
|
refs/heads/master
|
<repo_name>SSE73/testgmail<file_sep>/src/test/java/simbirsoft/signIn/HomePage.java
package simbirsoft.signIn;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class HomePage {
private WebDriver driver;
private WebDriverWait wait;
public HomePage(WebDriver driver) {
this.driver = driver;
wait = new WebDriverWait(driver, 10);
}
@FindBy(css = "a.gmail-nav__nav-link.gmail-nav__nav-link__sign-in")
WebElement signIn;
private By identifierNext = By.id("identifierNext");
public void open() {
driver.get("https://www.google.com/intl/ru/gmail/about/#");
}
public void getStarted() {
signIn.click();
wait.until(ExpectedConditions.visibilityOfElementLocated(identifierNext));
}
}
<file_sep>/src/test/java/simbirsoft/signIn/SignInTest.java
package simbirsoft.signIn;
import org.junit.Assert;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
import simbirsoft.WebDriverSettings;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.util.ArrayList;
import java.util.List;
public class SignInTest extends WebDriverSettings {
@Test
public void singIn() {
HomePage homePage = PageFactory.initElements(driver,HomePage.class);
homePage.open();
homePage.getStarted();
SignInPage signInPage = PageFactory.initElements(driver,SignInPage.class);
signInPage.setLogin("<EMAIL>");
String profileIdentifierText = signInPage.profileIdentifier();
Assert.assertEquals(profileIdentifierText, "<EMAIL>");
signInPage.setPassword("<PASSWORD>");
LetterPage letterPage = PageFactory.initElements(driver,LetterPage.class);
letterPage.setFindFio("Филинин Илья");
List<WebElement> intCountFio = letterPage.getCountFio();
int bbb = ((ArrayList) intCountFio).size();
int countLettersText = Integer.parseInt(letterPage.getCountLetters());
Assert.assertEquals(countLettersText, bbb);
SendPage sendPage = PageFactory.initElements(driver,SendPage.class);
sendPage.openSendForm();
//sendPage.whomLetter("<EMAIL>");
sendPage.whomLetter("<EMAIL>");
sendPage.setSubjectbox("Тестовое задание от Сысылятина");
sendPage.bodyLetterser("Было прислано " + countLettersText + " письма");
sendPage.buttonSend();
}
}
|
657fe612b156254879abc2bb08b20e667ac911e9
|
[
"Java"
] | 2
|
Java
|
SSE73/testgmail
|
d23ec3714228b770a64c8fd1905dbbb2f2745eb5
|
9b880896e98ccc6e153ff8aa587f6ad75e76edf7
|
refs/heads/master
|
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itoa_base.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/08 10:30:41 by gpouyat #+# #+# */
/* Updated: 2017/01/24 07:59:17 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
char *win_linesitoa(uintmax_t num, unsigned int base, int *i)
{
char *str;
str = ft_strnew(nb_of_figure(num, base) + 2);
while (num)
{
str[*i] = ((num % base <= 9) ? num % base + '0'\
: num % base + 'A' - 10);
num = num / base;
*i = *i + 1;
}
return (str);
}
char *ft_itoa_base(int nb, unsigned int base)
{
int neg;
char *str;
int i;
unsigned int num;
i = 0;
neg = 0;
if (nb < 0)
{
num = -nb;
if (base == 10)
neg = 1;
else if (base == 16 || base == 8)
num = UINT_MAX - num + 1;
}
else
num = nb;
if (num == 0)
return (ft_strdup("0"));
str = win_linesitoa(num, base, &i);
str[i] = (neg ? '-' : str[i]);
str = rev(str);
return (str);
}
char *ft_itoa_plusbase(int nb, unsigned int base)
{
int neg;
char *str;
int i;
unsigned int num;
i = 0;
neg = 0;
if (nb < 0)
{
num = -nb;
if (base == 10)
neg = 1;
else if (base == 16 || base == 8)
num = 4294967296 - num;
}
else
num = nb;
if (num == 0)
return (ft_strdup("+0"));
str = win_linesitoa(num, base, &i);
str[i] = (neg ? '-' : '+');
str = rev(str);
return (str);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* b_join.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/12/25 22:33:31 by gpouyat #+# #+# */
/* Updated: 2019/01/04 15:27:10 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/libft.h"
t_array_byte b_join(t_array_byte dest, t_array_byte srcs)
{
char *str_join;
if (!srcs.bytes || !dest.bytes)
return (dest);
if (!(str_join = ft_memalloc(dest.nb + srcs.nb)))
b_clean(dest);
else
{
ft_memcpy(str_join, dest.bytes, dest.nb);
ft_memcpy(&str_join[dest.nb], srcs.bytes, srcs.nb);
dest.bytes = str_join;
dest.nb = dest.nb + srcs.nb;
}
return (dest);
}
t_array_byte b_join_secu(t_array_byte dest, t_array_byte srcs,
size_t lvl)
{
char *str_join;
if (!srcs.bytes || !dest.bytes)
return (dest);
if (!(str_join = ft_secu_malloc_lvl(dest.nb + srcs.nb, lvl)))
b_clean_secu(dest);
else
{
ft_memcpy(str_join, dest.bytes, dest.nb);
ft_memcpy(&str_join[dest.nb], srcs.bytes, srcs.nb);
dest.bytes = str_join;
dest.nb = dest.nb + srcs.nb;
}
return (dest);
}
t_array_byte b_joinf(t_array_byte dest, t_array_byte srcs, int free)
{
t_array_byte ret;
ret = b_join(dest, srcs);
if (free == 1 || free == 3)
b_clean(dest);
if (free == 1 || free == 3)
b_clean(srcs);
return (ret);
}
t_array_byte b_joinf_secu(t_array_byte dest, t_array_byte srcs, int free,
size_t lvl)
{
t_array_byte ret;
ret = b_join_secu(dest, srcs, lvl);
if (free == 1 || free == 3)
b_clean_secu(dest);
if (free == 1 || free == 3)
b_clean_secu(srcs);
return (ret);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* pf_itoa_base.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/08 10:30:41 by gpouyat #+# #+# */
/* Updated: 2018/10/11 12:20:20 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
uintmax_t nb_of_figure(uintmax_t nb, uintmax_t base)
{
uintmax_t figure;
figure = 0;
if (nb == 0)
return (1);
while (nb)
{
figure++;
nb = nb / base;
}
return (figure);
}
char *rev(char *str)
{
char *rev;
uintmax_t i;
uintmax_t a;
a = 0;
i = 0;
i = ft_strlen(str);
rev = ft_strnew(i);
i--;
while (rev && str[a])
{
rev[a] = str[i];
a++;
i--;
}
free(str);
return (rev);
}
char *pf_itoa_base(intmax_t nb, uintmax_t base)
{
int neg;
char *str;
int i;
uintmax_t num;
i = 0;
neg = 0;
if (nb < 0)
{
num = -nb;
if (base == 10 || base == 2)
neg = 1;
else if (base == 16 || base == 8)
num = ULLONG_MAX - num + 1;
}
else
num = nb;
if (num == 0)
return (ft_strdup("0"));
str = win_linesitoa(num, base, &i);
if (neg)
str[i] = '-';
str = rev(str);
return (str);
}
char *pf_uitoa_base(uintmax_t nb, uintmax_t base)
{
char *str;
int i;
i = 0;
if (nb == 0)
return (ft_strdup("0"));
str = win_linesitoa(nb, base, &i);
str = rev(str);
return (str);
}
char *pf_itoa_plusbase(intmax_t nb, uintmax_t base)
{
int neg;
char *str;
int i;
uintmax_t num;
i = 0;
neg = 0;
if (nb < 0)
{
num = -nb;
if (base == 10)
neg = 1;
else if (base == 16 || base == 8)
num = ULLONG_MAX - num + 1;
}
else
num = nb;
if (num == 0)
return (ft_strdup("+0"));
str = win_linesitoa(num, base, &i);
str[i] = (neg ? '-' : '+');
str = rev(str);
return (str);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/10 15:17:00 by gpouyat #+# #+# */
/* Updated: 2017/03/02 12:38:34 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static int nb_word(char const *s, char c)
{
size_t i;
size_t count;
i = 0;
count = 0;
while (s[i])
{
if (s[i] != c)
{
count++;
while (s[i] != c && s[i])
i++;
}
else
i++;
}
return (count);
}
static char **ft_split_cut(char **tab, char const *s, unsigned int count,
char c)
{
unsigned int word;
unsigned int i;
unsigned int temp;
temp = 0;
i = 0;
word = 0;
while (s[i] && word < count)
{
temp = 0;
if (s[i] != c)
{
while (s[temp + i] != c && s[temp + i])
temp++;
tab[word] = ft_strsub(s, i, temp);
word++;
i = temp + i;
}
else
i++;
}
return (tab);
}
char **ft_strsplit(char const *s, char c)
{
char **tab;
if (s == NULL)
return (NULL);
tab = ft_strdblnew(nb_word(s, c));
if (tab == NULL)
return (NULL);
tab = ft_split_cut(tab, s, nb_word(s, c), c);
return (tab);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* error.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/12/30 21:28:40 by gpouyat #+# #+# */
/* Updated: 2017/12/21 19:39:00 by guiforge ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include <sys/types.h>
#include <signal.h>
void basicerror(char *name, char *error, int ex)
{
ft_putstr_fd(name, 2);
perror(error);
if (ex)
exit(EXIT_FAILURE);
}
void basicerror_out(char *name, char *error, int nb)
{
ft_putstr_fd(name, 2);
perror(error);
exit(nb);
}
void exit_error(const char *progname, const char *error, pid_t pid, int sig)
{
ft_putstr_fd(progname, STDERR_FILENO);
ft_putstr_fd(": EXIT-ERROR: ", STDERR_FILENO);
if (error)
ft_putendl_fd(error, STDERR_FILENO);
else
ft_putendl_fd("", STDERR_FILENO);
kill(pid, sig);
exit(EXIT_FAILURE);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_x.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/23 15:20:22 by gpouyat #+# #+# */
/* Updated: 2018/10/11 14:20:03 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/libft.h"
static char *next_x(t_flags flags, char *tmp)
{
if (!tmp)
return (NULL);
if (ft_atoi_base(tmp, 16) < 0 && !flags.type[0] && ft_strlen(tmp) == 16)
tmp = ft_replace(tmp, "", 0, 8);
else if (ft_atoi_base(tmp, 16) < 0 && flags.type[0] == 'h' &&\
flags.type[1] == 0 && ft_strlen(tmp) == 16)
tmp = ft_replace(tmp, "", 0, 12);
else if (ft_atoi_base(tmp, 16) < 0 && flags.type[0] == 'h' &&\
ft_strlen(tmp) == 16)
tmp = ft_replace(tmp, "", 0, 14);
if (flags.preci == 0 && ft_atoi(tmp) == 0)
tmp = ft_replace(tmp, "", 0, 1);
return (tmp);
}
char *ft_x(t_flags flags, char *format, va_list ap, int **i)
{
char *tmp;
char *tmp2;
if (!format || !i || !*i)
return (NULL);
tmp = pf_itoa_base(ft_tnum(flags, ap), 16);
tmp = next_x(flags, tmp);
tmp2 = preci(flags, tmp);
free(tmp);
if (((ft_atoi(tmp2) != 0) && flags.hash) || flags.convers == 'p')
tmp2 = ft_replace(tmp2, "0X", 0, 0);
tmp = minus(flags, tmp2);
free(tmp2);
tmp2 = width(flags, tmp);
free(tmp);
tmp2 = (flags.convers == 'X' ? tmp2 : ft_strtolower(tmp2));
format = ft_replace(format, tmp2, **i, flags.size + 1);
**i = **i + ft_strlen(tmp2) - 1;
free(tmp2);
return (format);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* type_of_number.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/16 11:04:27 by gpouyat #+# #+# */
/* Updated: 2017/02/04 09:22:30 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/libft.h"
intmax_t ft_tnum(t_flags flags, va_list ap)
{
intmax_t num;
char c;
short int i;
num = 0;
if (flags.type[0] == 'h' && flags.type[1] == 'h')
return (c = va_arg(ap, int));
else if (flags.type[0] == 'h')
return (i = va_arg(ap, int));
else if (flags.type[0] == 'l' && flags.type[1] == 'l')
return (num = va_arg(ap, long long int));
else if (flags.type[0] == 'l')
return (num = va_arg(ap, long int));
else if (flags.type[0] == 'j')
return (num = va_arg(ap, intmax_t));
else if (flags.type[0] == 'z')
return (num = va_arg(ap, ssize_t));
return (num = va_arg(ap, int));
}
uintmax_t ft_utnum(t_flags flags, va_list ap)
{
uintmax_t num;
unsigned char c;
unsigned short int i;
num = 0;
if (flags.type[0] == 'h' && flags.type[1] == 'h')
return (c = va_arg(ap, unsigned int));
else if (flags.type[0] == 'h')
return (i = va_arg(ap, unsigned int));
else if (flags.type[0] == 'l' && flags.type[1] == 'l')
return (num = va_arg(ap, unsigned long long int));
else if (flags.type[0] == 'l')
return (num = va_arg(ap, unsigned long int));
else if (flags.type[0] == 'j')
return (num = va_arg(ap, uintmax_t));
else if (flags.type[0] == 'z')
return (num = va_arg(ap, size_t));
return (num = va_arg(ap, unsigned int));
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* color.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/24 08:42:28 by gpouyat #+# #+# */
/* Updated: 2018/10/11 13:37:33 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/libft.h"
static char *replace_couleur(char *format, int i)
{
if (!ft_strncmp(&format[i], "{red}", 5))
format = ft_replace(format, C_RED, i, 5);
else if (!ft_strncmp(&format[i], "{no}", 4))
format = ft_replace(format, C_NONE, i, 4);
else if (!ft_strncmp(&format[i], "{blue}", 6))
format = ft_replace(format, C_BLUE, i, 6);
else if (!ft_strncmp(&format[i], "{green}", 7))
format = ft_replace(format, C_GREEN, i, 7);
else if (!ft_strncmp(&format[i], "{yellow}", 8))
format = ft_replace(format, C_YELLOW, i, 8);
else if (!ft_strncmp(&format[i], "{Bred}", 6))
format = ft_replace(format, B_RED, i, 6);
else if (!ft_strncmp(&format[i], "{Bblue}", 7))
format = ft_replace(format, B_BLUE, i, 7);
else if (!ft_strncmp(&format[i], "{Bgreen}", 8))
format = ft_replace(format, B_GREEN, i, 8);
else if (!ft_strncmp(&format[i], "{Byellow}", 9))
format = ft_replace(format, B_YELLOW, i, 9);
return (format);
}
char *pf_couleur(char *format)
{
int i;
i = 0;
while (format && format[i])
{
if (format[i] == '{')
{
format = replace_couleur(format, i);
}
i++;
}
return (format);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* log.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/12/27 17:01:05 by gpouyat #+# #+# */
/* Updated: 2019/01/11 19:17:28 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/libft.h"
#include <fcntl.h>
int g_log_fd = -1;
static t_bool g_init = False;
int log_init(char *filename, int fd)
{
if (g_init)
log_warn("New init !!!!");
if (filename)
g_log_fd = open(filename, O_RDWR | O_CREAT | O_TRUNC, 0644);
else
g_log_fd = fd;
if (g_log_fd == -1)
ft_dprintf(STDERR_FILENO, "Error init logger file: %s\n", filename);
else
ft_dprintf(g_log_fd, "\t\t ***** Logger start *****\n"
"******************************************************************\n");
g_init = True;
return (g_log_fd);
}
int log_log(enum e_logger_lvl lvl, const char *format, va_list list)
{
if (!g_init)
return (-1);
if (lvl == LOG_LVL_ERROR)
ft_dprintf(g_log_fd, "{no}[{red}ERROR{no}] >>>: {red}");
else if (lvl == LOG_LVL_FATAL)
ft_dprintf(g_log_fd, "{no}{red}[FATAL] !!!!!!!!!: ");
else if (lvl == LOG_LVL_WARN)
ft_dprintf(g_log_fd, "{no}{yellow}[Warning]: ");
else if (lvl == LOG_LVL_INFO)
ft_dprintf(g_log_fd, "{no}[Info]: ");
else
ft_dprintf(g_log_fd, "{no}-> ");
ft_vdprintf(g_log_fd, format, list);
ft_dprintf(g_log_fd, "{no}\n");
return (g_log_fd);
}
void log_close(void)
{
ft_dprintf(g_log_fd, "\t\t ----- Logger END -----\n"
"-----------------------------------------------------------------*\n");
if (g_log_fd > 2)
close(g_log_fd);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lstpush.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/05/10 13:20:28 by gpouyat #+# #+# */
/* Updated: 2019/01/04 15:57:03 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../../includes/libft.h"
void ft_lstpush(t_list **alst, t_list *new)
{
t_list *tmp;
tmp = *alst;
while (tmp && tmp->next)
tmp = tmp->next;
if (tmp)
{
tmp->next = new;
new->prev = tmp;
new->next = NULL;
}
else
*alst = new;
}
void ft_lstpush_new(t_list **alst, void const *content, size_t content_size)
{
t_list *new;
new = ft_lstnew(content, content_size);
if (new)
ft_lstpush(alst, new);
}
void ft_lstpush_new_secu(t_list **alst, void const *content,
size_t content_size, size_t lvl)
{
t_list *new;
new = ft_lstnew_secu(content, content_size, lvl);
if (new)
ft_lstpush(alst, new);
}
void ft_lstpush_extra(t_list **alst, void const *content,
size_t content_size)
{
t_list *new;
new = ft_lstextra(content, content_size);
if (new)
ft_lstpush(alst, new);
}
void ft_lstpush_extra_secu(t_list **alst, void const *content,
size_t content_size, size_t lvl)
{
t_list *new;
new = ft_lstextra_secu(content, content_size, lvl);
if (new)
ft_lstpush(alst, new);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* print.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/24 08:41:51 by gpouyat #+# #+# */
/* Updated: 2018/10/11 12:28:06 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/libft.h"
static t_flags zero(t_flags flags)
{
flags.hash = 0;
flags.space = 0;
flags.plus = 0;
flags.convers = 0;
flags.type[0] = 0;
flags.type[1] = 0;
flags.type[2] = 0;
flags.minus = 0;
flags.preci = -1;
flags.width = 0;
flags.zero = 0;
flags.size = 0;
return (flags);
}
static int ret(int len, char *format, int fd)
{
int i;
format = pf_couleur(format);
if (!format)
return (len);
ft_putstr_fd(format, fd);
i = ft_strlen(format);
free(format);
return (i + len);
}
static int chech_error_malloc(void)
{
ft_putendl_fd("Printf ERROR Malloc\n", STDERR_FILENO);
return (0);
}
int print(int fd, char *frmt, va_list ap)
{
t_flags flags;
int i;
char *format;
int len;
if (!(format = ft_strdup(frmt)))
return (chech_error_malloc());
i = 0;
len = 0;
while (format && format[i])
{
if (format[i] == '%')
{
flags = zero(flags);
flags = get_struct(flags, &format[i]);
flags.type[0] = ((flags.convers == 'D' || flags.convers == 'O') ?
flags.type[0] = 'l' : flags.type[0]);
format = ft_convers(&flags, format, ap, &i);
if (flags.type[2] == -1)
len++;
}
i++;
}
return (ret(len, format, fd));
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strcmpa.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/03 13:31:35 by gpouyat #+# #+# */
/* Updated: 2019/02/01 17:24:21 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static void lines_free(char *s1_tmp, char *s2_tmp)
{
free(s1_tmp);
free(s2_tmp);
}
int ft_strcmpa(const char *s1, const char *s2)
{
int i;
int a;
char *s2_tmp;
char *s1_tmp;
i = 0;
a = 0;
s2_tmp = ft_strtolower(ft_strdup(s2));
s1_tmp = ft_strtolower(ft_strdup(s1));
while (ft_isalpha(s1_tmp[i]) == 0 && s1_tmp[i])
i++;
while (ft_isalpha(s2_tmp[a]) == 0 && s2_tmp[a])
a++;
while (s1_tmp[i] == s2_tmp[a] && (s1_tmp[i] || s2_tmp[a]))
{
i++;
a++;
while (ft_isalpha(s1_tmp[i]) == 0 && s1_tmp[i])
i++;
while (ft_isalpha(s2_tmp[a]) == 0 && s2_tmp[a])
a++;
}
i = ((unsigned char)s1_tmp[i] - (unsigned char)s2_tmp[a]) % 127;
lines_free(s1_tmp, s2_tmp);
return (i);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_replace.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/09 12:10:42 by gpouyat #+# #+# */
/* Updated: 2018/10/11 13:55:54 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
int ft_replace_init(char *src1, char *src2, int index, int size)
{
if (!src1 || !src2 || ft_strlen(src1) < (size_t)(index + 1))
return (-1);
if ((ft_strlen(&src1[index]) < (size_t)size))
return (-1);
return (0);
}
char *ft_replace(char *src1, char *src2, int index, int size)
{
char *begin;
char *end;
char *ret;
if (ft_replace_init(src1, src2, index, size))
return (NULL);
if ((begin = ft_strnew((index + 1))) == NULL)
return (NULL);
begin = ft_strncpy(begin, src1, index);
end = ft_strjoin(src2, &src1[index + size]);
if (end)
ret = ft_strjoin(begin, end);
else
ret = NULL;
ft_fri(&begin);
ft_fri(&end);
ft_fri(&src1);
return (ret);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_str.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/12/02 11:27:15 by gpouyat #+# #+# */
/* Updated: 2019/03/10 14:39:08 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/intern/get_next_line.h"
static int exist_stock(char **line, char **stock, char *str)
{
char *temp;
char *tmp_stock;
tmp_stock = *stock;
if ((temp = ft_strstr(*stock, str)))
{
*temp = '\0';
*line = ft_strdup(*stock);
*stock = ft_strdup(temp + 1);
temp = NULL;
ft_strdel(&tmp_stock);
return (0);
}
return (1);
}
static int read_gnl(char **stock, char *buf, char **line, char *str)
{
char *temp;
if ((temp = ft_strstr(buf, str)))
{
*temp = '\0';
*line = ft_strjoin(*stock, buf);
free(*stock);
*stock = ft_strdup(temp + 1);
free(buf);
temp = NULL;
if (*stock && *stock[0] == 0)
ft_fri(stock);
return (0);
}
return (1);
}
static int win_lines_return(int ret, char **line, char **stock,
char **buf)
{
if (ret == -1)
return (-1);
*line = ft_strdup(*stock);
free(*stock);
*stock = NULL;
free(*buf);
*buf = NULL;
if (ret == 0 && *line[0] != '\0')
return (1);
return (0);
}
int get_next_str(const int fd, char **line, char *str)
{
char *buf;
int ret;
char *temp;
static char *stock = NULL;
if (stock)
{
if ((exist_stock(line, &stock, str)) == 0)
return (1);
}
else
stock = ft_strnew(0);
ret = 0;
buf = ft_strnew(BUFF_SIZE + 1);
while ((ret = (int)read(fd, buf, BUFF_SIZE)) > 0)
{
buf[ret] = '\0';
if (read_gnl(&stock, buf, line, str) == 0)
return (1);
temp = stock;
stock = ft_strjoin(stock, buf);
ft_fri(&temp);
}
return (win_lines_return(ret, line, &stock, &buf));
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_secu_free.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/07/20 20:09:31 by gpouyat #+# #+# */
/* Updated: 2018/12/25 23:19:58 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/libft.h"
/*
** @brief Searches into memory for a pointer
**
** @param ptr Pointer to search
** @param mem Where to seach
**
** @return Returns the corresponding malloc struct
*/
static t_secu_malloc *ft_malloc_search(void *ptr, t_mem *mem)
{
t_secu_malloc *tmp;
tmp = mem->first;
while (tmp && (tmp->ptr != ptr))
tmp = tmp->next;
return (tmp);
}
/*
** @brief Frees securely the variable passed
**
** @param ptr The pointer to the variable you want to free
*/
void ft_secu_free(void *ptr)
{
t_mem *mem;
t_secu_malloc *secu_malloc;
if (!(mem = get_mem()))
return ;
if (!(secu_malloc = ft_malloc_search(ptr, mem)))
return ;
if (!secu_malloc->prev)
mem->first = secu_malloc->next;
else
secu_malloc->prev->next = secu_malloc->next;
if (!secu_malloc->next)
mem->last = secu_malloc->prev;
else
secu_malloc->next->prev = secu_malloc->prev;
ft_memdel(&secu_malloc->ptr);
ft_memdel((void **)&secu_malloc);
}
/*
** @brief Frees all it can find in memory
*/
void ft_secu_free_all(void)
{
t_mem *mem;
t_secu_malloc *secu_malloc;
t_secu_malloc *tmp;
if (!(mem = get_mem()))
return ;
secu_malloc = mem->first;
while (secu_malloc)
{
tmp = secu_malloc;
secu_malloc = secu_malloc->next;
free(tmp->ptr);
free(tmp);
}
free(mem);
}
/*
** @brief Frees a whole `lvl`
**
** @param lvl level to free
*/
void ft_secu_free_lvl(size_t lvl)
{
t_mem *mem;
t_secu_malloc *secu_malloc;
t_secu_malloc *tmp;
if (!(mem = get_mem()))
return ;
secu_malloc = mem->first;
while (secu_malloc)
{
if (secu_malloc->lvl == lvl)
{
tmp = secu_malloc;
ft_secu_free(tmp->ptr);
if (!(mem = get_mem()))
return ;
secu_malloc = mem->first;
}
else
secu_malloc = secu_malloc->next;
}
}
<file_sep># libft
my_lib
print_srcs : ft_printf code
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_lstsort.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/06/07 17:32:43 by gpouyat #+# #+# */
/* Updated: 2018/10/02 11:24:48 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
void ft_lstsort(t_list **lst, t_bool (*sort)(t_list *a, t_list *b))
{
t_list *new_lst;
t_list *smaller;
t_list *index;
new_lst = NULL;
if (!lst || !*lst)
return ;
while (*lst)
{
index = *lst;
smaller = *lst;
while (index)
{
if (!sort(smaller, index))
smaller = index;
index = index->next;
}
ft_lstremove(lst, smaller);
ft_lstpush(&new_lst, smaller);
}
*lst = new_lst;
}
void ft_lstsortrev(t_list **lst, t_bool (*sort)(t_list *a, t_list *b))
{
ft_lstsort(lst, sort);
ft_lstrev(lst);
}
void ft_lstrev(t_list **lst)
{
t_list *new;
t_list *tmp;
new = NULL;
if (!lst || !*lst)
return ;
while (*lst)
{
tmp = *lst;
*lst = (*lst)->next;
ft_lstremove(lst, tmp);
ft_lstadd(&new, tmp);
}
*lst = new;
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/09 17:58:37 by gpouyat #+# #+# */
/* Updated: 2018/10/11 14:56:19 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/libft.h"
char get_conver(char c)
{
char *tab;
char result;
int i;
i = 0;
tab = ft_strdup("sSpdDioOuUxXcCb%%");
while (tab && (result = tab[i]))
{
if (c == tab[i])
{
free(tab);
return (result);
}
i++;
}
free(tab);
return (0);
}
t_flags get_type(char *format, t_flags flags)
{
if (!format)
return (flags);
if (format[0] == 'z')
flags.type[0] = 'z';
else if (format[0] == 'j')
flags.type[0] = 'j';
else if (format[0] == 'l' && format[1] != 'l')
flags.type[0] = 'l';
else if (format[0] == 'h' && format[1] != 'h')
flags.type[0] = 'h';
else if (format[0] == 'l' && format[1] == 'l')
{
flags.type[0] = 'l';
flags.type[1] = 'l';
flags.size++;
}
else if (format[0] == 'h' && format[1] == 'h')
{
flags.type[0] = 'h';
flags.type[1] = 'h';
flags.size++;
}
flags.size++;
return (flags);
}
t_flags get_flags(t_flags flags, char *format, int i)
{
if (!format)
return (flags);
if (format[i] == '#')
flags.hash = 1;
else if (format[i] == ' ')
flags.space = 1;
else if (format[i] == '+')
flags.plus = 1;
else if (format[i] == '-')
flags.minus = 1;
else if (format[i] == '0')
flags.zero = 1;
return (flags);
}
static t_flags win_lines(t_flags flags, char *format, int i)
{
if (!format)
return (flags);
flags.size = i;
flags.convers = get_conver(format[i]);
if (!flags.convers)
{
flags = get_type(&format[i], flags);
flags.convers = get_conver(format[flags.size]);
}
flags.zero = ((flags.convers == 'd' && flags.preci != -1) ? 0 : flags.zero);
if (flags.convers == 'p')
{
flags.hash = 1;
flags.type[0] = 'l';
}
else if (flags.convers == 'D')
flags.type[0] = 'l';
return (flags);
}
t_flags get_struct(t_flags flags, char *format)
{
int i;
i = 1;
if (!format)
return (flags);
while (format[i] && (format[i] == '#' || format[i] == ' '
|| format[i] == '+' || format[i] == '-' || format[i] == '0'))
{
flags = get_flags(flags, format, i);
i++;
}
flags.width = ((ft_isdigit(format[i])) ? ft_atoi(&format[i]) : flags.width);
flags.minus = ((flags.minus && flags.width) ? flags.width : flags.minus);
while (ft_isdigit(format[i]))
i++;
if (format[i] == '.')
{
i++;
flags.preci = ft_atoi(&format[i]);
}
while (ft_isdigit(format[i]))
i++;
return (win_lines(flags, format, i));
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_o.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/21 14:46:44 by gpouyat #+# #+# */
/* Updated: 2018/10/11 14:17:05 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/libft.h"
char *pfoitoa_short(short int nb, uintmax_t base)
{
char *str;
int i;
unsigned short int num;
i = 0;
if (nb < 0)
{
num = -nb;
num = USHRT_MAX - num + 1;
}
else
num = nb;
if (num == 0)
return (ft_strdup("0"));
str = ft_strnew(nb_of_figure(num, base) + 2);
while (str && num)
{
str[i] = ((num % base <= 9) ? num % base + '0' : num % base + 'A' - 10);
num = num / base;
i++;
}
str = rev(str);
return (str);
}
char *pfoitoa_char(char nb, uintmax_t base)
{
char *str;
int i;
unsigned char num;
i = 0;
if (nb < 0)
{
num = -nb;
if (base == 16 || base == 8)
num = UCHAR_MAX - num + 1;
}
else
num = nb;
if (num == 0)
return (ft_strdup("0"));
str = ft_strnew(nb_of_figure(num, base) + 2);
while (str && num)
{
str[i] = ((num % base <= 9) ? num % base + '0' : num % base + 'A' - 10);
num = num / base;
i++;
}
str = rev(str);
return (str);
}
char *o_itoa(t_flags flags, va_list ap)
{
uintmax_t num;
num = ft_tnum(flags, ap);
if (flags.type[0] == 'h' && flags.type[1] == 'h')
return (pfoitoa_char(num, 8));
else if (flags.type[0] == 'h')
return (pfoitoa_short(num, 8));
else if (flags.type[0] == 0)
return (ft_itoa_base(num, 8));
return (pf_itoa_base(num, 8));
}
char *ft_o(t_flags flags, char *format, va_list ap, int **i)
{
char *tmp;
char *tmp2;
tmp = o_itoa(flags, ap);
if (ft_atoi(tmp) == 0 && !flags.hash && flags.preci != -1)
tmp = ft_replace(tmp, "", 0, 1);
if (flags.hash && ft_atoi(tmp) != 0)
tmp = ft_replace(tmp, "0", 0, 0);
tmp2 = preci(flags, tmp);
free(tmp);
tmp = minus(flags, tmp2);
free(tmp2);
tmp2 = width(flags, tmp);
free(tmp);
tmp2 = (flags.convers == 'O' ? tmp2 : ft_strtolower(tmp2));
format = ft_replace(format, tmp2, **i, flags.size + 1);
**i = **i + ft_strlen(tmp2) - 1;
free(tmp2);
return (format);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* libft.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/10/26 16:21:53 by gpouyat #+# #+# */
/* Updated: 2019/04/29 15:38:04 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef LIBFT_H
# define LIBFT_H
# include <unistd.h>
# include <stdlib.h>
# include <string.h>
# include <stdint.h>
# include <limits.h>
# include <errno.h>
# include <stdio.h>
# include "./intern/get_next_line.h"
# include "./intern/ft_printf.h"
# include "./intern/ft_btree.h"
# include "./intern/secure_memory.h"
# include "./intern/color.h"
# include "./intern/t_bool.h"
extern int g_log_fd;
typedef struct s_list
{
void *content;
size_t content_size;
struct s_list *next;
struct s_list *prev;
} t_list;
typedef struct s_array_byte
{
char *bytes;
size_t nb;
} t_array_byte;
enum e_logger_lvl
{
LOG_LVL_OFF,
LOG_LVL_FATAL,
LOG_LVL_ERROR,
LOG_LVL_WARN,
LOG_LVL_INFO,
LOG_LVL_DEBUG,
LOG_LVL_MAX
};
/*
** ERROR FUNCTION
*/
int over_p(char *str, char *ag, int nb);
void basicerror_out(char *name, char *error, int nb);
int over(char *str, int nb);
void *over_str(char *str);
void basicerror(char *name, char *error, int ex);
void *over_p_str(char *str, char *ag);
void exit_error(const char *progname, const char *error,
pid_t pid, int sig);
int over_log(int ret, enum e_logger_lvl lvl, char *fmt, ...);
/*
** LIST FUNCTION
*/
t_list *ft_lstnew(void const *content, size_t content_size);
t_list *ft_lstnew_secu(void const *content, size_t content_size,
size_t lvl);
t_list *ft_lstextra_secu(void const *content, size_t content_size,
size_t lvl);
t_list *ft_lstextra(void const *content, size_t content_size);
t_list *ft_lstmap(t_list *lst, t_list *(f)(t_list *elem));
void ft_lstsuppress(t_list *list);
void ft_lstaddnew(t_list **list, void const *content,
size_t content_size);
void ft_lstiter(t_list *lst, void (*f)(t_list *elem));
void ft_lstdel(t_list **alst, void (*del)(void *, size_t));
void ft_lstadd(t_list **alst, t_list *nw);
void ft_lstdelone(t_list **alst, void (*del)(void *, size_t));
void ft_lstpush(t_list **alst, t_list *new_elem);
void ft_lstpush_new(t_list **alst, void const *content,
size_t content_size);
void ft_lstpush_extra(t_list **alst, void const *content,
size_t content_size);
void ft_lstpush_extra_secu(t_list **alst, void const *content,
size_t content_size, size_t lvl);
void ft_lstremove(t_list **lst, t_list *removed);
void ft_lstsort(t_list **lst, t_bool (*sort)(t_list *a,
t_list *b));
void ft_lstsortrev(t_list **lst, t_bool (*sort)(t_list *a,
t_list *b));
void ft_lstrev(t_list **lst);
void ft_lstpush_new_secu(t_list **alst, void const *content,
size_t content_size, size_t lvl);
/*
** TAB FUNCTION
*/
char **ft_strdbldup(char **str);
void ft_strdblfree(char **tab);
char **tri_strdbl_r(char **str);
char **tri_strdbl(char **str);
char **ft_strdblnew(int size);
void ft_strdblprint(char **tab);
size_t ft_strdbllen(const char **array);
/*
** STRING\IS FUNCTION
*/
int ft_isalpha(int c);
int ft_isalnum(int c);
int ft_isalnum(int c);
int ft_isascii(int c);
int ft_isprint(int c);
int ft_isdigit(int c);
int ft_str_isvalue(char *s);
int ft_str_isdigit(char *s);
int ft_str_isprint(char *s);
/*
** STRING\FREE FUNCTION
*/
void ft_fri(char **adrr);
void ft_strclr(char *s);
void ft_strdel(char **as);
/*
** STRING\PUT FUNCTION
*/
void ft_putendl(char const *str);
void ft_putendl_fd(char const *str, int fd);
void ft_putnbr(int n);
void ft_putnbr_fd(int n, int fd);
void ft_putsize_t_base_fd(size_t number, unsigned int base,
int fd);
void ft_putnbr_base_fd(unsigned int number, unsigned int base,
int fd);
void ft_putnbr_base_fd_low(unsigned int number,
unsigned int base, int fd);
void ft_putstr(char const *str);
void ft_putstr_fd(char const *str, int fd);
void ft_putchar_fd(char c, int fd);
void ft_putchar(char c);
/*
** STRING\USEMALLOC
*/
char *pf_itoa_base(intmax_t nb, uintmax_t base);
char *pf_uitoa_base(uintmax_t nb, uintmax_t base);
char *pf_itoa_plusbase(intmax_t nb, uintmax_t base);
char *ft_uitoa(unsigned int n);
char *ft_itoa_base(int nb, unsigned int base);
char *ft_itoa_plusbase(int nb, unsigned int base);
char *ft_strdup(const char *str);
char *ft_strjoincl(char *s1, char const *s2, int free);
char *ft_replace(char *src1, char *src2, int index, int size);
char *ft_strjoin(char const *s1, char const *s2);
char *ft_strtrim(char const *s);
char *ft_strnew(size_t size);
int ft_indexchr(const char *s, int c);
char *rev(char *str);
uintmax_t nb_of_figure(uintmax_t nb, uintmax_t base);
char *ft_getchar(wchar_t c);
char *ft_getwstr(wchar_t *s);
int ft_strwlen(wchar_t *s);
void ft_putwstr(wchar_t *s);
void ft_putwchar(wchar_t c);
void ft_putwstr_fd(wchar_t *s, int fd);
void ft_putwchar_fd(wchar_t c, int fd);
int ft_atoi_base(char *str, int base);
unsigned int ft_atoi_unsigned(const char *str);
char *ft_strtolower(char *str);
size_t ft_strlcat(char *dest, const char *src, size_t size);
void ft_striteri(char *s, void (*f)(unsigned int, char *));
void ft_striter(char *s, void (*f)(char *));
void *ft_memalloc(size_t size);
void ft_memdel(void **ap);
void *ft_memchr(const void *s, int c, size_t n);
void *ft_memccpy(void *dest, const void *src, int c, size_t n);
void *ft_memcpy(void *dest, const void *src, size_t n);
void *ft_memcpy_swap(void *dest, const void *src, size_t n);
void *ft_memset(void *s, int c, size_t n);
void *ft_memmove(void *dst, const void *src, size_t n);
void ft_bzero(void *s, size_t n);
int ft_strnequ(char const *s1, char const *s2, size_t n);
int ft_strequ(char const *s1, char const *s2);
size_t ft_strlen(const char *str);
size_t ft_strlen_max(const char *str, size_t max);
int ft_strcmp(const char *s1, const char *s2);
int ft_strcmpi(const char *s1, const char *s2);
int ft_strncmpi(const char *s1, const char *s2, size_t n);
int ft_strncmp(const char *s1, const char *s2, size_t n);
int ft_toupper(int c);
int ft_tolower(int c);
int ft_memcmp(const void *s1, const void *s2, size_t n);
int ft_atoi(const char *str);
char *ft_strsub(char const *s, unsigned int start, size_t len);
char *ft_strmap(char const *s, char (*f)(char));
char *ft_strstr(const char *big, const char *little);
ssize_t ft_memstr(const char *big, const char *little, size_t len);
char *ft_strnstr(const char *big, const char *little, size_t n);
char *ft_strrchr(const char *s, int c);
char *ft_strchr(const char *s, int c);
char *ft_strcpy(char *dest, const char *src);
char *ft_strncpy(char *dest, const char *src, size_t n);
char *ft_itoa(int n);
char *win_linesitoa(uintmax_t num, unsigned int base, int *i);
char *ft_strcat(char *dest, const char *src);
char *ft_strncat(char *dest, const char *src, size_t n);
char *ft_strmapi(char const *s, char (*f)(unsigned int, char));
char **ft_strsplit(char const *s, char c);
char *ft_overwrite(char *string, char old, char new,\
ssize_t count);
size_t ft_strcount(char *str, char c);
size_t ft_memcount(char *str, char c, size_t len_str);
/*
** BITS FUNCTION
*/
void b_print(int size, void const *nb);
void b_print_array(t_array_byte array, char *split);
void b_print_fd(int size, void const *nb, int fd);
void b_print_array_fd(t_array_byte array, char *split, int fd);
t_array_byte b_new_secu(size_t nb, size_t lvl);
t_array_byte b_new(size_t nb);
t_array_byte b_dump_secu(const char *s, size_t len, size_t lvl);
t_array_byte b_dump(const char *s, size_t len);
t_array_byte b_clean_secu(t_array_byte arr);
t_array_byte b_clean(t_array_byte arr);
t_array_byte b_joinf_secu(t_array_byte dest, t_array_byte srcs,
int free, size_t lvl);
t_array_byte b_join_secu(t_array_byte dest, t_array_byte srcs,
size_t lvl);
t_array_byte b_joinf(t_array_byte dest, t_array_byte srcs, int free);
t_array_byte b_join(t_array_byte dest, t_array_byte srcs);
uint32_t left_rot32(uint32_t nb, unsigned int count);
uint32_t right_rot32(uint32_t nb, unsigned int count);
uint64_t left_rot64(uint64_t nb, unsigned int count);
uint64_t right_rot64(uint64_t nb, unsigned int count);
uint16_t ft_swap_int16(uint16_t x);
uint32_t ft_swap_int32(uint32_t x);
uint64_t ft_swap_int64(uint64_t x);
__uint128_t ft_swap_int128(__uint128_t x);
/*
** LOGGER
*/
int log_log(enum e_logger_lvl lvl, const char *format,
va_list list);
int log_init(char *filename, int fd);
void log_close(void);
void log_func_start(const char function[24]);
void log_func_end(const char function[24]);
void log_fatal(const char *fmt, ...);
void log_error(const char *fmt, ...);
void log_warn(const char *fmt, ...);
void log_info(const char *fmt, ...);
void log_debug(const char *fmt, ...);
size_t ft_align(size_t number, size_t divider);
size_t ft_align4(size_t number);
ssize_t ft_next_multiple(ssize_t number, size_t divisor);
int ft_getopt(int argc, char const *argv[],
const char *optstring);
char *ft_itochar(size_t size, const void *nb, t_bool is_little);
char *ft_itochar_secu(size_t size, const void *nb,
t_bool is_little, size_t lvl);
void close_reset(int *fd);
char *ft_getip(void);
char *ft_exp_path(const char *path,\
const char *abs_current);
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* log_wrappers.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/12/27 18:43:46 by gpouyat #+# #+# */
/* Updated: 2019/01/04 15:38:48 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/libft.h"
void log_fatal(const char *fmt, ...)
{
va_list list;
va_start(list, fmt);
log_log(LOG_LVL_FATAL, fmt, list);
va_end(list);
}
void log_error(const char *fmt, ...)
{
va_list list;
va_start(list, fmt);
log_log(LOG_LVL_ERROR, fmt, list);
va_end(list);
}
void log_warn(const char *fmt, ...)
{
va_list list;
va_start(list, fmt);
log_log(LOG_LVL_WARN, fmt, list);
va_end(list);
}
void log_info(const char *fmt, ...)
{
va_list list;
va_start(list, fmt);
log_log(LOG_LVL_INFO, fmt, list);
va_end(list);
}
void log_debug(const char *fmt, ...)
{
va_list list;
va_start(list, fmt);
log_log(LOG_LVL_DEBUG, fmt, list);
va_end(list);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_putnbr_base.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/01/11 19:07:41 by gpouyat #+# #+# */
/* Updated: 2018/10/08 16:49:42 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include <libft.h>
static char g_base_up[16] = {
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'A',
'B',
'C',
'D',
'E',
'F'
};
static char g_base_low[16] = {
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'a',
'b',
'c',
'd',
'e',
'f'
};
static void ft_putnbr_base_fd_up(unsigned int number, unsigned int base,
int fd, t_bool up)
{
char c;
if (base > 16 || !base)
return ;
if (number >= base)
{
ft_putsize_t_base_fd(number / base, base, fd);
ft_putsize_t_base_fd(number % base, base, fd);
}
if (number < (size_t)base)
{
c = up ? g_base_up[number] : g_base_low[number];
ft_putchar_fd(c, fd);
}
}
void ft_putnbr_base_fd(unsigned int number, unsigned int base, int fd)
{
ft_putnbr_base_fd_up(number, base, fd, True);
}
void ft_putnbr_base_fd_low(unsigned int number, unsigned int base,
int fd)
{
ft_putnbr_base_fd_up(number, base, fd, False);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* secure_memory.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/07/20 19:56:25 by gpouyat #+# #+# */
/* Updated: 2019/02/09 12:56:15 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef SECURE_MEMORY_H
# define SECURE_MEMORY_H
# include <stdlib.h>
# include <sys/types.h>
# include <signal.h>
# ifdef __APPLE__
# include <malloc/malloc.h>
# else
# define malloc_size(x) 0
# endif
# define MALLOC_LVL_DEFAULT 0
# define M_LVL_FUNCT 1
/*
** @file secure_memory.h
**
** @brief Function prototypes for the lexer module
**
** This contains the prototypes for the program,
** and eventually any macros, constants,
** or global variables you will need.
*/
/*
** @struct s_secu_malloc
**
** @brief Contains all the info for the secu_malloc functions
**
** @param ptr Pointer to the malloc memory area
** @param lvl Categorize the pointer
** @param prev Previous struct
** @param next Next struct
*/
struct s_secu_malloc
{
void *ptr;
size_t lvl;
struct s_secu_malloc *prev;
struct s_secu_malloc *next;
};
typedef struct s_secu_malloc t_secu_malloc;
/*
** @struct s_mem
**
** @brief Main struct to hold the malloc securely
**
** @param first First node
** @param last last node
*/
typedef struct s_mem
{
t_secu_malloc *first;
t_secu_malloc *last;
} t_mem;
/*
** @file ft_secu_free.c
**
** @brief Functions used to securely free
*/
void ft_secu_free(void *ptr);
void ft_secu_free_all(void);
void ft_secu_free_lvl(size_t lvl);
/*
** @file ft_secu_malloc.c
**
** @brief Functions to malloc securely
*/
void *secu_malloc(size_t size);
void *ft_secu_malloc_lvl(size_t size, size_t lvl);
t_mem *get_mem(void);
char *ft_strdup_secu(const char *str, size_t lvl);
char *ft_strnew_secu(size_t size, size_t lvl);
void *ft_secu_add(void *secu_ptr, size_t lvl);
void ft_secu_malloc_debug(void);
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* convers.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/10 07:42:13 by gpouyat #+# #+# */
/* Updated: 2018/10/11 13:55:01 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/libft.h"
char *ft_d(t_flags flags, char *format, va_list ap, int **i)
{
char *tmp;
char *tmp2;
int base;
if (!format || !i || !*i)
return (NULL);
base = (flags.convers == 'b' ? 2 : 10);
tmp = (flags.plus ? (pf_itoa_plusbase(ft_tnum(flags, ap), base)) :
(pf_itoa_base(ft_tnum(flags, ap), base)));
if (!tmp)
return (NULL);
if (flags.preci == 0 && ft_atoi(tmp) == 0)
tmp = ft_replace(tmp, "", 0, 1);
tmp2 = preci(flags, tmp);
free(tmp);
tmp = minus(flags, tmp2);
free(tmp2);
if (flags.space && !flags.plus && ft_atoi(tmp) >= 0)
tmp = ft_replace(tmp, " ", 0, 0);
tmp2 = width(flags, tmp);
free(tmp);
format = ft_replace(format, tmp2, **i, flags.size + 1);
**i = **i + ft_strlen(tmp2) - 1;
free(tmp2);
return (format);
}
char *ft_u(t_flags flags, char *format, va_list ap, int **i)
{
char *tmp;
char *tmp2;
if (!format || !i || !*i)
return (NULL);
if (flags.convers == 'U')
{
flags.type[0] = 'l';
flags.type[1] = 0;
}
tmp = pf_uitoa_base(ft_utnum(flags, ap), 10);
if (flags.preci == 0 && ft_atoi(tmp) == 0)
if (!(tmp = ft_replace(tmp, "", 0, 1)))
return (NULL);
tmp2 = preci(flags, tmp);
free(tmp);
tmp = minus(flags, tmp2);
free(tmp2);
tmp2 = width(flags, tmp);
free(tmp);
format = ft_replace(format, tmp2, **i, flags.size + 1);
**i = **i + ft_strlen(tmp2) - 1;
free(tmp2);
return (format);
}
char *ft_hs(t_flags flags, char *format, int **i)
{
char *tmp;
char *tmp2;
tmp = ft_strdup("%");
tmp2 = minus(flags, tmp);
free(tmp);
tmp = width(flags, tmp2);
free(tmp2);
format = ft_replace(format, tmp, **i, flags.size + 1);
**i = **i + ft_strlen(tmp) - 1;
free(tmp);
return (format);
}
char *ft_convers(t_flags *flgs, char *format, va_list ap, int *i)
{
t_flags flags;
flags = *flgs;
if (flags.convers == 'd' || flags.convers == 'i' || flags.convers == 'D'\
|| flags.convers == 'b')
return (ft_d(flags, format, ap, &i));
else if (flags.convers == 's')
return (ft_s(flags, format, ap, &i));
else if (flags.convers == '%')
return (ft_hs(flags, format, &i));
else if (flags.convers == 'x' || flags.convers == 'X'\
|| flags.convers == 'p')
return (ft_x(flags, format, ap, &i));
else if (flags.convers == 'o' || flags.convers == 'O')
return (ft_o(flags, format, ap, &i));
else if (flags.convers == 'c')
return (ft_c(&flgs, format, ap, &i));
else if (flags.convers == 'u' || flags.convers == 'U')
return (ft_u(flags, format, ap, &i));
else if (flags.convers == 'C')
return (ft_upc(&flgs, format, ap, &i));
else if (flags.convers == 'S')
return (ft_ups(flags, format, ap, &i));
return (format);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* btree_print.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/06/17 19:51:39 by gpouyat #+# #+# */
/* Updated: 2018/10/02 11:17:52 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_btree.h"
static int btree_strlen(char *s)
{
int i;
i = 0;
while (s[i])
i++;
return (i);
}
static void btree_display_str(char *str)
{
if (!str)
{
write(1, "NULL", 4);
return ;
}
write(1, str, btree_strlen(str));
}
void node_print(t_btree *this, int current_level, int max_level,\
char *(*applyf)(void *))
{
int i;
i = 0;
if (this)
{
node_print(this->right, current_level + 1, max_level, applyf);
while (i++ < current_level)
btree_display_str(" ");
btree_display_str(applyf(this->item));
btree_display_str("\n");
node_print(this->left, current_level + 1, max_level, applyf);
return ;
}
if (current_level < max_level)
{
node_print(NULL, current_level + 1, max_level, applyf);
while (i++ < current_level)
btree_display_str(" ");
btree_display_str("..\n");
node_print(NULL, current_level + 1, max_level, applyf);
}
}
void btree_print(t_btree *this, char *(*applyf)(void *))
{
if (!this)
return ;
btree_display_str("[--- Display tree ---]\n");
node_print(this, 0, btree_level_count(this), applyf);
btree_display_str("\n\n");
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* display_flags.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/12 15:36:30 by gpouyat #+# #+# */
/* Updated: 2018/10/11 13:52:00 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/libft.h"
char *preci(t_flags flags, char *str)
{
char *tmp;
char *complet;
int i;
int len;
i = 0;
if (!str)
return (NULL);
len = ft_strlen(str) - flags.plus - (str[0] == '-');
if (flags.preci > len)
{
if (!(tmp = ft_strnew(flags.preci - len)))
return (NULL);
if (str[0] == '+' || str[0] == '-')
{
tmp[i] = (str[0] == '+') ? '+' : '-';
str[0] = '0';
i++;
}
while (i != flags.preci - len)
tmp[i++] = '0';
complet = ft_strjoincl(tmp, str, 1);
return (complet);
}
return (ft_strdup(str));
}
char *width(t_flags flags, char *str)
{
char *tmp;
char *complet;
int i;
int len;
i = 0;
len = ft_strlen(str);
if (!str || flags.width <= len)
return (ft_strdup(str));
tmp = ft_strnew(flags.width - len);
str[1] = ((flags.hash && flags.zero && str[1]) ? '0' : str[1]);
while (tmp && i <= flags.width - len - 1)
{
tmp[i] = (flags.zero ? '0' : ' ');
i++;
}
if (!(complet = ft_strjoincl(tmp, str, 1)))
return (NULL);
if ((str[0] == '-' || str[0] == '+' || str[0] == ' ') && flags.zero)
{
complet[0] = str[0];
complet[flags.width - len] = (flags.zero ? '0' : ' ');
}
complet[1] = ((flags.hash && flags.zero && complet[1]) ? 'x' : complet[1]);
return (complet);
}
char *minus(t_flags flags, char *str)
{
char *tmp;
int len;
if (!str)
return (NULL);
len = ft_strlen(str);
if (flags.minus <= len)
return (ft_strdup(str));
if (!(tmp = ft_strnew(flags.minus + len)))
return (NULL);
tmp = ft_strcpy(tmp, str);
while (len <= flags.minus - 1)
{
tmp[len] = ' ';
len++;
}
return (tmp);
}
<file_sep># **************************************************************************** #
# #
# ::: :::::::: #
# Makefile :+: :+: :+: #
# +:+ +:+ +:+ #
# By: gpouyat <<EMAIL>> +#+ +:+ +#+ #
# +#+#+#+#+#+ +#+ #
# Created: 2017/02/05 12:29:27 by gpouyat #+# #+# #
# Updated: 2019/03/04 15:19:15 by gpouyat ### ########.fr #
# #
# **************************************************************************** #
# .NOTPARALLEL:
.PHONY: all clean fclean re
C_NO = \033[0m
C_G = \033[0;32m
C_Y = \033[1;33m
C_B = \033[1;34m
C_C = \033[1;36m
C_R = \033[1;31m
SRC_SUBDIR = libft_srcs/error
SRCS += error.c over_p_str.c over_p.c over_str.c over.c
SRC_SUBDIR += libft_srcs/list
SRCS += ft_lstadd.c ft_lstdel.c ft_lstdelone.c ft_lstfree.c ft_lstiter.c\
ft_lstmap.c ft_lstnew.c ft_lstpush.c ft_lstremove.c ft_lstsort.c
SRC_SUBDIR += libft_srcs/string
SRCS += ft_atoi_base.c ft_atoi.c ft_strcat.c ft_strchr.c ft_strcpy.c\
ft_striter.c ft_striteri.c ft_strlcat.c ft_strlen.c ft_strmap.c\
ft_strmapi.c ft_strncat.c ft_strncpy.c ft_strnstr.c ft_strrchr.c\
ft_strsplit.c ft_strstr.c ft_strsub.c ft_strtolower.c \
ft_overwrite.c ft_tolower.c ft_toupper.c ft_strcount.c
SRC_SUBDIR += libft_srcs/string/comp
SRCS += ft_strcmpa.c ft_strcmp.c ft_strequ.c ft_strncmp.c ft_strnequ.c
SRC_SUBDIR += libft_srcs/string/free
SRCS += ft_fri.c ft_strclr.c ft_strdel.c
SRC_SUBDIR += libft_srcs/string/is
SRCS += ft_isalnum.c ft_isalpha.c ft_isascii.c ft_isdigit.c ft_isprint.c\
ft_str_isdigit.c ft_str_isprint.c ft_str_isvalue.c
SRC_SUBDIR += libft_srcs/string/put
SRCS += ft_putchar.c ft_putchar_fd.c ft_putendl.c ft_putendl_fd.c\
ft_putnbr.c ft_putnbr_fd.c ft_putstr.c ft_putstr_fd.c \
ft_putsize_t_base_fd.c ft_putnbr_base.c
SRC_SUBDIR += libft_srcs/string/useMalloc
SRCS += ft_itoa_base.c ft_itoa.c ft_replace.c ft_strdup.c ft_strjoin.c\
ft_strnew.c ft_strtrim.c pf_itoa_base.c
SRC_SUBDIR += libft_srcs/string/wchar
SRCS += ft_getchar.c ft_putwchar.c ft_strwlen.c
SRC_SUBDIR += libft_srcs/tab
SRCS += ft_strdbldup.c ft_strdblfree.c ft_strdblnew.c ft_strdblprint.c\
tri.c ft_strdbllen.c
SRC_SUBDIR += libft_srcs/void
SRCS += ft_bzero.c ft_memalloc.c ft_memccpy.c ft_memchr.c ft_memcmp.c\
ft_memcpy.c ft_memdel.c ft_memmove.c ft_memset.c
SRC_SUBDIR += libft_srcs
SRCS += get_next_line.c ft_next_multiple.c ft_getopt.c ft_align.c \
ft_itochar.c close_reset.c ft_getip.c ft_exp_path.c get_next_str.c
SRC_SUBDIR += print_srcs
SRCS += convers.c display_flags.c ft_cs.c ft_o.c ft_printf.c ft_x.c get.c\
type_of_number.c color.c ft_dprintf.c print.c ft_vprintf.c
SRC_SUBDIR += secure_memory
SRCS += ft_secu_free.c ft_secu_malloc.c ft_strnew_secu.c ft_strdup_secu.c \
ft_secu_malloc_debug.c
SRC_SUBDIR += btree
SRCS += btree_apply_infix.c btree_apply_prefix.c btree_apply_suffix.c\
btree_create_node.c btree_destroy.c btree_insert_data.c\
btree_level_count.c btree_print.c btree_search_item.c\
SRC_SUBDIR += bits
SRCS += b_print.c b_new.c b_dump.c b_clean.c b_join.c rot.c swap.c
SRC_SUBDIR += logger
SRCS += log.c log_wrappers.c log_func.c
###############################################################################
# Compiler
NAME = libft.a
CC = clang
CFLAGS = -Wall -Wextra -Werror
UNAME_S := $(shell uname -s)
ifeq ($(UNAME_S), Linux)
CFLAGS += -fPIC
endif
ifeq ($(DEV),yes)
CFLAGS += -g -Wvla
endif
ifeq ($(SAN),yes)
CFLAGS += -fsanitize=address -fno-omit-frame-pointer -fno-optimize-sibling-calls
endif
#The Directories, Source, Includes, Objects and Libraries
INC = -I includes -I includes/intern
SRCS_DIR = sources
vpath %c $(addprefix $(SRCS_DIR)/,$(SRC_SUBDIR))
#Objects
OBJS_DIR = objs
OBJS = $(SRCS:%.c=$(OBJS_DIR)/%.o)
BUILD_DIR = $(OBJS_DIR) $(DEPS_DIR)
#Utils
RM = rm -rf
MKDIR = mkdir -p
COUNT = 0
TOTAL = 0
PERCENT = 0
$(eval TOTAL=$(shell echo $$(printf "%s" "$(SRCS)" | wc -w)))
###############################################################################
all: $(NAME)
$(NAME): $(OBJS)
@ar rc $(NAME) $(OBJS)
@ranlib $(NAME)
@echo
@echo "[\033[35m---------------------------------\033[0m]"
@echo "[\033[36m----------- Lib Done! -----------\033[0m]"
@echo "[\033[35m---------------------------------\033[0m]"
$(OBJS_DIR)/%.o: %.c | $(OBJS_DIR)
@$(CC) $(CFLAGS) $(INC) -o $@ -c $<
$(eval COUNT=$(shell echo $$(($(COUNT)+1))))
$(eval PERCENT=$(shell echo $$((($(COUNT) * 100 )/$(TOTAL)))))
@printf "$(C_B)%-8s $(C_Y) $<$(C_NO) \n" "[$(PERCENT)%]"
$(BUILD_DIR):
@$(MKDIR) $@
clean:
@echo "\033[35m$(NAME) :\033[0m [\033[31mSuppression des .o\033[0m]"
@$(RM) $(OBJS_DIR)
fclean: clean
@echo "\033[35m$(NAME) :\033[0m [\033[31mSuppression de $(NAME)\033[0m]"
@$(RM) $(NAME)
re: fclean all
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_secu_malloc.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/07/20 19:57:29 by gpouyat #+# #+# */
/* Updated: 2019/02/15 15:08:09 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/libft.h"
/*
** @brief Adds `secu_malloc` in `mem`
**
** @param secu_malloc Item to add
** @param mem List in which to add
*/
static void ft_s_malloc_mouv(t_secu_malloc *secu_malloc, t_mem *mem)
{
if (!mem->first)
{
mem->first = secu_malloc;
mem->last = secu_malloc;
secu_malloc->prev = NULL;
secu_malloc->next = NULL;
}
else
{
secu_malloc->prev = mem->last;
mem->last->next = secu_malloc;
mem->last = secu_malloc;
}
}
/*
** @brief Securely mallocs with a category
**
** @param size Size to be malloced
** @param lvl Pointer category
**
** @return Returns a pointer to the malloced area in memory
*/
void *ft_secu_malloc_lvl(size_t size, size_t lvl)
{
void *ptr;
if (!(ptr = ft_memalloc(size)))
{
free(secu_malloc);
over("Malloc secu: Malloc failed (return NULL)", 2);
return (NULL);
}
return (ft_secu_add(ptr, lvl));
}
/*
** @brief Securely allocates memoy
** @param size Size of malloc
** @return Pointer to the area of memory which has been allocated
*/
void *secu_malloc(size_t size)
{
return (ft_secu_malloc_lvl(size, MALLOC_LVL_DEFAULT));
}
/*
** @brief Singleton to get the mem struct
**
** @return Return the `mem` struct
*/
t_mem *get_mem(void)
{
static t_mem *mem = NULL;
if (mem == NULL)
{
if (!(mem = (t_mem *)ft_memalloc(sizeof(t_mem))))
{
over("Malloc secu: Malloc failed", 2);
return (NULL);
}
mem->first = NULL;
mem->last = NULL;
}
return (mem);
}
void *ft_secu_add(void *secu_ptr, size_t lvl)
{
t_mem *mem;
t_secu_malloc *secu_malloc;
mem = get_mem();
if (!mem ||
!(secu_malloc = (t_secu_malloc*)ft_memalloc(sizeof(t_secu_malloc))))
{
over("Malloc secu: Malloc failed (return NULL)", 2);
return (NULL);
}
secu_malloc->lvl = lvl;
secu_malloc->ptr = secu_ptr;
secu_malloc->next = NULL;
ft_s_malloc_mouv(secu_malloc, mem);
return (secu_ptr);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_itochar.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/12/25 20:33:12 by gpouyat #+# #+# */
/* Updated: 2019/01/04 15:31:58 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/libft.h"
char *ft_itochar(size_t size, const void *nb, t_bool is_little)
{
char *ret;
if (!(ret = ft_memalloc(size)))
return (NULL);
if (is_little)
ft_memcpy_swap(ret, nb, size);
else
ft_memcpy(ret, nb, size);
return (ret);
}
char *ft_itochar_secu(size_t size, const void *nb, t_bool is_little,
size_t lvl)
{
char *ret;
if (!(ret = ft_secu_malloc_lvl(size, lvl)))
return (NULL);
if (is_little)
ft_memcpy_swap(ret, nb, size);
else
ft_memcpy(ret, nb, size);
return (ret);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* color.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/12/21 18:23:22 by guiforge #+# #+# */
/* Updated: 2018/10/02 11:06:24 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef COLOR_H
# define COLOR_H
# define C_NONE "\033[0m"
# define C_BOLD "\033[1m"
# define C_UNDER "\033[4m"
# define C_FLASH "\033[5m"
# define C_REVERS "\033[7m"
# define C_BLACK "\033[30m"
# define C_RED "\033[31m"
# define C_GREEN "\033[32m"
# define C_BROWN "\033[33m"
# define C_BLUE "\033[34m"
# define C_MAGENTA "\033[35m"
# define C_CYAN "\033[36m"
# define C_GREY "\033[37m"
# define B_BLACK "\033[40m"
# define B_RED "\033[41m"
# define B_GREEN "\033[42m"
# define B_ORANGE "\033[43m"
# define B_BLUE "\033[44m"
# define B_CYAN "\033[46m"
# define B_GREY "\033[47m"
# define CD_GREY "\033[90m"
# define CL_RED "\033[91m"
# define CL_GREEN "\033[92m"
# define C_YELLOW "\033[93m"
# define CL_BLUE "\033[94m"
# define CL_TURQ "\033[96m"
# define BD_GREY "\033[100m"
# define BL_RED "\033[101m"
# define BL_GREEN "\033[102m"
# define B_YELLOW "\033[103m"
# define BL_BLUE "\033[104m"
# define BL_PURPLE "\033[105m"
# define B_TURQ "\033[106m"
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_btree.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/06/17 10:44:56 by gpouyat #+# #+# */
/* Updated: 2018/10/02 11:09:38 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FT_BTREE_H
# define FT_BTREE_H
# include <stdlib.h>
# include <unistd.h>
typedef struct s_btree
{
struct s_btree *parent;
struct s_btree *left;
struct s_btree *right;
void *item;
} t_btree;
t_btree *btree_create_node(void *item);
void btree_apply_suffix(t_btree *root, void (*applyf)(void *));
void btree_apply_prefix(t_btree *root, void (*applyf)(void *));
void btree_apply_infix(t_btree *root, void (*applyf)(void *));
void btree_destroy(t_btree **root, void (*del)(void *));
void btree_insert_data(t_btree **root, void *item,
int (*cmpf)(void *, void *));
int btree_level_count(t_btree *root);
void *btree_search_item(t_btree *root, void *data_ref,
int (*cmpf)(void *, void *));
void btree_print(t_btree *this, char *(*applyf)(void *));
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_exp_path.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/02/13 14:53:45 by gpouyat #+# #+# */
/* Updated: 2019/02/15 15:08:52 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/libft.h"
/*
** @brief This function will find the first `..` it will find in the string
** `path` and return a pointer to it.
**
** @param path The string to search into
**
** @return Returns a pointer to the first `..` it'll find in `path`
*/
static char *find_start_ddots(char *path, char *start2)
{
char *start;
char *tmp;
if (!path)
return (NULL);
start = path;
while ((tmp = ft_strchr(start, '/')) != start2 && tmp)
{
start = tmp;
start++;
}
return (start);
}
/*
** @brief Removes the extraneous dots for given `path`.
**
** @param path String containing a path to remove the extraneous dots from.
**
** @return Returns the modified path without the extraneous dots inside.
*/
static char *remove_dots(char *path)
{
char *start;
char *start2;
if (!path)
return (NULL);
while ((start = ft_strstr(path, "/./")) ||\
((start = ft_strstr(path, "/.")) && !start[2]))
ft_memcpy(start, start + 2, ft_strlen(start + 1));
while ((start2 = ft_strstr(path, "/../")) ||\
((start2 = ft_strstr(path, "/..")) && !start2[3]))
{
start = find_start_ddots(path, start2);
if (start == path)
start++;
if (!*start)
return (path);
if (start2[3] == '/')
start2++;
ft_memcpy(start, start2 + 3, ft_strlen(start2 + 2));
}
if (path && ft_strlen(path) > 2 &&
ft_strequ(&path[ft_strlen(path) - 2], "/."))
path[ft_strlen(path) - 1] = 0;
return (path);
}
/*
** @brief Removes the extraneous backslashes from a given `path`
**
** @param path String containing a path to remove the extraneous backslashes
** from.
**
** @return Returns the modified path without the extraneous backslashes inside.
*/
static char *remove_backslash(char *path)
{
char *start;
if (!path)
return (NULL);
while ((start = ft_strstr(path, "//")) && ft_strlen(start + 2))
ft_memcpy(start + 1, start + 2, ft_strlen(start + 1));
while (path && ft_strlen(path) > 1 && path[ft_strlen(path) - 1] == '/')
path[ft_strlen(path) - 1] = 0;
return (path);
}
static char *get_abspath(const char *path, const char *abs_current)
{
char current[PATH_MAX + 1];
char *ret;
if (abs_current)
{
ft_bzero(current, PATH_MAX + 1);
ft_strncpy(current, abs_current, PATH_MAX);
}
else if (!getcwd(current, PATH_MAX))
return (NULL);
if (path && *path != '/')
{
ret = ft_strnew(ft_strlen(current) + ft_strlen(path) + 1);
if (!ret)
return (NULL);
ft_strcat(ret, current);
ft_strcat(ret, "/");
ft_strcat(ret, path);
}
else
ret = ft_strdup(path);
return (ret);
}
/*
** @brief This function will expand a path given through a pointer.\n
** It will first remove the dots then the backslashes. If a `./` or a `//` are
** found in the modified string, the function will reset the modified path
** and return the original one.
**
** @param path The filename/path you want to modify
**
** @return path Returns the modified path
*/
char *ft_exp_path(const char *path, const char *abs_current)
{
char *ret;
size_t len;
if (!path)
return (NULL);
ret = get_abspath(path, abs_current);
if (!ret)
return (NULL);
ret = remove_dots(remove_backslash(ret));
if (ret)
{
len = ft_strlen(ret) - 1;
if (ret[len] == '/' && len != 0)
ret[len] = 0;
}
if (ft_strstr(ret, "./") || ft_strstr(ret, "//"))
{
log_fatal("CD expand PATH wrong ! (%s) so return (NULL)", ret);
ft_strdel(&ret);
return (NULL);
}
return (ret);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* log_func.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/12/27 23:54:42 by gpouyat #+# #+# */
/* Updated: 2019/01/11 19:22:37 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/libft.h"
static size_t g_tabs = 0;
static void print_tabs(void)
{
size_t tmp;
tmp = g_tabs;
while (tmp)
{
ft_putchar_fd(' ', g_log_fd);
tmp--;
}
}
void log_func_start(const char function[24])
{
if (!g_log_fd)
return ;
print_tabs();
ft_dprintf(g_log_fd, "{blue}[*] Start -- %s{no}\n", function);
g_tabs++;
}
void log_func_end(const char function[24])
{
if (!g_log_fd)
return ;
g_tabs--;
print_tabs();
ft_dprintf(g_log_fd, "{blue}[*] End --- %s{no}\n", function);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* b_print.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/12/23 15:07:39 by gpouyat #+# #+# */
/* Updated: 2019/01/04 15:30:25 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../../includes/libft.h"
void b_print(int size, void const *nb)
{
unsigned char *b;
unsigned char bit;
int j;
b = (unsigned char *)nb;
while (--size >= 0)
{
j = 8;
while (--j >= 0)
{
bit = (b[size] >> j) & 1;
ft_putnbr(bit);
}
}
}
void b_print_array(t_array_byte array, char *split)
{
size_t i;
i = 0;
while (i < array.nb)
{
if (i)
ft_putstr(split);
b_print(sizeof(char), &array.bytes[i]);
++i;
}
ft_putchar('\n');
}
void b_print_fd(int size, void const *nb, int fd)
{
unsigned char *b;
unsigned char bit;
int j;
b = (unsigned char *)nb;
while (--size >= 0)
{
j = 8;
while (--j >= 0)
{
bit = (b[size] >> j) & 1;
ft_putnbr_fd(bit, fd);
}
}
}
void b_print_array_fd(t_array_byte array, char *split, int fd)
{
size_t i;
i = 0;
while (i < array.nb)
{
if (i)
ft_putstr_fd(split, fd);
b_print_fd(sizeof(char), &array.bytes[i], fd);
++i;
}
ft_putchar_fd('\n', fd);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_printf.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/09 14:33:06 by gpouyat #+# #+# */
/* Updated: 2018/12/27 17:54:07 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef FT_PRINTF_H
# define FT_PRINTF_H
# include <stdarg.h>
typedef struct s_flags
{
unsigned char hash;
unsigned char space;
unsigned char plus;
char convers;
char type[3];
int minus;
int preci;
int width;
int zero;
int size;
} t_flags;
uintmax_t ft_utnum(t_flags flags, va_list ap);
intmax_t ft_tnum(t_flags flags, va_list ap);
char *minus(t_flags flags, char *str);
char *width(t_flags flags, char *str);
char *preci(t_flags flags, char *str);
void check(t_flags flags, char *format);
char *ft_x(t_flags flags, char *format, va_list ap, int **i);
char *ft_o(t_flags flags, char *format, va_list ap, int **i);
char *ft_s(t_flags flags, char *format, va_list ap, int **i);
char *ft_c(t_flags **flags, char *format, va_list ap,
int **i);
char *ft_ups(t_flags flags, char *format, va_list ap,
int **i);
char *ft_upc(t_flags **flags, char *format, va_list ap,
int **i);
char *ft_convers(t_flags *flags, char *format, va_list ap,
int *i);
int ft_printf(char *format, ...);
t_flags get_struct(t_flags flags, char *format);
int print(int fd, char *frmt, va_list ap);
char *pf_couleur(char *format);
int ft_dprintf(int fd, char *frmt, ...);
int ft_vprintf(const char *format, va_list ap);
int ft_vdprintf(int fd, const char *format, va_list ap);
#endif
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_getopt.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/04/29 15:01:10 by gpouyat #+# #+# */
/* Updated: 2019/03/10 14:38:59 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
#include "ft_getopt.h"
int g_optind = 1;
int g_opterr = 1;
char *g_optarg = NULL;
int g_optopt;
static int ft_getopt_init(int argc, char const *argv[])
{
if (argc > g_optind && ft_strequ(argv[g_optind], "--"))
{
g_optind++;
return (-1);
}
if (argc <= g_optind || *argv[g_optind] != '-')
return (-1);
return (0);
}
static char ft_getopt_current(char **next, const char **argv)
{
char ret;
if (!*next || !**next)
*next = (char *)argv[g_optind] + 1;
ret = **next;
if (ret)
++*next;
if (!**next)
g_optind++;
g_optopt = ret;
g_optarg = NULL;
return (ret);
}
static int ft_getopt_check(char search, const char *opstring)
{
int index;
index = -1;
while (opstring && opstring[++index])
if (opstring[index] == search)
return (opstring[index + 1] == ':');
return (-1);
}
static int ft_getopt_error(const char *prgm, char current, int err)
{
char current_str[2];
current_str[0] = current;
current_str[1] = 0;
ft_putstr_fd(prgm, STDERR_FILENO);
if (err == FT_GETOPT_OPT_REQ)
{
over_p_str(": option requires an argument --", current_str);
}
else if (err == FT_GETOPT_INV_OPT)
{
over_p_str(": illegal option -- ", current_str);
}
return ((int)'?');
}
int ft_getopt(int argc, char const *argv[], const char *optstring)
{
static char *next = NULL;
int check;
char current;
if (ft_getopt_init(argc, argv))
return (-1);
current = ft_getopt_current(&next, argv);
check = ft_getopt_check(current, optstring);
if (ft_isalnum(current) && check != -1)
{
if (check == 1)
{
if (*next)
g_optarg = next;
else if (argv[g_optind])
g_optarg = (char *)argv[g_optind];
else
return (ft_getopt_error(*argv, current, FT_GETOPT_OPT_REQ));
next = NULL;
g_optind++;
}
return (g_optopt);
}
return (ft_getopt_error(*argv, current, FT_GETOPT_INV_OPT));
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_cs.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gpouyat <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/01/21 17:08:21 by gpouyat #+# #+# */
/* Updated: 2018/10/11 14:55:35 by gpouyat ### ########.fr */
/* */
/* ************************************************************************** */
#include "../includes/libft.h"
static char *end_format(t_flags flags, char *format, int **i, char *tmp)
{
char *tmp2;
if (!format || !i || !tmp)
{
free(tmp);
return (NULL);
}
tmp2 = preci(flags, tmp);
free(tmp);
tmp = minus(flags, tmp2);
free(tmp2);
tmp2 = width(flags, tmp);
free(tmp);
format = ft_replace(format, tmp2, **i, flags.size + 1);
**i = **i + ft_strlen(tmp2) - 1;
free(tmp2);
return (format);
}
char *ft_s(t_flags flags, char *format, va_list ap, int **i)
{
char *tmp;
char *tmp2;
if (!format || !i || !*i)
return (NULL);
tmp = va_arg(ap, char*);
if (tmp && (tmp = ft_strdup(tmp)))
{
if ((unsigned int)flags.preci < (unsigned int)ft_strlen(tmp))
tmp[flags.preci] = 0;
tmp2 = (ft_strcmp(tmp, "") ? minus(flags, tmp) : ft_strdup(tmp));
free(tmp);
tmp = width(flags, tmp2);
free(tmp2);
format = ft_replace(format, tmp, **i, flags.size + 1);
**i = **i + ft_strlen(tmp) - 1;
free(tmp);
}
else
format = ft_replace(format, "(null)", **i, flags.size + 1);
return (format);
}
char *ft_c(t_flags **flgs, char *format, va_list ap, int **i)
{
char *tmp;
int c;
t_flags flags;
if (!format || !i || !*i)
return (NULL);
flags = **flgs;
if (!(c = va_arg(ap, int)))
{
(**flgs).type[2] = -1;
flags.preci = 0;
flags.width--;
}
if (!(tmp = ft_strnew(1)))
return (NULL);
tmp[0] = (char)c;
return (end_format(flags, format, i, tmp));
}
char *ft_upc(t_flags **flgs, char *format, va_list ap, int **i)
{
char *tmp;
int c;
t_flags flags;
if (!format || !i || !*i)
return (NULL);
flags = **flgs;
c = va_arg(ap, wchar_t);
if (c == 0)
{
flags.type[2] = -1;
return (ft_replace(format, "\0", **i, flags.size + 1));
}
tmp = ft_getchar(c);
return (end_format(flags, format, i, tmp));
}
char *ft_ups(t_flags flags, char *format, va_list ap, int **i)
{
char *tmp;
char *tmp2;
if (!format || !i || !*i)
return (NULL);
tmp = ft_getwstr(va_arg(ap, wchar_t*));
if (tmp)
{
if ((unsigned int)flags.preci < (unsigned int)ft_strlen(tmp))
tmp[flags.preci] = 0;
tmp2 = minus(flags, tmp);
free(tmp);
tmp = width(flags, tmp2);
free(tmp2);
format = ft_replace(format, tmp, **i, flags.size + 1);
**i = **i + ft_strlen(tmp) - 1;
free(tmp);
}
else
format = ft_replace(format, "(null)", **i, flags.size + 1);
return (format);
}
|
4ba938678b30226b92a88ca2a65937d19b584a56
|
[
"Markdown",
"C",
"Makefile"
] | 37
|
C
|
Guiforge/libft
|
4f5236f52619dc368537b420f5a53c7f1ae8f757
|
57a8022c5b0071a4b3ee1be97bac4f5fb18a4dee
|
refs/heads/master
|
<file_sep>package com.company.calculation;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.Phaser;
/**
* Created by Yevgen on 03.04.2016 as a part of the project "JEE_Unit_3.2_Homework".
*/
public class CalcSquareSumPart implements Callable<Long> {
private static final String DIAGNOSTIC_PATTERN = "Class name: %s, Thread: %s, startIndex: %d, quantity of elements: %d, result: %d";
private static final String AFTER_PARSING_BARRIER_PATTERN = "Class name: %s, Thread: %s: After parsing barrier";
public static final String SLEEPING_PATTERN = "Class name: %s, Thread: %s is sleeping for %d ms ...";
private int[] values;
private int startIndex;
private int elementQuantity;
private boolean executionIllustrate;
private int sleepingIntervalBound;
private Phaser phaser;
private HashMap<String, Long> resultMap;
public CalcSquareSumPart(int[] values, int startIndex, int elementQuantity, boolean showDiagnostic,
int sleepingIntervalBound, Phaser phaser, HashMap<String, Long> resultMap) {
this.values = values;
this.startIndex = startIndex;
this.elementQuantity = elementQuantity;
this.executionIllustrate = showDiagnostic;
this.sleepingIntervalBound = sleepingIntervalBound;
this.phaser = phaser;
this.resultMap = resultMap;
if (phaser != null) {
// Adds this task as a new unarrived party to this phaser.
phaser.register();
}
}
public CalcSquareSumPart(int[] values, int startIndex, int elementQuantity,
boolean showDiagnostic, int sleepingIntervalBound) {
this (values, startIndex, elementQuantity, showDiagnostic, sleepingIntervalBound, null, null);
}
private long getSquareSum() {
long result = 0L;
int upperLimit = startIndex + elementQuantity;
upperLimit = upperLimit <= values.length ? upperLimit : values.length;
for (int i = startIndex; i < upperLimit; i++) {
result += Math.pow(values[i], 2);
}
if (executionIllustrate) {
// To show the thread execute order ...
int sleepingInterval = (sleepingIntervalBound <= 0) ? sleepingIntervalBound :
new Random().nextInt(sleepingIntervalBound);
if (sleepingInterval > 0) {
System.out.println(String.format(SLEEPING_PATTERN, getClass().getName(), Thread.currentThread().getName(), sleepingInterval));
try {
Thread.sleep(sleepingInterval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(String.format(DIAGNOSTIC_PATTERN, getClass().getName(), Thread.currentThread().getName(),
startIndex, elementQuantity, result));
}
return result;
}
@Override
public Long call() throws Exception {
Long result = getSquareSum();
// Store result if it needs
if (resultMap != null) {
resultMap.put(Thread.currentThread().getName(), result);
}
if (phaser != null) {
phaser.arriveAndDeregister();
if (executionIllustrate) {
System.out.println(String.format(AFTER_PARSING_BARRIER_PATTERN, getClass().getName(),
Thread.currentThread().getName()));
}
}
return result;
}
}
<file_sep>package com.company.test;
import com.company.calculation.SquareSumUsingFuture;
import com.company.calculation.SquareSumUsingPhaser;
import java.util.Random;
/**
* Created by Yevgen on 02.04.2016 as a part of the project "JEE_Unit_3.2_Homework".
*/
public class SquareSumTest {
private final static String IMPLEMENTATION_INFORMATION_PATTERN = "The <%s> execution ... ";
private final static String RESULT_MESSAGE_PATTERN =
"The result of the square sum of the %d random generating from %d to %d integer elements, " +
"calculating by using %d threads, is: %d";
private final static int ARRAY_SIZE = 100000;
private final static int ELEMENT_VALUE_ORIGIN = 0;
private final static int ELEMENT_VALUE_BOUND = 1000;
private final static int NUMBER_OF_THREADS = 4;
private int[] generateTestData() {
return new Random().ints(ARRAY_SIZE, ELEMENT_VALUE_ORIGIN, ELEMENT_VALUE_BOUND).toArray();
}
public void demonstrate(boolean executionIllustrate, int sleepingIntervalBound) {
int[] testData = generateTestData();
System.out.println(String.format(IMPLEMENTATION_INFORMATION_PATTERN, SquareSumUsingFuture.class.getName()));
System.out.println(String.format(RESULT_MESSAGE_PATTERN, testData.length, ELEMENT_VALUE_ORIGIN, ELEMENT_VALUE_BOUND,
NUMBER_OF_THREADS, new SquareSumUsingFuture(executionIllustrate, sleepingIntervalBound).
getSquareSum(testData, NUMBER_OF_THREADS)));
System.out.println(String.format(IMPLEMENTATION_INFORMATION_PATTERN, SquareSumUsingPhaser.class.getName()));
System.out.println(String.format(RESULT_MESSAGE_PATTERN, testData.length, ELEMENT_VALUE_ORIGIN, ELEMENT_VALUE_BOUND,
NUMBER_OF_THREADS, new SquareSumUsingPhaser(executionIllustrate, sleepingIntervalBound).
getSquareSum(testData, NUMBER_OF_THREADS)));
}
}
<file_sep>package com.company.calculation;
import com.company.calculation.CalcSquareSumPart;
import com.company.calculation.SquareSum;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Phaser;
/**
* Created by Yevgen on 03.04.2016 as a part of the project "JEE_Unit_3.2_Homework".
*/
public class SquareSumUsingPhaser implements SquareSum {
private boolean executionIllustrate;
private int sleepingIntervalBound;
public SquareSumUsingPhaser(boolean executionIllustrate, int sleepingIntervalBound) {
this.executionIllustrate = executionIllustrate;
this.sleepingIntervalBound = sleepingIntervalBound;
}
@Override
public long getSquareSum(int[] values, int numberOfThreads) {
Phaser phaser = new Phaser(1);
ExecutorService executor = Executors.newFixedThreadPool(numberOfThreads);
HashMap<String, Long> resultMap = new HashMap<>();
try {
int startIndex = 0;
int elementQuantity = values.length / numberOfThreads;
for (int i = 0; i < numberOfThreads; i++) {
int thisPortion = elementQuantity + ((i == 0) ? (values.length % numberOfThreads) : 0);
// Intentionally do not use <Future> here just to demonstrate phaser-mechanism
executor.submit(new CalcSquareSumPart(values, startIndex, thisPortion, executionIllustrate,
sleepingIntervalBound, phaser, resultMap));
startIndex += thisPortion;
}
} finally {
executor.shutdown();
}
// Wait for all parties on this phaser ...
phaser.arriveAndAwaitAdvance();
// Sleep for some time to show the order of execution
if (executionIllustrate) {
int sleepingInterval = (sleepingIntervalBound <= 0) ? sleepingIntervalBound :
new Random().nextInt(sleepingIntervalBound);
if (sleepingInterval > 0) {
System.out.println(String.format(CalcSquareSumPart.SLEEPING_PATTERN, getClass().getName(),
Thread.currentThread().getName(), sleepingInterval));
try {
Thread.sleep(sleepingInterval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return resultMap.values().stream().mapToLong(e -> e).sum();
}
}
|
b9af6b33674b449e254ea24aad7e8a1d09c818d4
|
[
"Java"
] | 3
|
Java
|
khomyakeugene/JEE_Unit_3.2_Homework
|
7ceff6e7d487bf1350b9f6be0aa66b0ef42b6e9f
|
d7b37fd6cbd195dbb372dad9b41d858094017c20
|
refs/heads/master
|
<file_sep>var work = {
"jobs": [
{
"employer": "Oracle",
"title": "Programmer",
"location": "Reedwood City, CA",
"dates": "Aug 1950 - Present",
"description": "Our team is in charge of implementation, development and operational support of Oracle R12 critical systems, more specifically Oracle Financials, Oracle E-Business Suite, Oracle Fusion, and Oracle ERP. We support countries with high volume transactions and our work has leading to a considerable reduction of bugs and an overall improvement of the modules through new enhancements. I have experience in Business Intelligence and Oracle Report adapting and improving several financials report that lead to a better decision making and auditory purposes for in the business. I also work in several internal projects to implement new solutions to extend and adapt the current system to Oracle evolving needs.",
"url":"http://www.oracle.com"
},
{
"employer": "<NAME>",
"title": "Front End Web Developer",
"location": "Jalisco, Mexico",
"dates": "Aug 2011 - Aug 2012",
"description": "Deviced, designed and developer nice and friendly web sites for commercial and marketing purpouses using standard web technologies. I also developed several mini games in android to archieve a effective position branding of the companies we worked with.",
"url":"http://www.sangsang.com.mx"
},
{
"employer": "National Autonomous University of Mexico",
"title": "Instructor",
"location": "DF, Mexico",
"dates": "Aug 2010 - Aug 2011",
"description": "I studied computer engineering in one of the top universities in Latin America and took several extracurricular courses in mathematics, social sciences and languages. I worked as a part time instructor giving introductory courses of mathematics, physics and programming to freshmen.",
"url": "http://www.unam.mx"
}
],
display: function(){
var formatedWorkEmployer, formattedWorkTitle, formattedWorkDates, formatedWorkLocation, formattedWorkDescription;
var jobs = work.jobs;
for(var job in jobs){
$("#workExperience").append(HTMLworkStart);
formatedWorkEmployer = HTMLworkEmployer.replace("%data%", jobs[job].employer);
formatedWorkEmployer = formatedWorkEmployer.replace("#", jobs[job].url);
formattedWorkTitle = HTMLworkTitle.replace("%data%", jobs[job].title);
formattedWorkDates = HTMLworkDates.replace("%data%", jobs[job].dates);
formatedWorkLocation = HTMLworkLocation.replace("%data%", jobs[job].location);
formattedWorkDescription = HTMLworkDescription.replace("%data%", jobs[job].description);
$(".work-entry:last").append(formatedWorkEmployer + formattedWorkTitle);
$(".work-entry:last").append(formattedWorkDates);
$(".work-entry:last").append(formatedWorkLocation);
$(".work-entry:last").append(formattedWorkDescription);
}
} // display ends
}; //work ends
var projects = {
"projects":[
{
"title": "Interactive Resume",
"dates": "Winter 2014",
"description": "A web based interactive resume",
"url": "https://github.com/chinokhan/Nano1-P2",
"images": ["images/p1.1.jpg","images/p1.2.jpg"]
},
{
"title": "Mockup Web Site",
"dates": "Winter 2014",
"description": "A simple template to create web sites",
"url": "https://github.com/chinokhan/Nano1-P1",
"images": []
}
],
display: function(){
var formattedProjectTitle, formattedProjectDates, formattedProjectDescription, formattedProjectImage;
var p = projects.projects;
for(var project in p){
$("#projects").append(HTMLprojectStart);
formattedProjectTitle = HTMLprojectTitle.replace("%data%", p[project].title);
formattedProjectDates = HTMLprojectDates.replace("%data%", p[project].dates);
formattedProjectDescription = HTMLprojectDescription.replace("%data%", p[project].description);
formattedProjectTitle = formattedProjectTitle.replace("#", p[project].url);
$(".project-entry:last").append(formattedProjectTitle);
$(".project-entry:last").append(formattedProjectDates);
$(".project-entry:last").append(formattedProjectDescription);
$(".project-entry:last").append(HTMLprojectImagesStart);
for(var i=0, n=p[project].images.length; i<n; i++){
formattedProjectImage = HTMLprojectImage.replace("%data%", p[project].images[i]);
$(".project-imgs:last").append(formattedProjectImage);
}
}
}//display ends
}; //projects ends
var education = {
"schools": [
{
"name": "Free University of Berlin",
"location": "Berlin, Germany",
"degree": "Computer Engineering",
"majors": ["Computer Science"],
"dates": 2013,
"url": "http://www.fu-berlin.de/en/"
},
{
"name": "National Autonomous University of Mexico",
"location": "DF, Mexico",
"degree": "Computer Engineering",
"majors": ["Computer Science","Mathematics"],
"dates": 2012,
"url": "http://www.unam.mx"
},
{
"name": "Escuela Nacional Preparatoria",
"location": "DF, Mexico",
"degree": "Computer technician",
"majors": ["Mechanics"],
"dates": 2006,
"url": "http://www.prepa9.unam.mx"
}
],
"onlineCourses" : [
{
"title": "Front End Web Developer",
"school": "Udacity",
"dates": 2015,
"url": "http://www.udacity.com"
},
{
"title": "Javascript Roadtrip",
"school": "Codeschool",
"dates": 2015,
"url": "http://www.codeschool.com"
},
{
"title": "Javascript Best Practices",
"school": "Codeschool",
"dates": 2015,
"url": "http://www.codeschool.com"
}
],
display: function(){
var formattedSchoolName,
formattedSchoolDegree,
formattedSchoolDates,
formattedSchoolLocation,
formattedSchoolMajor,
schools = education.schools;
for(var school in schools){
$("#education").append(HTMLschoolStart);
formattedSchoolName = HTMLschoolName.replace("%data%", schools[school].name);
formattedSchoolName = formattedSchoolName.replace("#", schools[school].url);
formattedSchoolDegree = HTMLschoolDegree.replace("%data%", schools[school].degree);
formattedSchoolDates = HTMLschoolDates.replace("%data%", schools[school].dates);
formattedSchoolLocation = HTMLschoolLocation.replace("%data%", schools[school].location);
$(".education-entry:last").append(formattedSchoolName + formattedSchoolDegree);
$(".education-entry:last").append(formattedSchoolDates);
$(".education-entry:last").append(formattedSchoolLocation);
for(var i=0, n=schools[school].majors.length; i<n; i++){
formattedSchoolMajor = HTMLschoolMajor.replace("%data%", schools[school].majors[i]);
$(".education-entry:last").append(formattedSchoolMajor);
}
}
$("#education").append(HTMLonlineClasses);
var formatedOnlineTitle,
formatedOnlineSchool,
formatedOnlineDates,
courses = education.onlineCourses;
for(var course in courses){
$("#education").append(HTMLschoolStart);
formatedOnlineTitle = HTMLonlineTitle.replace("%data%", courses[course].title);
formatedOnlineTitle = formatedOnlineTitle.replace("#", courses[course].url);
formatedOnlineSchool = HTMLonlineSchool.replace("%data%", courses[course].school);
formatedOnlineDates = HTMLonlineDates.replace("%data%", courses[course].dates);
$(".education-entry:last").append(formatedOnlineTitle + formatedOnlineSchool);
$(".education-entry:last").append(formatedOnlineDates);
$(".education-entry:last").append("<br>");
}
} //display ends
}; //education ends
var bio = {
"name": "<NAME>",
"role": "Front End Web Ninja",
"welcomeMessage": "Welcome to my kingdom",
"skills" : ["Oracle Database", "PL/SQL", "Oracle Applications", "Oracle R12",
"Oracle Fusion Middleware", "HTML5", "CSS3", "Javascript", "JSON",
"Bootstrap", "AngularJS", "Polymer"],
"contacts" : {
"mobile": "+52 1 33 39 45 38 62",
"email": "<EMAIL>",
"github": "jamesbond",
"twitter": "@jamesbond",
"location": "Mexico"
},
"biopic" : "images/myPic.jpg",
display: function(){
var formattedHTMLheaderName, formattedHTMLheaderRole, formattedHTMLmobile,
formattedHTMLemail, formattedHTMLtwitter, formattedHTMLgithub,
formatedHTMLlocation, formattedHTMLbioPic, formattedWelcomeMsg;
formattedHTMLheaderName = HTMLheaderName.replace("%data%", bio.name);
formattedHTMLheaderRole = HTMLheaderRole.replace("%data%", bio.role);
formattedHTMLmobile = HTMLmobile.replace("%data%", bio.contacts.mobile);
formattedHTMLemail = HTMLemail.replace("%data%", bio.contacts.email);
formattedHTMLtwitter = HTMLtwitter.replace("%data%", bio.contacts.twitter);
formattedHTMLgithub = HTMLgithub.replace("%data%", bio.contacts.github);
formatedHTMLlocation = HTMLlocation.replace("%data%", bio.contacts.location);
formattedHTMLbioPic = HTMLbioPic.replace("%data%", bio.biopic);
formattedWelcomeMsg = HTMLwelcomeMsg.replace("%data%", bio.welcomeMessage);
$("#header").prepend(formattedHTMLheaderRole);
$("#header").prepend(formattedHTMLheaderName);
$("#topContacts").append(formattedHTMLmobile);
$("#topContacts").append(formattedHTMLemail);
$("#topContacts").append(formattedHTMLtwitter);
$("#topContacts").append(formattedHTMLgithub);
$("#topContacts").append(formatedHTMLlocation);
$("#header").append(formattedHTMLbioPic);
$("#header").append(formattedWelcomeMsg);
//This part diplay the skills
if(bio.skills.length > 0){
$("#header").append(HTMLskillsStart);
var element = $("#skills"), formattedHTMLskills;
for(var i=0, len=bio.skills.length; i<len; i++){
formattedHTMLskills = HTMLskills.replace("%data%", bio.skills[i]);
element.append(formattedHTMLskills);
}
}//Skill display ends
//Display footer contacts
$("#footerContacts").append(formattedHTMLmobile);
$("#footerContacts").append(formattedHTMLemail);
$("#footerContacts").append(formattedHTMLtwitter);
$("#footerContacts").append(formattedHTMLgithub);
$("#footerContacts").append(formatedHTMLlocation);
} //display ends
}; //bio ends
bio.display();
work.display();
projects.display();
education.display();
$("#mapDiv").append(googleMap);
<file_sep>#Interactive Resume
A web based resume that uses jQuery to animate and add interactivity as well as a Google Maps API to add locations.
##Description
The goal behind this resume is to use jQuery to add animations and interactivity to the page. Additionally Google Maps API is used to show the locations of relevant places in the map, such as the location of the universities where the person studied or the location of past and current jobs.
##How to use
Download the files and open the index.hmtl file. Use Bower in case you want to add or modify packages.
To edit the resume with your own information open the file:
```
resumeBuilder.js
```
There you can edit the work, projects, education and bio variables, which are JavaScript objects that hold all relevant information.
###Requisites
Open with Chrome, Safari or Firefox. IE is not supported.
###How to run
Just double click on the index.html file
##Demo
You can see a demo here:
http://uliseschino.com/projects/interactive-resume
|
1509bc34446127f29d7826b99b72184d56482fae
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
uliseschino/frontend-nanodegree-interactive-resume
|
d7a6a984d84948ff0a6175eb787f57a683335d7e
|
8484a6b5208a420c095fe849fb084c1b6aa671a7
|
refs/heads/master
|
<repo_name>PestrakMary/java-advanced<file_sep>/keyEvent/src/by/bsu/MyFrame.java
package by.bsu;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class MyFrame extends JFrame {
MyFrame(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(650, 560);
JPanel mainPanel = new JPanel(new BorderLayout());
JLabel labelInstruction = new JLabel("Please type key combination: Alt + a ");
MyButton c = new MyButton();
c.addKeyCombinationListener(new KeyCombinationAdapter() {
@Override
public void keyCombinationTyped(KeyCombinationEvent e) {
c.setText("Combination is typed!");
c.setBackground(new Color(255, 200, 150));
}
});
mainPanel.add(labelInstruction, BorderLayout.NORTH);
mainPanel.add(c, BorderLayout.CENTER);
this.add(mainPanel);
this.setVisible(true);
}
}
<file_sep>/keywordCorrection/src/bsu/labs/MainFrame.java
package bsu.labs;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class MainFrame extends JFrame {
private File dictionary = new File("D:\\Универ\\3 курс\\5 семестр\\Java\\keywordCorrection\\src\\res\\dictionary.txt");
private File inputText;
private HashMap<String, String> dictionaryMap;
{
dictionaryMap = new HashMap<>();
dictionaryMap = fileToMap(dictionary);
}
private boolean isSaved = false;
private boolean isFileOpen = false;
private JFileChooser fileChooser = new JFileChooser("D:\\Универ\\3 курс\\5 семестр\\Java\\keywordCorrection\\src\\res");
private JTextArea textArea = new JTextArea();
MainFrame(){
super();
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent ev) {
if(isFileOpen) {
if (isSaved) {
dispose();
} else {
int answer = JOptionPane.showConfirmDialog(MainFrame.this, "Do you want to save changes?");
if (answer == JOptionPane.OK_OPTION) {
writeToFile(textArea.getText(), inputText);
dispose();
} else if (answer == JOptionPane.NO_OPTION) {
dispose();
}
}
} else {
int answer = JOptionPane.showConfirmDialog(MainFrame.this, "Do you want to save changes?");
if (answer == JOptionPane.OK_OPTION) {
if(fileChooser.showSaveDialog(MainFrame.this) == JFileChooser.APPROVE_OPTION) {
writeToFile(textArea.getText(), fileChooser.getSelectedFile());
dispose();
}
} else if (answer == JOptionPane.NO_OPTION) {
dispose();
}
}
}
});
this.setSize(600, 450);
this.setLayout(new BorderLayout());
JButton fixButton = new JButton("Check");
JButton saveButton = new JButton("Save Changes");
JPanel buttonBar = new JPanel(new BorderLayout());
buttonBar.add( fixButton, BorderLayout.WEST);
buttonBar.add(saveButton, BorderLayout.EAST);
JMenuBar toolsBar = new JMenuBar();
JMenu menuFile = new JMenu("File");
JMenuItem openFile = new JMenuItem("Open file");
menuFile.add(openFile);
toolsBar.add(menuFile);
this.add(toolsBar, BorderLayout.NORTH);
this.add(buttonBar, BorderLayout.SOUTH);
this.add(textArea, BorderLayout.CENTER);
openFile.addActionListener(e -> {
if(!textArea.getText().equals("")) {
int answer = JOptionPane.showConfirmDialog(MainFrame.this, "Do you want to save changes?");
if (answer == JOptionPane.OK_OPTION) {
if (isFileOpen) {
writeToFile(textArea.getText(), inputText);
} else {
if (fileChooser.showSaveDialog(MainFrame.this) == JFileChooser.APPROVE_OPTION) {
writeToFile(textArea.getText(), fileChooser.getSelectedFile());
dispose();
}
}
}
}
if(fileChooser.showOpenDialog(MainFrame.this) == JFileChooser.APPROVE_OPTION){
isSaved = false;
inputText = fileChooser.getSelectedFile();
readFromFile(inputText, textArea);
isFileOpen = true;
}
});
saveButton.addActionListener(this::actionPerformed
);
fixButton.addActionListener(e -> {
fixKeywords(textArea);
isSaved = false;
});
this.setVisible(true);
}
private void readFromFile(File file, JTextArea textArea){
try{
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String s;
while((s = bufferedReader.readLine())!= null){
textArea.append(s);
textArea.append(String.valueOf('\n'));
}
bufferedReader.close();
} catch (FileNotFoundException ex){
JOptionPane.showMessageDialog(MainFrame.this, "File doesn't exist!");
} catch (IOException ex){
JOptionPane.showMessageDialog(MainFrame.this, "Can not read the file");
}
}
private HashMap<String, String> fileToMap(File file){
HashMap<String, String> map = new HashMap<>();
try{
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String s;
while((s = bufferedReader.readLine())!=null){
for(String key: s.split(" ")) {
String stringBuffer = "(?i)"+
key +
"(?=[^\"]*(?:\"[^\"]*\"[^\"]*)*\\z)";
map.put(key, stringBuffer);
}
}
} catch (FileNotFoundException ex){
JOptionPane.showMessageDialog(MainFrame.this, "File doesn't exist!");
return null;
} catch (IOException ex){
JOptionPane.showMessageDialog(MainFrame.this, "Can not read the file");
return null;
}
return map;
}
private void fixKeywords(JTextArea textArea){
for (String key : dictionaryMap.keySet()) {
Pattern p = Pattern.compile(dictionaryMap.get(key));
Matcher m = p.matcher(textArea.getText());
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, key);
}
m.appendTail(sb);
textArea.setText(sb.toString());
}
JOptionPane.showMessageDialog(MainFrame.this, "Fixing completed");
}
private void writeToFile(String text, File file){
try{
PrintWriter printWriter = new PrintWriter(new BufferedWriter(new FileWriter(file)));
printWriter.print(text);
printWriter.close();
} catch (IOException ex){
JOptionPane.showMessageDialog(MainFrame.this, "Can not write changes!");
}
}
private void actionPerformed(ActionEvent e) {
if (isFileOpen) {
writeToFile(textArea.getText(), inputText);
isSaved = true;
} else {
if (fileChooser.showSaveDialog(MainFrame.this) == JFileChooser.APPROVE_OPTION) {
writeToFile(textArea.getText(), fileChooser.getSelectedFile());
}
}
}
}
<file_sep>/wedding/src/bsu/labs/Person.java
package bsu.labs;
import java.io.Serializable;
public class Person implements Serializable {
private String name;
enum Gender{
female,
male
};
private Gender gender;
enum Sign{
Aries, Taurus,
Gemini, Cancer,
Lion, Virgo,
Libra, Scorpio,
Sagittarius, Capricorn,
Aquarius, Fish
}
private Sign sign;
private int age;
private Sign partnerSign;
public Person(String name, Gender gender, Sign sign, int age, Sign partnerSign) {
this.name = name;
this.gender = gender;
this.sign = sign;
this.age = age;
this.partnerSign = partnerSign;
}
public String getName() {
return name;
}
public Sign getPartnerSign() {
return partnerSign;
}
public void setPartnerSign(Sign partnerSign) {
this.partnerSign = partnerSign;
}
public void setName(String name) {
this.name = name;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public Sign getSign() {
return sign;
}
public void setSign(Sign sign) {
this.sign = sign;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return //"***********************\n"+
"name = " + name + ',' +
" gender = " + gender + ','+
" sign = " + sign + ',' +
" age = " + age + ',' +
" partner sign = " + partnerSign;
// +"\n***********************\n";
}
}
<file_sep>/keyEvent/src/by/bsu/MyButton.java
package by.bsu;
import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.LinkedList;
public class MyButton extends JButton {
private LinkedList<KeyCombinationListener> ls = new LinkedList<KeyCombinationListener>();
MyButton()
{
this.setSize(400, 400);
this.setBackground(new Color(255, 255, 255));
this.setFocusable(true);
}
public void addKeyCombinationListener(KeyCombinationAdapter adapter)
{
this.addKeyListener(adapter);
}
public void removeKeyCombinationListener(KeyCombinationAdapter adapter)
{
this.removeKeyListener(adapter);
}
}
<file_sep>/wedding/src/bsu/labs/ContextMenu.java
package bsu.labs;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class ContextMenu extends JPopupMenu {
JMenuItem editPerson = new JMenuItem("Edit person");
JMenuItem deletePerson = new JMenuItem("Delete person");
JMenuItem pairSelection = new JMenuItem("Pair selection");
JFrame parent;
ContextMenu(Person person, JFrame parent){
this.parent = parent;
this.add(editPerson);
this.add(deletePerson);
this.add(pairSelection);
editPerson.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new InputDialog(ContextMenu.this.parent, "Edit", person);
}
});
deletePerson.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
((Main)parent).personsCollection.getCollection().remove(person);
((Main)parent).fillOutputList();
}
});
pairSelection.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (!((Main)parent).personsCollection.getCollection().isEmpty()) {
Person person1 = ((Main)parent).fileOutputList.getSelectedValue();
if (person1 != null) {
ArrayList<Person> result = (ArrayList<Person>) ((Main)parent).personsCollection.
getCollection().
stream().
filter((Person person2)-> person1.getGender() != person2.getGender()).
filter((Person person2) -> Math.abs(person2.getAge() - person1.getAge()) <= Main.IDEAL_AGE_DELTA).
filter((Person person2)-> person1.getPartnerSign() == person2.getSign()
&& person1.getSign() == person2.getPartnerSign()).collect(Collectors.toList());
StringBuffer buffer = new StringBuffer();
if(!result.isEmpty()) {
result.stream().forEachOrdered((Person person) -> {
buffer.append(person);
buffer.append('\n');
});
} else {
buffer.append("No available pairs now");
}
JOptionPane.showMessageDialog(parent, buffer.toString(), "Ideal pairs", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(parent, "Please choose person for selection pairs!");
}
}
}
});
this.setVisible(true);
}
}
<file_sep>/reflection/src/text_en_US.properties
classNameLabel = Enter name of class:
appName = Reflection
getMethodsButton = Get methods
createObject = Create object
classNotFoundEx = Can not find class for this name!
invokeMethodButton = Invoke method
resultLabel = Result:
exMessage = Wrong args types!
langButton = Language
languageEn = English
languageBe = Belarussian
toolsMenu = Tools
MessageTitle = Message<file_sep>/keyEvent/src/by/bsu/KeyCombinationListener.java
package by.bsu;
import java.awt.event.KeyListener;
public interface KeyCombinationListener extends KeyListener {
void keyCombinationTyped(KeyCombinationEvent e);
}
<file_sep>/reflection/src/bsu/labs/ContextMenu.java
package bsu.labs;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.stream.Collectors;
public class ContextMenu extends JPopupMenu {
JFrame parent;
ContextMenu(Method method, JFrame parent){
this.parent = parent;
JMenuItem invoke = new JMenuItem(((MyFrame)this.parent).rb.getString("invokeMethodButton"));
this.add(invoke);
invoke.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new InputDialog((MyFrame) ContextMenu.this.parent, ((MyFrame)ContextMenu.this.parent).rb.getString("invokeMethodButton"), method);
}
});
this.setVisible(true);
}
ContextMenu(Constructor constructor, JFrame parent){
this.parent = parent;
JMenuItem create = new JMenuItem(((MyFrame)this.parent).rb.getString("createObject"));
this.add(create);
create.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new InputDialog((MyFrame) ContextMenu.this.parent, ((MyFrame)ContextMenu.this.parent).rb.getString("createObject"), constructor);
}
});
this.setVisible(true);
}
}
<file_sep>/wedding/src/bsu/labs/Main.java
package bsu.labs;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
public class Main extends JFrame {
static final int IDEAL_AGE_DELTA = 2;
JFileChooser fileChooser = new JFileChooser("D:\\Универ\\3 курс\\5 семестр\\Java\\wedding\\src\\res");
File dataFile;
static Singleton<Person> personsCollection = Singleton.getInstance();
JList<Person> fileOutputList = new JList<>(new DefaultListModel<>());
public static void main(String[] args) {
new Main("Wedding");
}
Main(String title) {
super(title);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(650, 560);
fileOutputList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scrollPane = new JScrollPane(fileOutputList);
JMenuBar toolsBar = new JMenuBar();
JMenu menuFile = new JMenu("File");
JMenu menuEdit = new JMenu("Edit");
JMenuItem openFile = new JMenuItem("Open file");
JMenuItem saveFile = new JMenuItem("Save file");
JMenuItem addPerson = new JMenuItem("Add person");
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(scrollPane, BorderLayout.CENTER);
menuFile.add(openFile);
menuFile.add(saveFile);
menuEdit.add(addPerson);
toolsBar.add(menuFile);
toolsBar.add(menuEdit);
this.add(toolsBar, BorderLayout.NORTH);
this.add(mainPanel, BorderLayout.CENTER);
openFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (fileChooser.showOpenDialog(Main.this) == JFileChooser.APPROVE_OPTION) {
dataFile = fileChooser.getSelectedFile();
readFromFile(dataFile);
fillOutputList();
}
}
});
saveFile.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (dataFile != null) {
writeToFile(dataFile);
} else if (fileChooser.showSaveDialog(Main.this) == JFileChooser.APPROVE_OPTION) {
writeToFile(fileChooser.getSelectedFile());
}
}
});
addPerson.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new InputDialog(Main.this, "Add person");
fillOutputList();
}
});
fileOutputList.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
//invoke popup menu with right button
if (e.getButton() == MouseEvent.BUTTON3) {
new ContextMenu(((JList<Person>) e.getSource()).getSelectedValue(), Main.this).
show(Main.this, e.getXOnScreen(), e.getYOnScreen());
}
}
});
this.setVisible(true);
}
void writeToFile(File dataFile) {
try (ObjectOutputStream writer = new ObjectOutputStream(new FileOutputStream(dataFile))) {
personsCollection.getCollection().stream().
forEach((Person person) -> {
try {
writer.writeObject(person);
} catch (IOException e) {
JOptionPane.showMessageDialog(Main.this, "Write exception!");
}
});
} catch (IOException e) {
JOptionPane.showMessageDialog(Main.this, "Write exception!");
}
}
void readFromFile(File dataFile) {
personsCollection.getCollection().clear();
try (ObjectInputStream reader = new ObjectInputStream(new FileInputStream(dataFile))) {
Person temp;
while ((temp = (Person) reader.readObject()) != null) {
personsCollection.getCollection().add(temp);
}
} catch (EOFException ex) {
// JOptionPane.showMessageDialog(Main.this, "Read exception!");
} catch (ClassNotFoundException | IOException ex) {
JOptionPane.showMessageDialog(Main.this, "Wrong data in file");
}
}
void fillOutputList() {
DefaultListModel<Person> listModel = (DefaultListModel<Person>) fileOutputList.getModel();
listModel.clear();
personsCollection.getCollection().
stream().
forEachOrdered((Person person) ->listModel.addElement(person));
}
}
<file_sep>/README.md
# java-advanced
io-streams, stream api & lambdas, reflection, serialization, i18n,
threads, simple web, regex
|
4a423da05671c8f8dd6e061de56b824c81f3d002
|
[
"Markdown",
"Java",
"INI"
] | 10
|
Java
|
PestrakMary/java-advanced
|
b3eb1500144a0d2fde496b296256d9c727286698
|
9323dbc01996afc85a4c3ea40d6a1e9d704c2f9e
|
refs/heads/master
|
<file_sep># BurstLibNoise Example

Example Unity project for [BurstLibNoise](https://github.com/sunny8751/BurstLibNoise) which adds Burst support for LibNoise.
### Features
- ~3x speed boost on my computer using Burst parallel jobs
- Supports all LibNoise modules except for Cache, Curve, and Terrace
- Generate noise as texture for procedural generation heightmap
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using LibNoise.Generator;
using LibNoise.Operator;
using LibNoise;
public class LibNoiseTest : MonoBehaviour
{
[SerializeField] int Width = 0;
[SerializeField] int Height = 0;
// Start is called before the first frame update
void Start()
{
// STEP 1
// Gradient is set directly on the object
var mountainTerrain = new RidgedMultifractal();
// // STEP 2
var baseFlatTerrain = new Billow();
baseFlatTerrain.Frequency = 2.0;
// STEP 3
var flatTerrain = new ScaleBias(0.125, -0.75, baseFlatTerrain);
// STEP 4
var terrainType = new Perlin();
terrainType.Frequency = 0.5;
terrainType.Persistence = 0.25;
var finalTerrain = new Select(flatTerrain, mountainTerrain, terrainType);
finalTerrain.SetBounds(0, 1000);
finalTerrain.FallOff = 0.125;
float start = Time.realtimeSinceStartup;
RenderAndSetImage(finalTerrain);
Debug.Log("LibNoise runtime: " + (Time.realtimeSinceStartup - start));
}
void RenderAndSetImage(ModuleBase generator)
{
var heightMapBuilder = new Noise2D(Width, Height, generator);
heightMapBuilder.GeneratePlanar(Noise2D.Left, Noise2D.Right, Noise2D.Top, Noise2D.Bottom);
// heightMapBuilder.GenerateSpherical(90, -90, -180, 180);
// heightMapBuilder.GenerateCylindrical(-180, 180, -1, 1);
var image = heightMapBuilder.GetTexture();
GetComponent<Renderer>().material.mainTexture = image;
}
}
|
3c3c7f00c18020a7c031fff4a50bc4a8bec8e762
|
[
"Markdown",
"C#"
] | 2
|
Markdown
|
sunny8751/BurstLibNoiseExample
|
a2f29e4c787f1cc4b4d09611501c7ecb3d77116e
|
ed8a57ff424376de0f9137ec45f92b2ba81a2eae
|
refs/heads/master
|
<repo_name>fddsocool/AndroidWidgets<file_sep>/app/src/main/java/com/frx/jitepaikejava/NoIfElseDemo/PayCode.java
package com.frx.jitepaikejava.NoIfElseDemo;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 判断是那个支付方式
* 实际开发中可以根据需求传入特定的变量来判断
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface PayCode {
String value();
String name();
}
<file_sep>/app/src/main/java/com/frx/jitepaikejava/NoIfElseDemo/JingDongPay.java
package com.frx.jitepaikejava.NoIfElseDemo;
import android.util.Log;
@PayCode(value = "jingdong", name = "京东支付")
public class JingDongPay implements IPay {
@Override
public void pay() {
Log.d("fmsg===>PayCode注解", "===发起京东支付===");
}
}
<file_sep>/app/src/main/java/com/frx/jitepaikejava/MainActivity.java
package com.frx.jitepaikejava;
import android.content.Intent;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.frx.jitepaikejava.SplitEditDemo.SplitEditDemoActivity;
import com.frx.jitepaikejava.NoIfElseDemo.NoIfActivity;
import com.frx.jitepaikejava.StatusLayoutDemo.StatusLayoutActivity;
import java.util.ArrayList;
import java.util.List;
import static android.view.View.OVER_SCROLL_NEVER;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<DemoBean> arrayList = new ArrayList<>();
addDemo(arrayList);
RecyclerView recyclerView = findViewById(R.id.rlWidgets);
List<IDelegateAdapter<DemoBean>> delegateAdapters = new ArrayList<>();
UsageDelegate usageDelegate = new UsageDelegate(this);
WidgetDelegate widgetDelegate = new WidgetDelegate(this);
DivDelegate divDelegate = new DivDelegate(this);
delegateAdapters.add(usageDelegate);
delegateAdapters.add(widgetDelegate);
delegateAdapters.add(divDelegate);
DemoDelegateAdapter demoDelegateAdapter = new DemoDelegateAdapter(this, arrayList, delegateAdapters);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(demoDelegateAdapter);
recyclerView.setOverScrollMode(OVER_SCROLL_NEVER);
widgetDelegate.setOnItemClick((position, data) -> {
Intent intent = new Intent(this, data.getIntentClass());
startActivity(intent);
});
usageDelegate.setOnItemClick((position, data) -> {
Intent intent = new Intent(this, data.getIntentClass());
startActivity(intent);
});
}
private void addDemo(ArrayList<DemoBean> arrayList) {
DemoBean divWidget = new DemoBean();
divWidget.setType(0);
divWidget.setDemoName("控件");
arrayList.add(divWidget);
addWidget(arrayList);
DemoBean divUsage = new DemoBean();
divUsage.setType(0);
divUsage.setDemoName("技巧");
arrayList.add(divUsage);
addUsage(arrayList);
}
private void addWidget(ArrayList<DemoBean> arrayList) {
//分离式输入框
DemoBean splitEditDemo = new DemoBean();
splitEditDemo.setType(1);
splitEditDemo.setDemoName("分离式输入框");
splitEditDemo.setDescription("用于验证码等场景");
splitEditDemo.setIntentClass(SplitEditDemoActivity.class);
arrayList.add(splitEditDemo);
//状态管理布局
DemoBean statusLayoutDemo = new DemoBean();
statusLayoutDemo.setType(1);
statusLayoutDemo.setDemoName("状态管理布局");
statusLayoutDemo.setDescription("用于页面的各种状态之间的切换");
statusLayoutDemo.setIntentClass(StatusLayoutActivity.class);
arrayList.add(statusLayoutDemo);
}
private void addUsage(ArrayList<DemoBean> arrayList) {
//no-if的方法
DemoBean noIfDemo = new DemoBean();
noIfDemo.setType(2);
noIfDemo.setDemoName("no-if的方法");
noIfDemo.setDescription("用炫酷的方式改写if-else");
noIfDemo.setIntentClass(NoIfActivity.class);
arrayList.add(noIfDemo);
}
}<file_sep>/app/src/main/java/com/frx/jitepaikejava/WidgetDelegate.java
package com.frx.jitepaikejava;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
public class WidgetDelegate implements IDelegateAdapter<DemoBean> {
private Context mContext;
private onItemClick<DemoBean> mOnItemClick;
public WidgetDelegate(Context context) {
mContext = context;
}
public void setOnItemClick(onItemClick<DemoBean> onItemClick) {
mOnItemClick = onItemClick;
}
@Override
public boolean isForViewType(DemoBean data) {
return data.getType() == 1;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_widget, viewGroup, false);
return new WidgetDelegateViewHolder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, DemoBean data) {
WidgetDelegateViewHolder vh = (WidgetDelegateViewHolder) holder;
vh.mTvWidgetName.setText(String.valueOf(data.getDemoName()));
vh.mTvWidgetDes.setText(String.valueOf(data.getDescription()));
vh.mClRoot.setOnClickListener(v -> {
if (mOnItemClick != null) {
mOnItemClick.onClick(position, data);
}
});
}
static class WidgetDelegateViewHolder extends RecyclerView.ViewHolder {
ConstraintLayout mClRoot;
TextView mTvWidgetName;
TextView mTvWidgetDes;
public WidgetDelegateViewHolder(@NonNull View itemView) {
super(itemView);
mClRoot = itemView.findViewById(R.id.clRoot);
mTvWidgetName = itemView.findViewById(R.id.tvWidgetName);
mTvWidgetDes = itemView.findViewById(R.id.tvWidgetDes);
}
}
}
<file_sep>/app/src/main/java/com/frx/jitepaikejava/DemoBean.java
package com.frx.jitepaikejava;
public class DemoBean {
//0=>标志
//1=>控件
//2=>用法
private int type;
private String demoName;
private String description;
private Class mIntentClass;
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getDemoName() {
return demoName;
}
public void setDemoName(String demoName) {
this.demoName = demoName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Class getIntentClass() {
return mIntentClass;
}
public void setIntentClass(Class intentClass) {
mIntentClass = intentClass;
}
}
<file_sep>/app/src/main/java/com/frx/jitepaikejava/NoIfElseDemo/payFactory/IFactoryPay.java
package com.frx.jitepaikejava.NoIfElseDemo.payFactory;
/**
* 支付接口
*/
public interface IFactoryPay {
void init(PayStrategyFactory factory);
void pay();
}
<file_sep>/app/src/main/java/com/frx/jitepaikejava/UsageDelegate.java
package com.frx.jitepaikejava;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.RecyclerView;
public class UsageDelegate implements IDelegateAdapter<DemoBean> {
private Context mContext;
private onItemClick<DemoBean> mOnItemClick;
public UsageDelegate(Context context) {
mContext = context;
}
public void setOnItemClick(onItemClick<DemoBean> onItemClick) {
mOnItemClick = onItemClick;
}
@Override
public boolean isForViewType(DemoBean data) {
return data.getType() == 2;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.item_usage, viewGroup, false);
return new UsageDelegateViewHolder(view);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position, DemoBean data) {
UsageDelegateViewHolder vh = (UsageDelegateViewHolder) holder;
vh.mTvWidgetName.setText(String.valueOf(data.getDemoName()));
vh.mTvWidgetDes.setText(String.valueOf(data.getDescription()));
vh.mClRoot.setOnClickListener(v -> {
if (mOnItemClick != null) {
mOnItemClick.onClick(position, data);
}
});
}
static class UsageDelegateViewHolder extends RecyclerView.ViewHolder {
ConstraintLayout mClRoot;
TextView mTvWidgetName;
TextView mTvWidgetDes;
public UsageDelegateViewHolder(@NonNull View itemView) {
super(itemView);
mClRoot = itemView.findViewById(R.id.clRoot);
mTvWidgetName = itemView.findViewById(R.id.tvWidgetName);
mTvWidgetDes = itemView.findViewById(R.id.tvWidgetDes);
}
}
}
<file_sep>/app/src/main/java/com/frx/jitepaikejava/NoIfElseDemo/ResponsibilityChain/JingdongPayHandler.java
package com.frx.jitepaikejava.NoIfElseDemo.ResponsibilityChain;
import android.util.Log;
public class JingdongPayHandler extends PayHandler {
@Override
public void pay(String pay) {
if ("jingdong".equals(pay)) {
Log.d("fmsg===>责任链模式", "===发起京东支付===");
} else if (getTryNextPay() != null) {
getTryNextPay().pay(pay);
} else {
Log.d("fmsg===>责任链模式", "找不到对应的支付方式");
}
}
}
<file_sep>/app/src/main/java/com/frx/jitepaikejava/StatusLayoutDemo/statuslayout/StatusConfigBean.java
package com.frx.jitepaikejava.StatusLayoutDemo.statuslayout;
import android.view.View;
import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
public class StatusConfigBean {
/**
* 状态布局的status标记,比如空页面、错误页面等等
*/
private String status;
/**
* 与status标记对应的布局id
*/
@LayoutRes
private int layout;
/**
* 与layout类似的作用
*/
private View view;
/**
* 传入点击事件的id
*/
@IdRes
private int clickRes;
private boolean autoClick = true;
private StatusConfigBean() {
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public int getLayout() {
return layout;
}
public void setLayout(int layout) {
this.layout = layout;
}
public View getView() {
return view;
}
public void setView(View view) {
this.view = view;
}
public int getClickRes() {
return clickRes;
}
public void setClickRes(int clickRes) {
this.clickRes = clickRes;
}
public boolean isAutoClick() {
return autoClick;
}
public void setAutoClick(boolean autoClick) {
this.autoClick = autoClick;
}
// public static class Builder {
// private String status;
//
// @LayoutRes
// private int layout;
//
// private View view;
//
// @IdRes
// private int clickRes;
//
// private boolean autoClick = true;
//
// public Builder setStatus(String status) {
// this.status = status;
// return this;
// }
//
// public Builder setLayout(int layout) {
// this.layout = layout;
// return this;
// }
//
// public Builder setView(View view) {
// this.view = view;
// return this;
// }
//
// public Builder setClickRes(int clickRes) {
// this.clickRes = clickRes;
// return this;
// }
//
// public Builder setAutoClick(boolean autoClick) {
// this.autoClick = autoClick;
// return this;
// }
//
// public StatusConfigBean build() {
// return new StatusConfigBean(this);
// }
// }
public static class Builder {
StatusConfigBean mStatusConfigBean = new StatusConfigBean();
public Builder setStatus(String status) {
mStatusConfigBean.status = status;
return this;
}
public Builder setLayout(int layout) {
mStatusConfigBean.layout = layout;
return this;
}
public Builder setView(View view) {
mStatusConfigBean.view = view;
return this;
}
public Builder setClickRes(int clickRes) {
mStatusConfigBean.clickRes = clickRes;
return this;
}
public Builder setAutoClick(boolean autoClick) {
mStatusConfigBean.autoClick = autoClick;
return this;
}
public StatusConfigBean build() {
return mStatusConfigBean;
}
}
}
<file_sep>/README.md
# Android 收纳 #
----------
## 控件
### 分离式输入框 ###
- SplitEditDemo
- [https://github.com/jenly1314/SplitEditText](https://github.com/jenly1314/SplitEditText "原地址")
----------
### 页面状态管理 ###
- StatusLayoutDemo
- [https://github.com/Colaman0/StatusLayout](https://github.com/Colaman0/StatusLayout "原地址")
----------
## 技巧
### 优化代码中的if-else ###
- NoIfElseDemo
----------<file_sep>/app/src/main/java/com/frx/jitepaikejava/NoIfElseDemo/README.md
# 去除烦人的if-else
[https://mp.weixin.qq.com/s/Y6mOGs8_rVNxcnqVzCXdXA](https://mp.weixin.qq.com/s/Y6mOGs8_rVNxcnqVzCXdXA "原地址")
<file_sep>/app/src/main/java/com/frx/jitepaikejava/NoIfElseDemo/IPay.java
package com.frx.jitepaikejava.NoIfElseDemo;
/**
* 支付接口
*/
public interface IPay {
void pay();
}
<file_sep>/app/src/main/java/com/frx/jitepaikejava/StatusLayoutDemo/README.md
# StatusLayout : 一个超高自定义度又简单的页面状态管理库
[https://github.com/Colaman0/StatusLayout](https://github.com/Colaman0/StatusLayout "原地址")
#### 业务场景需求:
##### 在日常开发App的过程中,我们少不了对`Activity`/`Fragment` 等做一些不同状态不同UI的状态管理逻辑,比如`空页面` `错误重试页面` 等等,网上也有很多作者写了开源库来处理这些问题
----
#### `StatusLayout`有以下几个优点
* ##### 自由定制需要的状态以及对应布局,只需要一行代码
* ##### 可以定制动画效果
* ##### 可以用在旧项目上,不需要修改原有xml文件
* ##### 可设置全局属性避免重复劳动
#### 效果图:
#### 具体使用步骤如下:
### 1.第一步先把`StatusLayout`作为根布局,这里有以下两种写法
* ##### 把`StatusLayout`作为根布局在activity/fragment/view 中使用
> 在xml内直接把`StatusLayout`作为根布局,注意`StatusLayout`内部子view数量不能超过1个,
所以如果UI上需求需要排列多个View的时候,需要多套一层布局,比如:
```
<StatusLayout>
<LinearLayout>
<View/>
<View/>
<View/>
</LinearLayout>
</StatusLayout>
````
* ##### 通过 `StatusLayout.init()`方法传入Context以及你要显示到的layout资源文件,这个方法会返回一个StatusLayout对象,所以大家可以在封装BaseActivity的时候这样写:
```
// 后续可以通过mStatusLayout添加不同状态对应的UI
StatusLayout mStatusLayout = StatusLayout.init(this, R.layout.activity_main);
setContentView(mStatusLayout);
```
### 2. 添加不同状态对应的UI以及响应点击事件
* ##### `status` : 作为一个状态布局的status标记,比如`空页面` `错误页面` 等等你想要添加进去的页面,设置一下自己想要添加的`status`
* ##### `layoutRes` : 对应上面的`status`, 一个`status`对应一个view,一个布局,比如上面`status`传入了一个empty,那我们这里对应可以添加一个空页面的layout资源文件id
* ##### `view` : 跟`layoutRes`相似,考虑到有时候业务需求,某个状态下的页面可能按钮或者一些需要写的逻辑比较多比较复杂, 这个时候可以让开发者自己写一个view传进来,对应的一些逻辑判断则让`view`内部去处理 ,`StatusLayout`只负责切换
* ##### `clickRes` :每一个布局,可以传递一个id进来,比如`错误重试页面` 可以传一个button的id进来,这样在button被点击的时候,可以通过回调来接收到点击事件
### 3. 切换布局
#### 通过`switchLayout()两种方法来切换布局
* ##### `switchLayout`方法是用于切换你add进去的布局,只要传入你前面add布局的时候传入的status就可以了
### 5. 设置显示/隐藏的动画
##### 通过`setAnimation()` 来设置页面显示/隐藏的的动画, 也可以通过`setGlobalAnim()`来设置一个全局的动画效果,`setAnimation()`的优先级比`setGlobalAnim()`更高
### 6.设置全局属性
##### 考虑到APP里常见的`空页面` `loading` 之类的页面都是比较统一的,这个时候可以通过`StatusLayout.setGlobalData()`方法来设置全局的属性,这个时候可以设置全局属性来避免重复添加的代码,后续可以通过`add()`方法来覆盖全局属性。
<file_sep>/app/src/main/java/com/frx/jitepaikejava/StatusLayoutDemo/StatusLayoutActivity.java
package com.frx.jitepaikejava.StatusLayoutDemo;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.frx.jitepaikejava.R;
import com.frx.jitepaikejava.StatusLayoutDemo.statuslayout.StatusConfig;
import com.frx.jitepaikejava.StatusLayoutDemo.statuslayout.StatusConfigBean;
import com.frx.jitepaikejava.StatusLayoutDemo.statuslayout.StatusLayout;
import com.frx.jitepaikejava.utils.RxJavaUtil;
public class StatusLayoutActivity extends AppCompatActivity {
private Button mBtnNormal;
private Button mBtnEmpty;
private Button mBtnLoading;
private Button mBtnError;
private StatusLayout mStatusLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_status_layout);
mBtnNormal = findViewById(R.id.btn_normal);
mBtnEmpty = findViewById(R.id.btn_empty);
mBtnLoading = findViewById(R.id.btn_loading);
mBtnError = findViewById(R.id.btn_error);
mStatusLayout = findViewById(R.id.status_layout);
initView();
}
private void initView() {
View errorOtherView = LayoutInflater.from(this).inflate(R.layout.include_error_other, mStatusLayout, false);
StatusConfigBean errorOtherViewConfig = new StatusConfigBean.Builder()
.setStatus(StatusConfig.STATUS_ERROR)
.setView(errorOtherView)
.setAutoClick(true)
.build();
Button tryBtn = errorOtherView.findViewById(R.id.btn_retry);
StatusConfigBean normalViewConfig = new StatusConfigBean.Builder()
.setStatus(StatusConfig.STATUS_NORMAL)
.setLayout(R.layout.include_normal)
.setAutoClick(true)
.build();
mStatusLayout.initStatus(true, true, 0, 0)
.addLayout(normalViewConfig)
.addLayout(errorOtherViewConfig)
.setOnLayoutClickListener((view, status) -> {
Toast.makeText(this, "OnLayoutClickListener status:" + status, Toast.LENGTH_SHORT).show();
});
mBtnNormal.setOnClickListener(v -> {
mStatusLayout.switchLayout(StatusConfig.STATUS_NORMAL);
});
mBtnEmpty.setOnClickListener(v -> {
mStatusLayout.switchLayout(StatusConfig.STATUS_EMPTY);
});
mBtnLoading.setOnClickListener(v -> {
mStatusLayout.switchLayout(StatusConfig.STATUS_LOADING);
RxJavaUtil.runTimer(2000, new RxJavaUtil.OnRxRunTimerListener() {
@Override
public void onExecute(Long l) {
Log.d("StatusLayoutActivity", "loading:" + l);
}
@Override
public void onFinish() {
mStatusLayout.switchLayout(StatusConfig.STATUS_NORMAL);
}
@Override
public void onError(Throwable e) {
mStatusLayout.switchLayout(StatusConfig.STATUS_ERROR);
}
});
});
mBtnError.setOnClickListener(v -> {
mStatusLayout.switchLayout(StatusConfig.STATUS_ERROR);
});
tryBtn.setOnClickListener(v -> {
mStatusLayout.switchLayout(StatusConfig.STATUS_LOADING);
RxJavaUtil.runTimer(2000, new RxJavaUtil.OnRxRunTimerListener() {
@Override
public void onExecute(Long l) {
}
@Override
public void onFinish() {
mStatusLayout.switchLayout(StatusConfig.STATUS_NORMAL);
}
@Override
public void onError(Throwable e) {
mStatusLayout.switchLayout(StatusConfig.STATUS_ERROR);
}
});
});
mStatusLayout.switchLayout(StatusConfig.STATUS_LOADING);
RxJavaUtil.runTimer(2000, new RxJavaUtil.OnRxRunTimerListener() {
@Override
public void onExecute(Long l) {
}
@Override
public void onFinish() {
mStatusLayout.switchLayout(StatusConfig.STATUS_NORMAL);
}
@Override
public void onError(Throwable e) {
mStatusLayout.switchLayout(StatusConfig.STATUS_ERROR);
}
});
}
@Override
protected void onDestroy() {
mStatusLayout.onDestroy();
super.onDestroy();
}
}<file_sep>/app/src/main/java/com/frx/jitepaikejava/StatusLayoutDemo/statuslayout/StatusConfig.java
package com.frx.jitepaikejava.StatusLayoutDemo.statuslayout;
import com.frx.jitepaikejava.R;
import java.util.HashMap;
public class StatusConfig {
// 全局状态布局值
public static final String STATUS_NORMAL = "normal_content";
public static final String STATUS_LOADING = "loading_content";
public static final String STATUS_ERROR = "error_content";
public static final String STATUS_EMPTY = "empty_content";
// 全局状态布局的属性值
public static HashMap<String, StatusConfigBean> GlobalStatusConfigs = new HashMap<>();
public static void setGlobalStatusConfigs(StatusConfigBean[] statusConfigBeans) {
for (StatusConfigBean statusConfigBean : statusConfigBeans) {
GlobalStatusConfigs.put(statusConfigBean.getStatus(), statusConfigBean);
}
}
//全局切换动画
public static int GlobalInAnimation = R.anim.anim_status_layout_alpha_in;
public static int GlobalOutAnimation = R.anim.anim_status_layout_alpha_out;
public static void setGlobalAnimation(int inAnim, int outAnim) {
GlobalInAnimation = inAnim;
GlobalOutAnimation = outAnim;
}
}
|
0a4ce594556ac17f0ce75adcc9f72593fa98c73c
|
[
"Markdown",
"Java"
] | 15
|
Java
|
fddsocool/AndroidWidgets
|
da058c62a4f91c557740a69980277a3a3ed358b9
|
51a95f44382fa104964c46030027b150f8227e66
|
refs/heads/master
|
<repo_name>drummerprogrammer/bmw-landing<file_sep>/src/js/smooth-scroll.js
import SmoothScroll from 'smooth-scroll';
export const initSmoothScroll = () => new SmoothScroll('a[href*="#"]');
<file_sep>/src/js/scrolls.js
import ScrollOut from 'scroll-out';
import {setScrollAnimation} from './utils';
import {tubeParallax, appsParallax, appsValParallax, appsDiscountParallax, clubWheelRotate} from './animations';
const MAIN_VIDEO_ELEMENT = document.querySelector('#slide-main video');
export const initScrolls = () => ScrollOut({
// show
onShown: function (el, ctx) {
const {intersectY, offsetY, elementHeight} = ctx;
if (el.tagName === 'VIDEO') {
el.play();
el.style.opacity = '1';
}
if (el.classList.contains('fade')) {
el.classList.add('fadeIn');
}
if (el.id === 'slide-start' && intersectY === -1) {
MAIN_VIDEO_ELEMENT.play();
MAIN_VIDEO_ELEMENT.style.opacity = '1';
}
if (el.id === 'slide-tube') {
setScrollAnimation(tubeParallax, offsetY, elementHeight);
}
if (el.id === 'slide-apps') {
setScrollAnimation(appsParallax, offsetY, elementHeight);
setScrollAnimation(appsValParallax, offsetY, elementHeight);
setScrollAnimation(appsDiscountParallax, offsetY, elementHeight);
}
if (el.id === 'slide-club') {
setScrollAnimation(clubWheelRotate, offsetY, elementHeight);
}
},
onHidden: function (el, {intersectY}) {
if (el.tagName === 'VIDEO') {
el.pause();
el.style.opacity = '0';
}
if (el.classList.contains('fade')) {
el.classList.remove('fadeIn');
}
if (el.id === 'slide-start' && intersectY === -1) {
MAIN_VIDEO_ELEMENT.pause();
MAIN_VIDEO_ELEMENT.style.opacity = '0';
}
},
});
<file_sep>/src/js/lazy-loading.js
export const initLazyLoading = () => document.addEventListener('DOMContentLoaded', () => {
if ('IntersectionObserver' in window) {
const lazyloadImages = document.querySelectorAll('.lazy');
const imageObserver = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
const img = entry.target;
if (img.dataset.src) {
img.src = img.dataset.src;
}
img.classList.remove('lazy');
imageObserver.unobserve(img);
}
});
}, {
rootMargin: '0px',
threshold: 0.1,
});
lazyloadImages.forEach((image) => imageObserver.observe(image));
}
});
<file_sep>/src/js/index.js
import {initLazyLoading} from './lazy-loading';
import {initScrolls} from './scrolls';
import {initSoundControl} from './sound-controll';
import {initStars} from './stars';
import {initSmoothScroll} from './smooth-scroll';
import {initPhotoswipe} from './photoswipe';
import {initGlider} from './glider';
initSoundControl();
initStars();
initScrolls();
initSmoothScroll();
initLazyLoading();
initPhotoswipe('.gallery');
initGlider('.gallery-glider', {rewind: true}, true);
initGlider('.inspires-glider', {
slidesToShow: 5,
slidesToScroll: 5,
draggable: false,
});
<file_sep>/postcss.config.js
module.exports = ({file, options, env}) => ({
plugins: {
'autoprefixer': {
'browsers': '>0.25%, not dead, not ie <= 11',
},
}
});
<file_sep>/src/js/glider.js
import Glider from 'glider-js';
export const initGlider = (gliderSelector, options, autoplay) => {
window.addEventListener('DOMContentLoaded', () => {
const delay = 3000;
const elements = document.querySelectorAll(gliderSelector);
elements.forEach((el) => {
const idx = el.dataset.index;
const prev = `[data-index="${idx}"] ~ .glider-prev`;
const next = `[data-index="${idx}"] ~ .glider-next`;
const glider = new Glider(el, {
...options,
arrows: {
prev,
next,
},
});
if (autoplay) {
let interval = null;
const startSlideShow = (glider) => interval = setInterval(() => glider.scrollItem('next'), delay);
startSlideShow(glider);
const isTouchInteraction = 'ontouchstart' in window || navigator.msMaxTouchPoints;
const event = isTouchInteraction ? 'touchstart' : 'click';
window.addEventListener(event, ({target}) => {
const isClickInside = el.parentElement.contains(target);
if (isClickInside) {
clearInterval(interval);
interval = null;
} else {
if (!interval) {
startSlideShow(glider);
}
}
}, {passive: true});
}
});
},
);
};
<file_sep>/src/js/stars.js
export const initStars = () => {
const container = document.getElementById('main-stars');
if (container) {
const stars = container.querySelectorAll('.stars_star');
stars.forEach((star) => {
star.addEventListener('mouseenter', ({target}) => {
target.click();
}, {passive: true})
});
}
};
<file_sep>/src/js/sound-controll.js
export const initSoundControl = () => {
const mainSlide = document.getElementById('slide-main');
if (mainSlide) {
const video = mainSlide.querySelector('video');
const soundBtn = mainSlide.querySelector('.sound-button');
soundBtn.addEventListener('click', () => {
const isMuted = !video.muted;
video.muted = isMuted;
if (isMuted) {
soundBtn.classList.remove('sound-on');
soundBtn.classList.add('sound-off');
} else {
soundBtn.classList.remove('sound-off');
soundBtn.classList.add('sound-on');
}
});
}
};
<file_sep>/src/js/utils.js
export const calcScrollPercent = (startScrollPosition, step) => {
const val = (window.scrollY - startScrollPosition) / step;
if (val > 100) return 100;
if (val < 0) return 0;
return val;
};
export const setScrollAnimation = (animation, offsetY, elementHeight) => {
const wh = window.innerHeight;
const startScrollPosition = offsetY - wh;
const step = (elementHeight + wh) / 100;
if (!animation.listen) {
document.addEventListener('scroll', () => {
const value = calcScrollPercent(startScrollPosition, step);
animation.seek(value);
}, {passive: true});
animation.listen = true;
}
};
|
411b69ca8136e9bbff35f7120c1f75153fedfa51
|
[
"JavaScript"
] | 9
|
JavaScript
|
drummerprogrammer/bmw-landing
|
2fdf5414eec7467987eff83144c3b1e562a4340a
|
24774fdafc507dd7e0f85c7c36259e31fc77bda6
|
refs/heads/master
|
<file_sep>import React, { useState } from 'react';
const TodoGroup = (props) => {
const { data, index } = props;
const dataset = data[index];
const [ list, setList ] = useState(dataset.list);
const [ text, setText ] = useState('');
const TodoList = list.map((item, index) => {
const { description, checked } = item;
return (
<div key={index}>
<input type="checkbox" checked={checked} />
{description}
</div>
)
})
const handleChange = (e) => {
setText(e.target.value);
}
const handleSubmit = (e) => {
setList([
...list,
{
"description": text,
"checked": false
}
])
setText('');
e.preventDefault();
}
return (
<div className="TodoList">
<form onSubmit={handleSubmit}>
<input onChange={handleChange} value={text} placeholder="Add Todo" />
<button>추가</button>
</form>
{ TodoList }
</div>
)
}
export default TodoGroup;<file_sep>import React, { useState } from 'react';
import TodoMenu from './TodoMenu';
import TodoGroup from './TodoGroup';
const DATA = {
"result": {
"groups": [
{
"name": "2018년 목표",
"list": [
{
"description": "직장구하기",
"checked": false
},
{
"description": "몸무게정상화",
"checked": false
},
{
"description": "건강정상화",
"checked": false
},
{
"description": "HTML & CSS 공부",
"checked": false
}
]
},
{
"name": "가족",
"list": [
{
"description": "집사기",
"checked": false
},
{
"description": "땅사기",
"checked": false
},
{
"description": "가출하기",
"checked": false
},
{
"description": "집에가기",
"checked": false
}
]
}
]
}
}
const App = () => {
const dataGroups = DATA.result.groups;
const [ index, setIndex ] = useState(0);
const [ data, setData ] = useState(dataGroups);
return (
<div className="app">
<TodoMenu data={data} index={index} setIndex={setIndex} />
<TodoGroup data={data} setData={setData} index={index} />
</div>
)
}
export default App;<file_sep># TDD (Test Driven Development)
* 테스트 주도 개발
* 테스트를 먼저 작성하고, 개발을 하는 것
## TDD 실패 이유
* 아무도 스펙을 몰라.
* 시간이 오래 걸린다.
## 유사 TDD
* 개발자가 알 수 있는 범위 내에서 스펙을 최대한 상세하게 작성하기
* 해당 스펙을 기준으로 기능을 쪼개고, 컴포넌트를 쪼개자
# TodoApp
UI
* TodoGroup이 존재한다.
* TodoGroup은 좌측 List에 노출된다.
<!-- * TodoGroup의 제목이 TodoList 상단에 노출된다. -->
* TodoGroup에는 하나의 TodoList만 존재한다.
* TodoList는 최대 갯수가 없다.
* TodoList의 빈공간을 클릭했을 경우, 추가가 가능하다.
* TodoItem은 TodoList의 추가 버튼을 통해 추가가 가능하다.
* TodoItem은 동시에 여러개 추가가 불가능하다.
<!-- * TodoItem은 설명을 가지고 있다. -->
* TodoItem은 체크박스를 통해 Clear 가능하다.
* Clear된 TodoItem은 별도 리스트를 통해 확인 가능하다.
* TodoItem은 설명 수정이 가능하다.<file_sep>import React, { useState, useEffect } from 'react';
const TodoItem = (props) => {
const { description, checked } = props.item;
const { index } = props;
const [ checkState, setCheckState ] = useState(checked);
const handleChange = () => {
setCheckState(!checkState);
}
return (
<div key={index}>
<input type="checkbox" checked={checkState} onChange={handleChange} />
{description}
</div>
)
}
export default TodoItem;<file_sep>import React, { useState } from 'react';
const Form = (props) => {
const [ text, setText ] = useState('');
const { list, setList } = props;
const handleSubmit = (e) => {
e.preventDefault();
setList([
...list,
{
"description": text,
"checked": false
}
])
setText('');
}
const handleChange = (e) => {
setText(e.target.value);
}
return (
<form onSubmit={handleSubmit}>
<input value={text} onChange={handleChange} />
<button>전송</button>
</form>
)
}
export default Form;<file_sep>import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App'
import Todo from './components/Todo'
ReactDOM.render(<Todo />, document.querySelector("#app"));
|
68d3abe4f5003db6ad57954d478b31ebfe770ea4
|
[
"JavaScript",
"Markdown"
] | 6
|
JavaScript
|
react-study-201/study-2
|
d2ae1a4e2c7ce06b2afbbe339a63c395c1623d6a
|
935fe22d0dd89cd241f14dcf3db0b5f605c181a5
|
refs/heads/master
|
<repo_name>HSZemi/espenhain<file_sep>/sp/menu.py
MENU = [
('index','Aktuelles',False),
('ueber', 'Über das SP',False),
('zusammensetzung','Zusammensetzung',True),
('fraktionen','Fraktionen',True),
('sitzungen','Sitzungen',True),
('dokumente','Dokumente',False),
('protokolle','Protokolle',False),
('beschluesse','Beschlüsse',False),
('ausschuesse','Ausschüsse',True),
('praesidium','Präsidium',True),
('kontakt','Kontakt',False),
('impressum','Impressum',False),
('archiv','Archiv',False),
]
<file_sep>/amsel/forms.py
from django import forms
from django.forms import ModelForm, ValidationError
from datetime import date
from sp.helpers import get_places, get_ausschuesse, get_zusammensetzung, get_sitzungen, get_sitzungen_dokumente, get_all_sps, get_current_sp, is_subpath, get_dokumente, get_date_from_filename, get_beschluesse, get_protokoll_parts, is_uninetz, get_sitzung, validate_hook, get_praesidium
from amsel.helpers import get_all_sps_formvalues, get_committees_formvalues, get_protocol_types, get_folder_formvalues
class ResolutionForm(forms.Form):
title = forms.CharField(label="Titel des Beschlusses:")
resolutionfile = forms.FileField(label="Datei:")
sp_nr = forms.ChoiceField(choices=get_all_sps_formvalues(), label="SP:")
class ProtocolForm(forms.Form):
protocolfile = forms.FileField(label="Datei:")
sp_nr = forms.ChoiceField(choices=get_all_sps_formvalues(), label="SP:")
committee_id = forms.ChoiceField(choices=get_committees_formvalues(), label="Gremium:")
meeting_nr = forms.IntegerField(label="Sitzungsnummer:",help_text="0 für konstituierende Sitzung, 1-n für die weiteren Sitzungen.")
meeting_date = forms.DateField(label="Sitzungsdatum")
protocol_type = forms.ChoiceField(choices=get_protocol_types(), label="Protokolltyp")
is_special_meeting = forms.BooleanField(label="Außerordentliche Sitzung", help_text="Auswählen, falls es sich um eine außerordentliche Sitzung handelte.", required=False)
class MeetingNewForm(forms.Form):
committee_id = forms.ChoiceField(choices=get_committees_formvalues(), label="Gremium:")
meeting_date = forms.DateField(label="Sitzungsdatum")
class MeetingEditForm(forms.Form):
json = forms.CharField(label="JSON", widget=forms.Textarea)
class DocumentForm(forms.Form):
folderchoices = get_folder_formvalues(get_current_sp(), include_next_session=True)
startindex = 1 if len(folderchoices) > 1 else 0
title = forms.CharField(label="Titel der Datei:")
documentfile = forms.FileField(label="Datei:")
folder = forms.ChoiceField(choices=folderchoices, label="Sitzung:", initial=folderchoices[startindex][0])
class LoginForm(forms.Form):
username = forms.CharField(label='Account:')
password = forms.CharField(label='Passwort:', widget=forms.PasswordInput)
class EmptyForm(forms.Form):
pass
class CommitteeEditForm(forms.Form):
def __init__(self, *args, **kwargs):
members = kwargs.pop('members')
super(CommitteeEditForm, self).__init__(*args, **kwargs)
for i, member in enumerate(members):
if not 'delete' in member or member['delete'] == False:
self.fields['member_{}_name'.format(i)] = forms.CharField(label="Name {}".format(i), initial=member['name'])
self.fields['member_{}_faction'.format(i)] = forms.CharField(label="Fraktion {}".format(i), initial=member['faction'])
self.fields['member_{}_status'.format(i)] = forms.ChoiceField(label="Status {}".format(i), choices=[('m','Mitglied'),('#','stv. Mitglied'),('1','Vorsitz'),('2','stv. Vorsitz')], initial=member['status'])
self.fields['member_{}_delete'.format(i)] = forms.BooleanField(label="Löschen {}".format(i), required=False)
def extra_answers(self):
for name, value in self.cleaned_data.items():
if name.startswith('member_'):
yield (name[9:], int(name[7]), value)
class AddCommitteeMemberForm(forms.Form):
name = forms.CharField(label="Name", initial='')
faction = forms.CharField(label="Fraktion", initial='')
status = forms.ChoiceField(label="Status", choices=[('m','Mitglied'),('#','stv. Mitglied'),('1','Vorsitz'),('2','stv. Vorsitz')], initial='m')<file_sep>/sp/views.py
# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse, Http404, FileResponse
from django.utils.dateparse import parse_datetime
from django.utils.encoding import force_bytes
from django.core.exceptions import PermissionDenied
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from .menu import MENU
import os
import json
import csv
import datetime
from collections import OrderedDict
from .helpers import get_places, get_ausschuesse, get_zusammensetzung, get_sitzungen, get_sitzungen_dokumente, get_all_sps, get_current_sp, is_subpath, get_dokumente, get_date_from_filename, get_beschluesse, get_protokoll_parts, is_uninetz, get_sitzung, validate_hook, get_praesidium
import mimetypes
from subprocess import check_call, CalledProcessError
from distutils.dir_util import copy_tree
# Create your views here.
BASE_DIR = settings.BASE_DIR
def index(request):
#return HttpResponse('index')
sitzungen = get_sitzungen(sp=get_current_sp(), count=3)
context = {'menu':MENU, 'sp_number':get_current_sp(), 'sitzungen':sitzungen}
return render(request, 'sp/aktuelles.tpl', context)
def ueber(request):
context = {'menu':MENU}
return render(request, 'sp/ueber.tpl', context)
def zusammensetzung(request, archiv_sp=None):
sp = archiv_sp
if(sp == None):
sp = get_current_sp()
table = get_zusammensetzung(sp=sp)
sitze_count = 0
for row in table:
sitze_count += int(row['seats'])
context = {'menu':MENU, 'sitze_count':sitze_count, 'sp_number':sp, 'table':table, 'archiv_sp':archiv_sp}
return render(request, 'sp/zusammensetzung.tpl', context)
def fraktionen(request, archiv_sp=None):
sp = archiv_sp
if(sp == None):
sp = get_current_sp()
zusammensetzung = get_zusammensetzung(sp=sp)
factions = {}
non_factions = []
for line in zusammensetzung:
fraktionsname = line['faction']
if fraktionsname != '':
if fraktionsname not in factions:
factions[fraktionsname] = []
factions[fraktionsname].append(line['list'])
else:
non_factions.append(line['list'])
context = {'menu':MENU, 'factions':factions, 'non_factions':non_factions, 'archiv_sp':archiv_sp}
return render(request, 'sp/fraktionen.tpl', context)
def sitzungen(request, archiv_sp=None):
sp = archiv_sp
if(sp == None):
sp = get_current_sp()
sitzungen = get_sitzungen(sp=sp)
context = {'menu':MENU, 'sitzungen':sitzungen, 'sp_number':sp, 'archiv_sp':archiv_sp}
return render(request, 'sp/sitzungen.tpl', context)
def sitzungen_rss(request, archiv_sp=None):
sp = archiv_sp
if(sp == None):
sp = get_current_sp()
sitzungen = get_sitzungen(sp=sp)
context = {'sitzungen':sitzungen, 'sp_number':sp, 'archiv_sp':archiv_sp}
return render(request, 'sp/sitzungen_rss.tpl', context, content_type='application/rss+xml; charset=utf-8')
def sitzungen_ics(request, sp=get_current_sp(), jsonfile=None):
sitzungen = None
if(jsonfile == None):
sitzungen = get_sitzungen(sp=sp)
else:
directory = os.path.join(BASE_DIR, "sp/data/{sp}/sitzungen".format(sp=sp))
jsonfile = "{jsonfile}.json".format(jsonfile=jsonfile)
if "/" in jsonfile or not os.path.isfile(os.path.join(directory, jsonfile)):
raise Http404
sitzungen = [get_sitzung(directory, jsonfile)]
context = {'sitzungen':sitzungen, 'sp_number':sp}
return render(request, 'sp/ics.tpl', context, content_type='text/calendar; charset=utf-8')
def dokumente(request, archiv_sp=None):
sp = archiv_sp
if(sp == None):
sp = get_current_sp()
global_documents = get_dokumente(sp)
all_sessions = []
for sp_nr in get_all_sps():
sessions = []
sessionnumbers = get_sitzungen_dokumente(sp_nr)
for sessionnumber in sessionnumbers:
documents = get_dokumente(sp=sp_nr, sitzung=sessionnumber)
sessions.append({'session':sessionnumber, 'documents':documents})
all_sessions.append({'sp':sp_nr, 'sessions':sessions})
context = {'menu':MENU, 'documents':global_documents, 'sessions':all_sessions, 'current_sp':sp, 'archiv_sp':archiv_sp}
return render(request, 'sp/dokumente.tpl', context)
def dokumente_dl(request, sp, dateipfad, sitzung=''):
dateipfad = os.path.join(sitzung, dateipfad)
dateiname = os.path.basename(dateipfad)
if dateiname not in ('Einladung.pdf', 'Einladung_0.pdf', 'Einladung_1.pdf', 'Einladung_2.pdf') and not is_uninetz(request):
raise PermissionDenied
dateipfad = os.path.join(BASE_DIR, 'sp/data/{sp}/dokumente'.format(sp=sp), dateipfad)
if not is_subpath(dateipfad, os.path.join(BASE_DIR, 'sp/data/{sp}/dokumente'.format(sp=sp))) or not os.path.isfile(dateipfad):
raise Http404
response = FileResponse(open(dateipfad, 'rb'), content_type=mimetypes.guess_type(dateipfad)[0])
#response['Content-Disposition'] = "attachment; filename={0}".format(os.path.basename(dateipfad))
return response
def idx(request, dateipfad='index.html'):
templatepfad = os.path.join('idx', dateipfad)
dateipfad = os.path.join(BASE_DIR, 'sp/templates/idx', dateipfad)
if not is_subpath(dateipfad, os.path.join(BASE_DIR, 'sp/templates/idx')) or not os.path.isfile(dateipfad):
raise Http404
context = {'menu':MENU, 'document':templatepfad}
return render(request, 'sp/idx.tpl', context)
@csrf_exempt
def idx_hook(request):
if(validate_hook(request)):
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
if(body['repository']['id'] == 32903194):
if(body['head_commit']['modified'] or body['head_commit']['added'] or body['head_commit']['removed']):
try:
check_call(['git','--git-dir=/opt/vs-bonn/.git', '--work-tree=/opt/vs-bonn', 'pull'])
copy_tree('/opt/vs-bonn/html', '/opt/web/espenhain/sp/templates/idx')
return HttpResponse("yes")
except CalledProcessError as cpe:
return HttpResponse("cpe {0}".format(cpe.returncode))
return HttpResponse("no")
#return request.json["compare"]
def protokolle(request, ausschuss='sp'):
ausschuesse = get_ausschuesse()
all_protocols_n = []
if (ausschuss != 'sp') and (ausschuss not in ausschuesse):
raise Http404
for sp in get_all_sps():
protocols_n = []
path = os.path.join(BASE_DIR, 'sp/data/{sp}/protokolle/{ausschuss}'.format(sp=sp, ausschuss=ausschuss))
intern_path = os.path.join(BASE_DIR, 'sp/data/{sp}/protokolle/sp/intern'.format(sp=sp))
if not os.path.exists(path):
continue
for file in os.listdir(path):
if not os.path.isdir(os.path.join(path,file)):
parts = get_protokoll_parts(file)
if(parts != None):
if(parts['dateityp'] != 'dummy'):
parts['url'] = os.path.join("{0}/{1}".format(ausschuss, sp), file)
parts['intern'] = False
protocols_n.append(parts)
if ausschuss == 'sp':
for file in os.listdir(intern_path):
if not os.path.isdir(os.path.join(intern_path, file)):
parts = get_protokoll_parts(file)
if(parts != None):
if(parts['dateityp'] != 'dummy'):
parts['url'] = os.path.join("sp/{0}/intern".format(sp), file)
parts['intern'] = True
protocols_n.append(parts)
protocols_n.sort(key=lambda k: k['nummer'], reverse=True)
protocols_n.sort(key=lambda k: k['sitzungstyp'], reverse=True)
protocols_n.sort(key=lambda k: str(k['datum']), reverse=True)
all_protocols_n.append((sp, protocols_n))
title = "Studierendenparlament"
if ausschuss in ausschuesse:
title = ausschuesse[ausschuss]
context = {'menu':MENU, 'ausschuesse' : ausschuesse, 'title' : "Protokolle - {}".format(title), 'protocols_n':all_protocols_n, 'ausschuss':ausschuss}
return render(request, 'sp/protokolle.tpl', context)
def archiv(request):
context = {'menu':MENU, 'all_sps' : get_all_sps()}
return render(request, 'sp/archiv.tpl', context)
def protokolle_dl(request, sp, dateiname, ausschuss, intern=False):
if '/' in dateiname:
raise Http404
if intern:
dateiname = os.path.join('intern', dateiname)
if not is_uninetz(request):
raise PermissionDenied
dateipfad = os.path.join(BASE_DIR, 'sp/data/{sp}/protokolle/{ausschuss}'.format(sp=sp, ausschuss=ausschuss), dateiname)
if not is_subpath(dateipfad, os.path.join(BASE_DIR, 'sp/data/{sp}/protokolle/{ausschuss}'.format(sp=sp, ausschuss=ausschuss))) or (not os.path.isfile(dateipfad)):
raise Http404
response = FileResponse(open(dateipfad, 'rb'), content_type=mimetypes.guess_type(dateipfad)[0])
#response['Content-Disposition'] = "attachment; filename={0}".format(os.path.basename(dateipfad))
return response
def protokolle_dl_intern(request, sp, dateiname, ausschuss):
return protokolle_dl(request, sp, dateiname, ausschuss, intern=True)
def beschluesse(request):
beschluesse = []
for sp in get_all_sps():
documents = get_beschluesse(sp=sp)
beschluesse.append({'sp':sp, 'documents':documents})
context = {'menu':MENU, 'beschluesse':beschluesse}
return render(request, 'sp/beschluesse.tpl', context)
def beschluesse_dl(request, sp, dateiname):
#if not is_uninetz(request):
# raise PermissionDenied
dateipfad = os.path.join(BASE_DIR, 'sp/data/{sp}/beschluesse'.format(sp=sp), dateiname)
if not is_subpath(dateipfad, os.path.join(BASE_DIR, 'sp/data/{sp}/beschluesse'.format(sp=sp))) or ('/' in dateiname) or (not os.path.isfile(dateipfad)):
raise Http404
response = FileResponse(open(dateipfad, 'rb'), content_type=mimetypes.guess_type(dateipfad)[0])
#response['Content-Disposition'] = "attachment; filename={0}".format(os.path.basename(dateipfad))
return response
def ausschuesse(request, archiv_sp=None):
sp = archiv_sp
if(sp == None):
sp = get_current_sp()
committees = []
path = os.path.join(BASE_DIR, 'sp/data/{0}/ausschuesse'.format(sp))
if os.path.isdir(path):
files = os.listdir(path)
files.sort()
for file in files:
fpath = os.path.join(path,file)
if not os.path.isfile(fpath):
continue
name, ext = os.path.splitext(file)
title = name.split('_',1)[1] if '_' in name and name.split('_',1)[0].isdigit() else name
title = title.replace('ae', 'ä').replace('ue', 'ü').replace('oe', 'ö').replace('sz', 'ß')
title = title.replace('Ae', 'Ä').replace('Ue', 'Ü').replace('Oe', 'Ö').replace('_', ' ')
committee = { 'title':title, 'members':[], 'deputy_members':[], 'name':name }
if ext == '.txt':
with open(fpath, 'r') as f:
committee['text'] = f.read().strip()
committees.append(committee)
elif ext == '.tsv':
with open(fpath, 'r') as f:
reader = csv.DictReader(f, delimiter='\t')
for line in reader:
if line['status'] == '#':
committee['deputy_members'].append(line)
else:
committee['members'].append(line)
committees.append(committee)
context = {'menu':MENU, 'committees':committees, 'archiv_sp':archiv_sp}
return render(request, 'sp/ausschuesse.tpl', context)
def praesidium(request, archiv_sp=None):
sp = archiv_sp
if(sp == None):
sp = get_current_sp()
praesidium = get_praesidium(sp=sp)
context = {'menu':MENU, 'chair':praesidium, 'sp_number':sp, 'archiv_sp':archiv_sp}
return render(request, 'sp/praesidium.tpl', context)
def praesidium_image(request, sp=get_current_sp()):
dateipfad = os.path.join(BASE_DIR, 'sp/data/{0}/praesidium/praesidium.jpg'.format(sp))
if not os.path.isfile(dateipfad):
dateipfad = os.path.join(BASE_DIR, 'sp/static/sp/vide.png')
return FileResponse(open(dateipfad, 'rb'), content_type=mimetypes.guess_type(dateipfad)[0])
def kontakt(request):
context = {'menu':MENU}
return render(request, 'sp/kontakt.tpl', context)
def impressum(request):
praesidium = get_praesidium(sp=get_current_sp())
context = {'menu':MENU, 'president':praesidium[0]}
return render(request, 'sp/impressum.tpl', context)
def custom404(request):
context = {'menu':MENU}
return render(request, 'sp/404.tpl', context)
def custom403(request):
context = {'menu':MENU}
return render(request, 'sp/403.tpl', context)
<file_sep>/amsel/views.py
from django.shortcuts import render
from django.http import HttpResponse, Http404
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import redirect
from django.conf import settings
from amsel.menu import MENU
from sp.helpers import get_places, get_ausschuesse, get_zusammensetzung, get_sitzungen, get_sitzungen_dokumente, get_all_sps, get_current_sp, is_subpath, get_dokumente, get_date_from_filename, get_beschluesse, get_protokoll_parts, is_uninetz, get_sitzung, validate_hook, get_praesidium
from .forms import ResolutionForm, ProtocolForm, LoginForm, EmptyForm, CommitteeEditForm, AddCommitteeMemberForm, DocumentForm, MeetingNewForm, MeetingEditForm
from amsel.helpers import handle_uploaded_resolution, add_entry_to_tsv_file, handle_uploaded_protocol, remove_file, remove_file_from_tsv, save_committee, get_committee, add_to_committee, handle_uploaded_document, create_meeting, get_meeting, get_next_meeting_filename, get_meetings
from amsel.models import History
import os
import csv
BASE_DIR = settings.BASE_DIR
@login_required
def index(request):
context = {'menu':MENU, 'sp':get_current_sp()}
return render(request, 'amsel/index.tpl', context)
@login_required
def ausschuesse(request):
ausschuesse = []
directory = os.path.join(BASE_DIR, "sp/data/{sp}/ausschuesse".format(sp=get_current_sp()))
if(os.path.isdir(directory)):
for filename in sorted(os.listdir(directory)):
if(os.path.isfile(os.path.join(directory, filename)) and len(filename) > 4 and filename[-4:] == ".tsv"):
ausschuesse.append(filename)
context = {'menu':MENU, 'sp':get_current_sp(), 'ausschuesse':ausschuesse}
return render(request, 'amsel/ausschuesse.tpl', context)
@login_required
def ausschuesse_bearbeiten(request, dateiname):
messages = []
ausschuss = get_committee(sp=get_current_sp(), dateiname=dateiname)
form = CommitteeEditForm(request.POST or None, members=ausschuss)
if request.POST:
if form.is_valid():
ausschuss = []
ausschuss_raw = {}
for fieldname, person_id, value in form.extra_answers():
if(person_id not in ausschuss_raw):
ausschuss_raw[person_id] = {}
if fieldname == 'status' and value == 'm':
value = ''
ausschuss_raw[person_id][fieldname] = value
for person_id in sorted(ausschuss_raw):
ausschuss.append(ausschuss_raw[person_id])
retval = save_committee(request.user, dateiname, ausschuss)
if(retval):
messages.append({'klassen':'alert-success','text':'<strong>Hurra!</strong> Der Ausschuss wurde aktualisiert.'})
form = CommitteeEditForm(members=ausschuss)
else:
messages.append({'klassen':'alert-warning','text':'<strong>Hoppala!</strong> Das hat nicht funktioniert.'})
else:
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Bitte fülle das Formular korrekt aus.'})
context = {'menu':MENU, 'sp':get_current_sp(), 'form':form, 'messages':messages, 'dateiname':dateiname}
return render(request, 'amsel/ausschuesse_bearbeiten.tpl', context)
@login_required
def ausschuesse_bearbeiten_neues_mitglied(request, dateiname):
messages = []
ausschuss = get_committee(sp=get_current_sp(), dateiname=dateiname)
form = AddCommitteeMemberForm(request.POST or None)
if request.POST:
if form.is_valid():
new_member = {
'name': form.cleaned_data['name'],
'faction':form.cleaned_data['faction'],
'status':form.cleaned_data['status']
}
retval = add_to_committee(request.user, dateiname, new_member)
if(retval):
messages.append({'klassen':'alert-success','text':'<strong>Hurra!</strong> Das neue Ausschussmitglied wurde hinzugefügt.'})
else:
messages.append({'klassen':'alert-warning','text':'<strong>Hoppala!</strong> Das hat nicht funktioniert.'})
else:
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Bitte fülle das Formular korrekt aus.'})
context = {'menu':MENU, 'sp':get_current_sp(), 'form':form, 'messages':messages, 'dateiname':dateiname}
return render(request, 'amsel/ausschuesse_bearbeiten_neu.tpl', context)
@login_required
def history(request):
history = History.objects.all().order_by('-timestamp')
context = {'menu':MENU, 'sp':get_current_sp(), 'history':history}
return render(request, 'amsel/history.tpl', context)
@login_required
def beschluesse(request):
messages = []
form = ResolutionForm()
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = ResolutionForm(request.POST, request.FILES)
# check whether it's valid:
if form.is_valid():
if(get_date_from_filename(request.FILES['resolutionfile'].name) == None):
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Der Dateiname enthält das Beschlussdatum nicht im richtigen Format.'})
else:
filename, huf_messages = handle_uploaded_resolution(request.user, request.FILES['resolutionfile'], form.cleaned_data['sp_nr'])
messages.extend(huf_messages)
if(filename != None):
# add stuff to csv file
success = add_entry_to_tsv_file(request.user, os.path.join(BASE_DIR, 'sp/data', form.cleaned_data['sp_nr'], 'beschluesse/index.tsv'), filename, form.cleaned_data['title'])
if success:
messages.append({'klassen':'alert-success','text':'<strong>Hurra!</strong> Das hat wohl geklappt.'})
form = ResolutionForm()
else:
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Bitte fülle das Formular korrekt aus.'})
context = {'menu':MENU, 'sp':get_current_sp(), 'form':form, 'messages':messages}
return render(request, 'amsel/beschluesse.tpl', context)
@login_required
def beschluesse_entfernen(request):
beschluesse = []
for sp in get_all_sps():
documents = get_beschluesse(sp=sp)
beschluesse.append({'sp':sp, 'documents':documents})
context = {'menu':MENU, 'beschluesse':beschluesse}
return render(request, 'amsel/beschluesse_entfernen.tpl', context)
@login_required
def beschluesse_entfernen_ok(request, sp, dateiname):
messages = []
dateipfad = os.path.join('sp/data/{sp}/beschluesse'.format(sp=sp), dateiname)
tsvfile = 'sp/data/{sp}/beschluesse/index.tsv'.format(sp=sp)
form = EmptyForm()
if not is_subpath(os.path.join(BASE_DIR, dateipfad), os.path.join(BASE_DIR, 'sp/data/{sp}/beschluesse'.format(sp=sp))) or ('/' in dateiname) or (not os.path.isfile(os.path.join(BASE_DIR, dateipfad))):
raise Http404
if request.method == 'POST':
form = EmptyForm(request.POST)
if form.is_valid():
if remove_file(request.user, dateipfad):
if(remove_file_from_tsv(request.user, dateiname, tsvfile)):
messages.append({'klassen':'alert-success','text':'<strong>Jo mei!</strong> Der Beschluss wurde entfernt.'})
else:
messages.append({'klassen':'alert-success','text':'<strong>Jo mei!</strong> Der Beschluss wurde entfernt, aber stand gar nicht in der tsv-Datei.'})
else:
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Das hat nicht funktioniert. Bestimmt nur ein technischer Fehler.'})
else:
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Das hat nicht funktioniert. Bestimmt nur ein technischer Fehler.'})
context = {'menu':MENU, 'dateipfad':dateipfad, 'form':form, 'messages':messages}
return render(request, 'amsel/beschluesse_entfernen_ok.tpl', context)
@login_required
def protokolle(request):
messages = []
form = ProtocolForm()
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = ProtocolForm(request.POST, request.FILES)
# check whether it's valid:
if form.is_valid():
filename, huf_messages = handle_uploaded_protocol(request.user, request.FILES['protocolfile'], form.cleaned_data)
messages.extend(huf_messages)
form = ProtocolForm()
else:
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Bitte fülle das Formular korrekt aus.'})
context = {'menu':MENU, 'sp':get_current_sp(), 'form':form, 'messages':messages}
return render(request, 'amsel/protokolle.tpl', context)
@login_required
def protokolle_entfernen(request):
messages = []
ausschuesse = get_ausschuesse()
ausschuesse['sp'] = "Studierendenparlament"
all_protocols_n = []
for sp in get_all_sps():
for ausschuss in ausschuesse:
protocols_n = []
path = os.path.join(BASE_DIR, 'sp/data/{sp}/protokolle/{ausschuss}'.format(sp=sp, ausschuss=ausschuss))
intern_path = os.path.join(BASE_DIR, 'sp/data/{sp}/protokolle/sp/intern'.format(sp=sp))
if not os.path.exists(path):
continue
for file in os.listdir(path):
if not os.path.isdir(os.path.join(path,file)):
parts = get_protokoll_parts(file)
if(parts != None):
if(parts['dateityp'] != 'dummy'):
parts['url'] = os.path.join("sp/{0}".format(sp), file)
protocols_n.append(parts)
if ausschuss == 'sp':
for file in os.listdir(intern_path):
if not os.path.isdir(os.path.join(intern_path, file)):
parts = get_protokoll_parts(file)
if(parts != None):
if(parts['dateityp'] != 'dummy'):
parts['url'] = os.path.join("sp/{0}/intern".format(sp), file)
protocols_n.append(parts)
protocols_n.sort(key=lambda k: k['nummer'], reverse=True)
protocols_n.sort(key=lambda k: k['sitzungstyp'], reverse=True)
protocols_n.sort(key=lambda k: str(k['datum']), reverse=True)
if(len(protocols_n) > 0):
all_protocols_n.append((sp, ausschuss, protocols_n))
context = {'menu':MENU, 'ausschuesse' : ausschuesse, 'protocols_n':all_protocols_n, 'ausschuss':ausschuss}
return render(request, 'amsel/protokolle_entfernen.tpl', context)
@login_required
def protokolle_entfernen_ok(request, sp, dateiname, ausschuss):
messages = []
dateipfad = os.path.join('sp/data/{sp}/protokolle/{ausschuss}'.format(sp=sp, ausschuss=ausschuss), dateiname)
form = EmptyForm()
if not is_subpath(os.path.join(BASE_DIR, dateipfad), os.path.join(BASE_DIR, 'sp/data/{sp}/protokolle/{ausschuss}'.format(sp=sp, ausschuss=ausschuss))) or ('/' in dateiname) or (not os.path.isfile(os.path.join(BASE_DIR, dateipfad))):
raise Http404
if request.method == 'POST':
form = EmptyForm(request.POST)
if form.is_valid():
if remove_file(request.user, dateipfad):
messages.append({'klassen':'alert-success','text':'<strong>Jo mei!</strong> Das Protokoll wurde entfernt.'})
else:
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Das hat nicht funktioniert. Bestimmt nur ein technischer Fehler.'})
else:
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Das hat nicht funktioniert. Bestimmt nur ein technischer Fehler.'})
context = {'menu':MENU, 'dateipfad':dateipfad, 'form':form, 'messages':messages}
return render(request, 'amsel/protokolle_entfernen_ok.tpl', context)
@login_required
def dokumente(request):
messages = []
form = DocumentForm()
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = DocumentForm(request.POST, request.FILES)
# check whether it's valid:
if form.is_valid():
folder = form.cleaned_data['folder']
if folder == '-':
folder = ''
filename, hud_messages = handle_uploaded_document(request.user, request.FILES['documentfile'], get_current_sp(), folder)
messages.extend(hud_messages)
if(filename != None):
# add stuff to tsv file
success = add_entry_to_tsv_file(request.user, os.path.join(BASE_DIR, 'sp/data', str(get_current_sp()), 'dokumente', folder ,'index.tsv'), filename, form.cleaned_data['title'])
if success:
messages.append({'klassen':'alert-success','text':'<strong>Hurra!</strong> Das hat wohl geklappt.'})
form = DocumentForm()
else:
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Bitte fülle das Formular korrekt aus.'})
context = {'menu':MENU, 'sp':get_current_sp(), 'form':form, 'messages':messages}
return render(request, 'amsel/dokumente.tpl', context)
@login_required
def dokumente_entfernen(request):
dokumente = []
for sp in get_all_sps():
documents = {'index':get_dokumente(sp=sp)}
for sitzung in get_sitzungen_dokumente(sp=sp):
documents[sitzung] = get_dokumente(sp=sp, sitzung=sitzung)
dokumente.append({'sp':sp, 'documents':documents})
context = {'menu':MENU, 'dokumente':dokumente}
return render(request, 'amsel/dokumente_entfernen.tpl', context)
@login_required
def dokumente_entfernen_ok(request, sp, dateiname, folder=''):
messages = []
dateipfad = os.path.join('sp/data/{sp}/dokumente/{folder}'.format(sp=sp, folder=folder), dateiname)
tsvfile = os.path.join('sp/data/{sp}/dokumente/'.format(sp=sp), folder, 'index.tsv')
form = EmptyForm()
if not is_subpath(os.path.join(BASE_DIR, dateipfad), os.path.join(BASE_DIR, 'sp/data/{sp}/dokumente'.format(sp=sp))) or ('/' in dateiname) or (not os.path.isfile(os.path.join(BASE_DIR, dateipfad))):
raise Http404
if request.method == 'POST':
form = EmptyForm(request.POST)
if form.is_valid():
if remove_file(request.user, dateipfad):
if(remove_file_from_tsv(request.user, dateiname, tsvfile)):
messages.append({'klassen':'alert-success','text':'<strong>Jo mei!</strong> Das Dokument wurde entfernt.'})
else:
messages.append({'klassen':'alert-success','text':'<strong>Jo mei!</strong> Das Dokument wurde entfernt, aber stand gar nicht in der tsv-Datei.'})
else:
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Das hat nicht funktioniert. Bestimmt nur ein technischer Fehler.'})
else:
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Das hat nicht funktioniert. Bestimmt nur ein technischer Fehler.'})
context = {'menu':MENU, 'dateipfad':dateipfad, 'form':form, 'messages':messages}
return render(request, 'amsel/dokumente_entfernen_ok.tpl', context)
@login_required
def sitzungen(request):
messages = []
meetings = sorted(get_meetings().items(), reverse=True)
form = MeetingNewForm()
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = MeetingNewForm(request.POST)
# check whether it's valid:
if form.is_valid():
filename = get_next_meeting_filename(form.cleaned_data['meeting_date'], form.cleaned_data['committee_id'], get_current_sp())
return redirect('amsel:sitzungen_edit', sp=get_current_sp(), dateiname=filename)
else:
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Bitte fülle das Formular korrekt aus.'})
context = {'menu':MENU, 'sp':get_current_sp(), 'form':form, 'messages':messages, 'meetings':meetings}
return render(request, 'amsel/sitzungen.tpl', context)
@login_required
def sitzungen_edit(request, sp, dateiname, sp_copy=None, dateiname_copy=None):
messages = []
meetings = sorted(get_meetings().items(), reverse=True)
sp_copy = sp if sp_copy==None else sp_copy
dateiname_copy = dateiname if dateiname_copy==None else dateiname_copy
initial_value = get_meeting(dateiname_copy, sp_copy)
form = MeetingEditForm(initial={'json':initial_value})
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = MeetingEditForm(request.POST)
# check whether it's valid:
if form.is_valid():
cm_messages = create_meeting(dateiname, form.cleaned_data['json'], sp)
messages.extend(cm_messages)
else:
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Bitte fülle das Formular korrekt aus.'})
context = {'menu':MENU, 'sp':sp, 'dateiname':dateiname, 'form':form, 'messages':messages, 'meetings':meetings}
return render(request, 'amsel/sitzungen_edit.tpl', context)
@login_required
def sitzungen_entfernen(request):
messages = []
meetings = sorted(get_meetings().items(), reverse=True)
form = MeetingNewForm()
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = MeetingNewForm(request.POST)
# check whether it's valid:
if form.is_valid():
filename = get_next_meeting_filename(form.cleaned_data['meeting_date'], form.cleaned_data['committee_id'], get_current_sp())
return redirect('amsel:sitzungen_edit', sp=get_current_sp(), dateiname=filename)
else:
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Bitte fülle das Formular korrekt aus.'})
context = {'menu':MENU, 'sp':get_current_sp(), 'form':form, 'messages':messages, 'meetings':meetings}
return render(request, 'amsel/sitzungen_entfernen.tpl', context)
@login_required
def sitzungen_entfernen_ok(request, sp, dateiname):
messages = []
dateipfad = os.path.join('sp/data/{sp}/sitzungen/'.format(sp=sp), dateiname)
form = EmptyForm()
if not is_subpath(os.path.join(BASE_DIR, dateipfad), os.path.join(BASE_DIR, 'sp/data/{sp}/sitzungen'.format(sp=sp))) or ('/' in dateiname) or (not os.path.isfile(os.path.join(BASE_DIR, dateipfad))):
raise Http404
if request.method == 'POST':
form = EmptyForm(request.POST)
if form.is_valid():
if remove_file(request.user, dateipfad):
messages.append({'klassen':'alert-success','text':'<strong>Jo mei!</strong> Die Sitzung wurde entfernt.'})
else:
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Das hat nicht funktioniert. Bestimmt nur ein technischer Fehler.'})
else:
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Das hat nicht funktioniert. Bestimmt nur ein technischer Fehler.'})
context = {'menu':MENU, 'dateipfad':dateipfad, 'form':form, 'messages':messages}
return render(request, 'amsel/sitzungen_entfernen_ok.tpl', context)
def loginpage(request):
form = LoginForm()
username = None
messages = []
next_page = 'amsel:index'
if('next' in request.GET and len(request.GET['next']) > 0 and request.GET['next'][0] == '/'):
next_page = request.GET['next']
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
passwort = form.cleaned_data['password']
user = authenticate(username=username, password=passwort)
if user is not None:
if user.is_active:
login(request, user)
return redirect('amsel:index')
else:
# Return a 'disabled account' error message
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Dein Zugang wurde deaktiviert. Bitte wende dich an das IT-Referat.'})
else:
# Return an 'invalid login' error message.
messages.append({'klassen':'alert-danger','text':'<strong>Herrje!</strong> Das hat nicht funktioniert. Hast du Account und Passwort auch wirklich korrekt eingegeben?'})
else:
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Bitte fülle das Formular korrekt aus.'})
context = {'menu':[], 'messages' : messages, 'account':username, 'form':form}
return render(request, 'amsel/login.tpl', context)<file_sep>/README.md
# espenhain
espenhain!
<file_sep>/sp/static/sp/protokoll_toggle.js
$(document).ready(function() {
$(".top div").hide();
//toggle the componenet with class msg_body
var h3s = $(".top:has(div) h3");
h3s.append('<span class="toggler">▸</span>').css('cursor', 'pointer');
h3s.click(function()
{
var h3 = $(this);
var content = h3.next(".top div");
var toggler = h3.children('.toggler');
content.slideToggle(500, function(){
if (content.css('display') == 'none')
toggler.text('▸')
else
toggler.text('▼')
});
});
});<file_sep>/sp/static/sp/mail.js
"use strict";
(function(){
var data = {
'01_Haushaltsausschuss': '#?vsdq#vw|oh@%irqw0vl}h=#93(%A+?d#kuhi@%pdlowr=vs0kkdCdvwd1xql0erqq1gh%ANrqwdnw?2dA,?2vsdqA',
'02_Kassenpruefungsausschuss': '#?vsdq#vw|oh@%irqw0vl}h=#93(%A+?d#kuhi@%pdlowr=vs0nsdCdvwd1xql0erqq1gh%ANrqwdnw?2dA,?2vsdqA',
'03_Wahlausschuss': '#?vsdq#vw|oh@%irqw0vl}h=#93(%A+?d#kuhi@%pdlowr=vs0zdkoCdvwd1xql0erqq1gh%ANrqwdnw?2dA,?2vsdqA',
'04_Wahlpruefungsausschuss': '#?vsdq#vw|oh@%irqw0vl}h=#93(%A+?d#kuhi@%pdlowr=vs0zsdCdvwd1xql0erqq1gh%ANrqwdnw?2dA,?2vsdqA',
'05_Ausschuss_fuer_den_Hilfsfonds_zur_Unterstuetzung_in_Not_geratener_Studierender': '#?vsdq#vw|oh@%irqw0vl}h=#93(%A+?d#kuhi@%pdlowr=vs0klirCdvwd1xql0erqq1gh%ANrqwdnw?2dA,?2vsdqA',
'06_Satzungs-_und_Geschaeftsordnungsausschuss': '#?vsdq#vw|oh@%irqw0vl}h=#93(%A+?d#kuhi@%pdlowr=vs0vjrCdvwd1xql0erqq1gh%ANrqwdnw?2dA,?2vsdqA',
'07_Ausschuss_fuer_den_Rechtshilfefonds': '#?vsdq#vw|oh@%irqw0vl}h=#93(%A+?d#kuhi@%pdlowr=vs0ukdCdvwd1xql0erqq1gh%ANrqwdnw?2dA,?2vsdqA',
'08_Semesterticketausschuss': '#?vsdq#vw|oh@%irqw0vl}h=#93(%A+?d#kuhi@%pdlowr=vs0vwdCdvwd1xql0erqq1gh%ANrqwdnw?2dA,?2vsdqA'
}
for (var id in data) {
var el = document.getElementById(id);
if (el) {
el.innerHTML = el.innerHTML + decr(data[id]);
}
}
function decr(s){
var items = s.split("");
var out = "";
var codein, codeout;
for(var i = 0; i < items.length; i++){
codein = items[i].charCodeAt(0);
codeout = codein - 3;
out += String.fromCharCode(codeout);
}
return out;
}
})();
<file_sep>/amsel/models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class History(models.Model):
timestamp = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User)
description = models.TextField()<file_sep>/amsel/helpers.py
from sp.helpers import get_all_sps, get_ausschuesse, is_subpath, get_current_sp, get_sitzungen_dokumente
from django.conf import settings
import os
import shutil
import csv
from amsel.models import History
BASE_DIR = settings.BASE_DIR
def get_all_sps_formvalues():
all_sps = get_all_sps()
for i in range(len(all_sps)):
all_sps[i] = (all_sps[i], all_sps[i])
return all_sps
def get_committees_formvalues():
retval = [('sp','Studierendenparlament')]
all_committees = get_ausschuesse()
for key in all_committees:
retval.append((key, all_committees[key]))
return retval
def get_folder_formvalues(sp_nr, include_next_session=False):
retval = [('-','-')]
sessions = get_sitzungen_dokumente(sp_nr)
max_session = -1
for session in sessions:
retval.append((str(session), str(session)))
max_session = max(max_session, session)
if include_next_session:
# nächste Sitzung in der Reihe
retval.append((str(max_session + 1), str(max_session + 1)))
retval.sort(reverse=True)
return retval
def get_next_meeting_filename(meeting_date, committee_id, sp_nr=get_current_sp()):
for i in range(10):
filename = "{0}_{1}_{2}.json".format(meeting_date.strftime("%Y%m%d"), committee_id, i)
filepath = os.path.join(BASE_DIR, "sp/data", str(sp_nr), "sitzungen", filename)
if not os.path.isfile(filepath):
return filename
return "{0}_{1}_{2}.json".format(meeting_date.strftime("%Y%m%d"), committee_id, "lolwut")
def get_meeting(filename, sp_nr=get_current_sp()):
filepath = os.path.join(BASE_DIR, "sp/data", str(sp_nr), "sitzungen", filename)
if not os.path.isfile(filepath):
return ""
with open(filepath, "r") as f:
return f.read()
def create_meeting(filename, json, sp_nr=get_current_sp()):
filepath = os.path.join(BASE_DIR, "sp/data", str(sp_nr), "sitzungen", filename)
with open(filepath, "w") as f:
f.write(json)
return [{'klassen':'alert-success','text':'<strong>Juhu!</strong> Die Sitzung wurde gespeichert.'}]
def get_meetings():
all_sitzungen = {}
for sp in get_all_sps():
sitzungen_directory = os.path.join(BASE_DIR, "sp/data", str(sp), "sitzungen")
sitzungen = []
if os.path.exists(sitzungen_directory):
files = sorted(os.listdir(sitzungen_directory))
for f in files:
if f[-5:] == ".json":
sitzungen.append(f)
all_sitzungen[sp] = sorted(sitzungen, reverse=True)
return all_sitzungen
def handle_uploaded_resolution(user, f, sp_id):
messages = []
filename = None
if(f.content_type not in ('application/pdf','image/png','image/jpg','image/jpeg')):
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Bitte lade nur PDF-, PNG- oder JPG-Dateien hoch.'})
return (None, messages)
extension = f.name[-4:].lower()
if(extension not in ('.pdf','.png','.jpg')):
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Bitte lade nur PDF-, PNG- oder JPG-Dateien hoch.'})
return (None, messages)
filedir = "sp/data/{0}/beschluesse".format(sp_id)
filename = f.name
filepath = os.path.join(filedir, filename)
if(not is_subpath(filepath, filedir)):
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Es ist ein Problem mit dem Dateinamen aufgetreten.'})
return (None, messages)
if(not os.path.isdir(os.path.join(BASE_DIR, filedir))):
os.makedirs(os.path.join(BASE_DIR, filedir))
with open(os.path.join(BASE_DIR, filepath), 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
messages.append({'klassen':'alert-success','text':'<strong>Der Beschluss wurde erfolgreich hochgeladen.</strong>'})
log(user, "Beschluss '{}' wurde hochgeladen.".format(filepath))
return (filename, messages)
def handle_uploaded_protocol(user, f, meta):
messages = []
filename = None
if(f.content_type not in ('application/pdf')):
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Bitte lade nur PDF-Dateien hoch.'})
return (None, messages)
extension = f.name[-4:].lower()
if(extension not in ('.pdf')):
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Bitte lade nur PDF-Dateien hoch.'})
return (None, messages)
filedir = "sp/data/{0}/protokolle/{1}".format(meta['sp_nr'], meta['committee_id'])
pdate = meta['meeting_date'].strftime("%Y%m%d")
ptype = meta['protocol_type']
pnumber = meta['meeting_nr']
pao = "ao" if meta['is_special_meeting'] else ""
filename = "{date}_{type}_{number}{ao}.pdf".format(date=pdate, type=ptype, number=pnumber, ao=pao)
filepath = os.path.join(filedir, filename)
if(not is_subpath(filepath, filedir)):
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Es ist ein Problem mit dem Dateinamen aufgetreten.'})
return (None, messages)
if(not os.path.isdir(os.path.join(BASE_DIR, filedir))):
os.makedirs(os.path.join(BASE_DIR, filedir))
with open(os.path.join(BASE_DIR, filepath), 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
messages.append({'klassen':'alert-success','text':'<strong>Das Protokoll wurde erfolgreich hochgeladen.</strong>'})
log(user, "Protokoll '{}' wurde hochgeladen.".format(filepath))
return (filename, messages)
def handle_uploaded_document(user, f, sp_nr, folder):
messages = []
filename = None
if(f.content_type not in ('application/pdf')):
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Bitte lade nur PDF-Dateien hoch.'})
return (None, messages)
extension = f.name[-4:].lower()
if(extension not in ('.pdf')):
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Bitte lade nur PDF-Dateien hoch.'})
return (None, messages)
filedir = "sp/data/{0}/dokumente/{1}".format(sp_nr, folder)
filename = f.name
filepath = os.path.join(filedir, filename)
if(not is_subpath(filepath, filedir)):
messages.append({'klassen':'alert-warning','text':'<strong>Hoppla!</strong> Es ist ein Problem mit dem Dateinamen aufgetreten.'})
return (None, messages)
if(not os.path.isdir(os.path.join(BASE_DIR, filedir))):
os.makedirs(os.path.join(BASE_DIR, filedir))
with open(os.path.join(BASE_DIR, filepath), 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
messages.append({'klassen':'alert-success','text':'<strong>Die Datei wurde erfolgreich hochgeladen.</strong>'})
log(user, "Datei '{}' wurde hochgeladen.".format(filepath))
return (filename, messages)
def add_entry_to_tsv_file(user, tsv_file, filename, title):
lines = []
replaced = False
if os.path.isfile(tsv_file):
with open(tsv_file, "r") as f:
reader = csv.DictReader(f, delimiter="\t")
for line in reader:
if line['filename'] == filename:
line['title'] = title
replaced = True
lines.append(line)
if not replaced:
lines.append({'filename':filename, 'title':title})
with open(tsv_file, "w") as f:
writer = csv.DictWriter(f, fieldnames=['filename','title'], delimiter="\t")
writer.writeheader()
for line in lines:
writer.writerow(line)
log(user, "Datei '{}' wurde zur tsv-Datei '{}' hinzugefügt.".format(filename, tsv_file))
return True
def get_protocol_types():
retval = []
for t in ('Protokoll','Verlaufsprotokoll','Wortprotokoll','Ergebnisprotokoll'):
retval.append((t,t))
return retval
def get_committee(sp, dateiname):
ausschuss = []
filepath = os.path.join(BASE_DIR, "sp/data/{sp}/ausschuesse/{dateiname}".format(sp=sp, dateiname=dateiname))
if(os.path.isfile(filepath)):
with open(filepath, 'r') as f:
reader = csv.DictReader(f, delimiter='\t')
for line in reader:
ausschuss.append(line)
return ausschuss
def remove_file(user, filepath):
fullpath = os.path.join(BASE_DIR, filepath)
if(os.path.isfile(fullpath)):
shutil.move(fullpath, fullpath+".deleted")
log(user, "Datei '{}' wurde entfernt.".format(filepath))
return True
else:
return False
def remove_file_from_tsv(user, filename, tsv_file):
fullpath = os.path.join(BASE_DIR, tsv_file)
lines = []
removed = False
if os.path.isfile(fullpath):
with open(fullpath, "r") as f:
reader = csv.DictReader(f, delimiter="\t")
for line in reader:
if line['filename'] == filename:
removed = True
else:
lines.append(line)
with open(fullpath, "w") as f:
writer = csv.DictWriter(f, fieldnames=['filename','title'], delimiter="\t")
writer.writeheader()
for line in lines:
writer.writerow(line)
if(removed):
log(user, "Datei '{}' wurde aus tsv-Datei '{}' entfernt.".format(filename, tsv_file))
return removed
def save_committee(user, tsv_file, members):
fullpath = os.path.join(BASE_DIR, "sp/data/{sp}/ausschuesse/{dateiname}".format(sp=get_current_sp(), dateiname=tsv_file))
with open(fullpath, "w") as f:
writer = csv.DictWriter(f, fieldnames=['name','faction','status'], delimiter="\t")
writer.writeheader()
for line in members:
if not 'delete' in line or line['delete'] == False:
member = {'name':line['name'],'faction':line['faction'],'status':line['status']}
writer.writerow(member)
log(user, "Der Ausschuss '{}' wurde aktualisiert.".format(fullpath))
return True
def add_to_committee(user, tsv_file, member):
fullpath = os.path.join(BASE_DIR, "sp/data/{sp}/ausschuesse/{dateiname}".format(sp=get_current_sp(), dateiname=tsv_file))
committee = get_committee(get_current_sp(), tsv_file)
with open(fullpath, "w") as f:
writer = csv.DictWriter(f, fieldnames=['name','faction','status'], delimiter="\t")
writer.writeheader()
for line in committee:
writer.writerow(line)
writer.writerow(member)
log(user, "Dem Ausschuss '{}' wurde ein Mitglied hinzugefügt.".format(fullpath))
return True
def log(user, description):
history = History()
history.user = user
history.description = description
history.save()<file_sep>/sp/static/sp/chart.js
function colorbyname(name) {
var name = name.toUpperCase();
if (name == "WAHLBETEILIGUNG") return '#888';
if (name.indexOf("RCDS") != -1) return '#111';
if (name.indexOf("JUSO") != -1) return '#C22';
if (name.indexOf("OLB") != -1) return '#EB4';
if (name.indexOf("GHG") != -1) return '#4A4';
if (name.indexOf("PIRAT") != -1) return '#E91';
if (name.indexOf("LUST") != -1) return '#A44';
if (name.indexOf("LILI") != -1) return '#C46';
if (name.indexOf("UBIG") != -1) return '#94E';
if (name.indexOf("RE(H)") != -1) return '#22C';
return null;
}
function visualizeTable(table, target) {
var data = [];
var rows = $(table).find("tr");
for (var i = 0; i<rows.length; i++) {
var cells = $(rows[i]).children("td");
if (cells.length >= 2) {
var item = { label: $(cells[0]).text(), data: parseInt($(cells[1]).text()), row: $(rows[i]) };
var color = colorbyname(item['label']);
if (color) item['color'] = color;
data.push(item);
}
}
$.plot($(target), data,
{
series: {
pie: {
show: true,
label: {
formatter: function(label, slice){
return '<div style="font-size:x-small;text-align:center;padding:2px;color:'+slice.color+';">'+label+'<br/>'+slice.data[0][1]+'</div>';
}
},
highlight: {
opacity: 0.1,
},
}
},
grid: {
hoverable: true,
},
legend: {
show: false
}
});
$(target).bind("plothover", function (event, pos, obj) {
var rows = $(table).find("tr");
if (!obj) {
rows.removeClass("selected");
return;
}
var current = rows.filter(":contains(\""+obj.series.label+"\")");
current.addClass("selected");
rows.not(current).removeClass("selected");
});
}
function visualizeList (list, target, total) {
var data = [];
var totalcount = 0
var items = $(list).children("li");
for (var i = 0; i<items.length; i++) {
var label = $(items[i]).contents(":not(ul):not(ol)").text();
var cls = $(items[i]).children("ul,ol").attr("class")
var max = null;
if (cls.indexOf('max-') == 0) {
var x = cls.indexOf(' ');
if (x < 0) x = cls.length;
max = parseInt(cls.slice(4, x));
}
var count = $(items[i]).children("ul,ol").children("li").length;
if (max != null)
if (count > max) count=max;
totalcount += count;
var item = { label: label, data: count };
var color = colorbyname(label);
if (color) item['color'] = color;
data.push(item);
}
if (total && (totalcount < total)) {
data.push({ label: '[Abwesend]', data: total-totalcount, color: "#DDD" })
}
$.plot($(target), data,
{
series: {
pie: {
show: true,
label: {
formatter: function(label, slice){
return '<div style="font-size:x-small;text-align:center;padding:2px;color:'+slice.color+';">'+label+'<br/>'+slice.data[0][1]+'</div>';
}
}
}
},
legend: {
show: false
}
});
}
function visualizeVotings () {
var data = [];
var totalcount = 0
var items = $(".abstimmung");
for (var i = 0; i<items.length; i++) {
var item = $(items[i]);
var label = item.contents(".abst-titel").text();
var ja = item.children(".abst-ja").text();
ja = (ja.toLowerCase() == "einstimmig")?51:parseInt(ja);
var nein = item.children(".abst-nein").text();
nein = (nein.toLowerCase() == "einstimmig")?51:parseInt(nein);
var enthaltung = parseInt(item.children(".abst-enthaltung").text());
var color = colorbyname(label);
var data = [{ label: 'Ja', data: [[1,ja]], color: ((ja)?"#3D3":"#EFE") },
{ label: 'Nein', data: [[2,nein]], color: ((nein)?"#D33":"#FEE") },
{ label: 'Enthaltung', data: [[3,enthaltung]], color: ((enthaltung)?"#CCC":"#EEE") }];
var div = $(document.createElement('div'));
var sum = ja+nein+enthaltung+1;
div.addClass('voting-graph');
$(items[i]).before(div);
$.plot(div, data,
{
series: {
stack: 0,
lines: {show: false, steps: false },
bars: { show: true, barWidth: 0.9, align: 'center' }
},
legend: {
show: false
},
grid: { borderWidth:0 },
xaxis: { show:false },
yaxis: { show:false, min: 0, max:sum },
});
}
}
function visualizeSPDifferences(table1, table2, target) {
var data = [];
var data1 = {};
var data2 = {};
var beteiligung1 = 0;
var beteiligung2 = 0;
var div = $(document.createElement('div'));
var rows = $(table1).find("tr");
for (var i = 0; i<rows.length; i++) {
var cells = $(rows[i]).children("td");
if (cells.length >= 2) {
data1[$(cells[0]).text()] = parseInt($(cells[1]).text());
beteiligung1 += parseInt($(cells[2]).text());
}
}
rows = $(table2).find("tr");
for (var i = 0; i<rows.length; i++) {
var cells = $(rows[i]).children("td");
if (cells.length >= 2) {
data2[$(cells[0]).text()] = parseInt($(cells[1]).text());
beteiligung2 += parseInt($(cells[2]).text());
}
}
data.push({ label: "Wahlbeteiligung", data: (beteiligung2-beteiligung1) });
for (var key in data2) {
var neu = data2[key];
var alt = data1[key];
var item = { label: key, data: (neu-alt) };
var color = colorbyname(item['label']);
if (color) item['color'] = color;
data.push(item);
}
$.plot($(target), data,
{
series: {
stack: 0,
lines: {show: true, steps: false },
bars: { show: true, barWidth: 0.9, align: 'center' }
},
legend: {
show: false
},
grid: { borderWidth:0 },
xaxis: { show:false },
yaxis: { show:false },
});
}
$(document).ready(function () {
if ($('#sp-table').length > 0) {
visualizeTable("#sp-table", "#chart");
//visualizeSPDifferences("#sp-table-old", "#sp-table", "#chart1");
}
});
<file_sep>/amsel/menu.py
MENU = [
('amsel:index','Index',False),
('amsel:ausschuesse','Ausschüsse',False),
('amsel:beschluesse','Beschlüsse +',False),
('amsel:beschluesse_entfernen','Beschlüsse -',False),
('amsel:protokolle','Protokolle +',False),
('amsel:protokolle_entfernen','Protokolle -',False),
('amsel:dokumente','Dokumente + ',False),
('amsel:dokumente_entfernen','Dokumente -',False),
('amsel:sitzungen','Sitzungen +',False),
('amsel:sitzungen_entfernen','Sitzungen -',False),
('amsel:history','History',False),
('admin:password_change','<PASSWORD>wort <PASSWORD>',False),
('admin:logout','Logout',False),
]
<file_sep>/sp/helpers.py
import os
import csv
import json
from pathlib import Path
from django.utils.dateparse import parse_datetime
from django.utils.encoding import force_bytes
import datetime
import time
import ipaddress
import random
import string
import email.utils
from django.conf import settings
import hmac
from hashlib import sha1
BASE_DIR = settings.BASE_DIR
def is_subpath(subpath, path):
subpath = Path(subpath)
path = Path(path)
return (path in subpath.parents)
def rfc822date(date):
''' Änderungsdatum im RFC822-Format '''
if date:
timetuple = date.timetuple()
mktime = time.mktime(timetuple)
return email.utils.formatdate(mktime)
else:
return None
def dtstamp(date):
''' Änderungsdatum im iCal-Format '''
if date:
return date.strftime('%Y%m%dT%H%M%SZ')
else:
return None
def is_uninetz(request):
'''Angemeldete Nutzer dürfen sowieso'''
if request.user.is_authenticated:
return True
''' Prüft, ob der aktuelle Benutzer aus dem Uninetz kommt '''
univ4 = ipaddress.IPv4Network('192.168.127.12/16')
univ6 = ipaddress.IPv6Network('2a00:5ba0::/48')
stwv4 = ipaddress.IPv4Network('172.16.58.3/23')
local = ipaddress.ip_address('127.0.0.1')
addr = ipaddress.ip_address(request.META['REMOTE_ADDR'])
return (addr in univ6) or (addr in univ4) or (addr in stwv4) or (addr == local)
def get_praesidium(sp):
filename = os.path.join(BASE_DIR, 'sp/data/{0}/praesidium/praesidium.tsv'.format(sp))
chair = []
if os.path.isfile(filename):
with open(filename, 'r') as f:
reader = csv.DictReader(f, delimiter='\t')
for line in reader:
chair.append(line)
return chair
def get_dokumente(sp, sitzung=None):
path = os.path.join(BASE_DIR, 'sp/data/{0}/dokumente/index.tsv'.format(sp))
if sitzung != None:
path = os.path.join(BASE_DIR, 'sp/data/{0}/dokumente/{1}/index.tsv'.format(sp, sitzung))
sitzung = str(sitzung)
else:
sitzung = ''
documents = []
try:
with open(path, 'r') as f:
reader = csv.DictReader(f, delimiter='\t')
for line in reader:
if 'filename' in line:
line['path'] = os.path.join(sitzung, line['filename'])
documents.append(line)
except IOError:
pass
return documents
def get_date_from_filename(filename):
if len(filename) >= 8 and filename[0:8].isdigit():
datum_string = filename[0:8]
year = int(datum_string[0:4])
month = int(datum_string[4:6])
day = int(datum_string[6:8])
datum = datetime.date(year, month, day)
return datum
return None
def get_beschluesse(sp):
path = os.path.join(BASE_DIR, 'sp/data/{0}/beschluesse/index.tsv'.format(sp))
documents = []
try:
with open(path, 'r') as f:
reader = csv.DictReader(f, delimiter='\t')
for line in reader:
if 'filename' in line:
line['date'] = get_date_from_filename(line['filename'])
documents.append(line)
except IOError:
pass
beschluesse = {}
for line in documents:
if line['date'] not in beschluesse:
beschluesse[line['date']] = []
beschluesse[line['date']].append(line)
retval = []
for d in sorted(beschluesse, reverse=True):
retval.append({'date':d,'documents':beschluesse[d]})
return retval
def get_protokoll_parts(filename):
datum = ''
datum_pretty = ''
protokolltyp = ''
nummer = -1
sitzungstyp = ''
dateityp = ''
if len(filename) >= 4 and filename[-4:] == '.pdf':
dateityp = 'pdf'
elif len(filename) >= 5 and filename[-5:] == '.html':
dateityp = 'html'
elif len(filename) >= 6 and filename[-6:] == '.dummy':
dateityp = 'dummy'
else:
return None
if len(filename) >= 8 and filename[0:8].isdigit():
datum_string = filename[0:8]
year = int(datum_string[0:4])
month = int(datum_string[4:6])
day = int(datum_string[6:8])
datum = datetime.date(year, month, day)
for typ in ("Protokoll","Verlaufsprotokoll","Ergebnisprotokoll","Wortprotokoll"):
if typ in filename:
protokolltyp = typ
items = filename.split("_")
nr = items[-1]
endung_offset = len(dateityp)+1
if len(nr) > endung_offset:
nr = nr[:-endung_offset]
if "ao" in nr:
sitzungstyp = "außerordentliche"
if len(nr) > 2 and nr[:-2].isdigit():
try:
nummer = int(nr[:-2])
except ValueError:
pass # keep default value
else:
sitzungstyp = "ordentliche"
if nr.isdigit():
try:
nummer = int(nr)
except ValueError:
pass # keep default value
return {'datum':datum, 'protokolltyp':protokolltyp, 'nummer':nummer, 'sitzungstyp':sitzungstyp, 'filename':filename, 'dateityp':dateityp}
def get_current_sp():
return 39
def get_all_sps():
directory = os.path.join(BASE_DIR, "sp/data")
sps = []
for entry in os.listdir(directory):
if os.path.isdir(os.path.join(directory, entry)) and entry.isdigit():
sps.append(int(entry))
sps.sort(reverse=True)
return sps
def get_sitzungen_dokumente(sp):
directory = os.path.join(BASE_DIR, "sp/data/{sp}/dokumente".format(sp=sp))
sessions = []
for entry in os.listdir(directory):
if os.path.isdir(os.path.join(directory, entry)) and entry.isdigit():
sessions.append(int(entry))
sessions.sort(reverse=True)
return sessions
def get_sitzung(directory, jsonfile, sp):
sitzung = None
if not (len(jsonfile) > 5 and os.path.isfile(os.path.join(directory, jsonfile)) and jsonfile[-5:]=='.json'):
return None
places = get_places()
try:
with open(os.path.join(directory, jsonfile), "r") as j:
sitzung = json.load(j)
sitzung['past'] = False
if 'place' in sitzung and sitzung['place'] in places:
sitzung['place'] = places[sitzung['place']]
if 'start' in sitzung:
sitzung['start'] = parse_datetime(sitzung['start'])
if(sitzung['start'] < datetime.datetime.now()):
sitzung['past'] = True
if 'ende' in sitzung:
sitzung['ende'] = parse_datetime(sitzung['ende'])
r = random.Random()
r.seed("{0}{1}".format(sitzung['name'], sitzung['start']))
sitzung['hash'] = ''.join(r.choice(string.ascii_uppercase + string.digits) for _ in range(8))
change_time = int(os.stat(os.path.join(directory, jsonfile)).st_mtime)
sitzung['change_date'] = datetime.datetime.utcfromtimestamp(change_time).replace(tzinfo=datetime.timezone.utc)
sitzung['change_date_rfc822'] = rfc822date(sitzung['change_date'])
sitzung['dtstamp'] = dtstamp(sitzung['change_date'])
sitzung['json_id'] = jsonfile[:-5]
if('folder' in sitzung):
if os.path.isfile(os.path.join(BASE_DIR, "sp/data", str(sp), "dokumente", str(sitzung['folder']), "Einladung.pdf")):
sitzung['agenda_file'] = "Einladung.pdf"
for i in range(4):
if os.path.isfile(os.path.join(BASE_DIR, "sp/data", str(sp), "dokumente", str(sitzung['folder']), "Einladung_{}.pdf".format(i))):
sitzung['agenda_file'] = "Einladung_{}.pdf".format(i)
except:
pass
return sitzung
def get_sitzungen(sp, count=None):
if(count):
count = int(count)
directory = os.path.join(BASE_DIR, "sp/data/{sp}/sitzungen".format(sp=sp))
if not os.path.isdir(directory):
return []
jsonfiles = sorted(os.listdir(directory), reverse=True)
sitzungen = []
for jsonfile in jsonfiles:
if len(jsonfile) > 5 and os.path.isfile(os.path.join(directory, jsonfile)) and jsonfile[-5:]=='.json':
sitzung = get_sitzung(directory, jsonfile, sp)
sitzungen.append(sitzung)
if(count):
count -= 1
if(count < 1):
break
return sitzungen
def get_zusammensetzung(sp):
table = []
filepath = os.path.join(BASE_DIR, 'sp/data/{sp}/zusammensetzung.tsv'.format(sp=sp))
if(os.path.isfile(filepath)):
with open(filepath, 'r') as f:
reader = csv.DictReader(f, delimiter="\t")
for line in reader:
table.append(line)
return table
def get_ausschuesse():
ausschuesse = {}
with open(os.path.join(BASE_DIR, 'sp/data/ausschuesse.tsv'), 'r') as f:
reader = csv.DictReader(f, delimiter="\t")
for line in reader:
ausschuesse[line['id']] = line['name']
return ausschuesse
def get_places():
places = {}
with open(os.path.join(BASE_DIR, 'sp/data/places.tsv'), 'r') as f:
reader = csv.DictReader(f, delimiter="\t")
for line in reader:
places[line['id']] = line
return places
def validate_hook(request):
header_signature = request.META.get('HTTP_X_HUB_SIGNATURE')
if header_signature is None:
return True
sha_name, signature = header_signature.split('=')
if sha_name != 'sha1':
return False
mac = hmac.new(force_bytes(settings.SECRET_GITHUB_HOOK_TOKEN), msg=force_bytes(request.body), digestmod=sha1)
if not hmac.compare_digest(force_bytes(mac.hexdigest()), force_bytes(signature)):
return False
return True
<file_sep>/sp/urls.py
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^ueber/$', views.ueber, name='ueber'),
url(r'^zusammensetzung/$', views.zusammensetzung, name='zusammensetzung'),
url(r'^zusammensetzung/(?P<archiv_sp>[0-9]+)/$', views.zusammensetzung, name='zusammensetzung'),
url(r'^fraktionen/$', views.fraktionen, name='fraktionen'),
url(r'^fraktionen/(?P<archiv_sp>[0-9]+)/$', views.fraktionen, name='fraktionen'),
url(r'^sitzungen/$', views.sitzungen, name='sitzungen'),
url(r'^sitzungen/(?P<archiv_sp>[0-9]+)/$', views.sitzungen, name='sitzungen'),
url(r'^sitzungen/feed.rss$', views.sitzungen_rss, name='sitzungen_rss'),
url(r'^sitzungen/(?P<archiv_sp>[0-9]+)/feed.rss$', views.sitzungen_rss, name='sitzungen_rss'),
url(r'^sitzungen/cal.ics$', views.sitzungen_ics, name='sitzungen_ics'),
url(r'^sitzungen/(?P<sp>[0-9]+)/cal.ics$', views.sitzungen_ics, name='sitzungen_ics'),
url(r'^sitzungen/(?P<sp>[0-9]+)/(?P<jsonfile>.+).ics$', views.sitzungen_ics, name='sitzung_ics_single'),
url(r'^dokumente/$', views.dokumente, name='dokumente'),
url(r'^dokumente/idx/$', views.idx, name='idx'),
url(r'^dokumente/idx/hook/$', views.idx_hook, name='idx_hook'),
url(r'^dokumente/idx/(?P<dateipfad>.+)$', views.idx, name='idx'),
url(r'^dokumente/dl/(?P<sp>[0-9]+)/(?P<dateipfad>.+)$', views.dokumente_dl, name='dokumente_dl'),
url(r'^dokumente/dl/(?P<sp>[0-9]+)/(?P<sitzung>[0-9.]+)/(?P<dateipfad>.+)$', views.dokumente_dl, name='dokumente_dl'),
url(r'^protokolle/$', views.protokolle, name='protokolle'),
url(r'^protokolle/(?P<ausschuss>[a-z]+)/$', views.protokolle, name='protokolle'),
url(r'^protokolle/dl/(?P<sp>[0-9]+)/(?P<ausschuss>[a-z]+)/intern/(?P<dateiname>.+)$', views.protokolle_dl_intern, name='protokolle_dl_intern'),
url(r'^protokolle/dl/(?P<sp>[0-9]+)/(?P<ausschuss>[a-z]+)/(?P<dateiname>.+)$', views.protokolle_dl, name='protokolle_dl'),
url(r'^beschluesse/$', views.beschluesse, name='beschluesse'),
url(r'^beschluesse/dl/(?P<sp>[0-9]+)/(?P<dateiname>.+)$', views.beschluesse_dl, name='beschluesse_dl'),
url(r'^ausschuesse/$', views.ausschuesse, name='ausschuesse'),
url(r'^ausschuesse/(?P<archiv_sp>[0-9]+)/$', views.ausschuesse, name='ausschuesse'),
url(r'^praesidium/$', views.praesidium, name='praesidium'),
url(r'^praesidium/(?P<archiv_sp>[0-9]+)/$', views.praesidium, name='praesidium'),
url(r'^praesidium/image$', views.praesidium_image, name='praesidium_image'),
url(r'^praesidium/(?P<sp>[0-9]+)/image$', views.praesidium_image, name='praesidium_image'),
url(r'^archiv/$', views.archiv, name='archiv'),
url(r'^kontakt/$', views.kontakt, name='kontakt'),
url(r'^impressum/$', views.impressum, name='impressum'),
]<file_sep>/amsel/urls.py
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^login/$', views.loginpage, name='login'),
url(r'^ausschuesse/$', views.ausschuesse, name='ausschuesse'),
url(r'^ausschuesse/bearbeiten/(?P<dateiname>.+)/neu$', views.ausschuesse_bearbeiten_neues_mitglied, name='ausschuesse_bearbeiten_neues_mitglied'),
url(r'^ausschuesse/bearbeiten/(?P<dateiname>.+)$', views.ausschuesse_bearbeiten, name='ausschuesse_bearbeiten'),
url(r'^beschluesse/$', views.beschluesse, name='beschluesse'),
url(r'^beschluesse/entfernen/$', views.beschluesse_entfernen, name='beschluesse_entfernen'),
url(r'^beschluesse/entfernen/(?P<sp>[0-9]+)/(?P<dateiname>.+)$', views.beschluesse_entfernen_ok, name='beschluesse_entfernen_ok'),
url(r'^protokolle/$', views.protokolle, name='protokolle'),
url(r'^protokolle/entfernen/$', views.protokolle_entfernen, name='protokolle_entfernen'),
url(r'^protokolle/entfernen/(?P<sp>[0-9]+)/(?P<ausschuss>[a-z]+)/(?P<dateiname>.+)$', views.protokolle_entfernen_ok, name='protokolle_entfernen_ok'),
url(r'^dokumente/$', views.dokumente, name='dokumente'),
url(r'^dokumente/entfernen/$', views.dokumente_entfernen, name='dokumente_entfernen'),
url(r'^dokumente/entfernen/(?P<sp>[0-9]+)/(?P<folder>[0-9.]+)/(?P<dateiname>.+)$', views.dokumente_entfernen_ok, name='dokumente_entfernen_ok'),
url(r'^dokumente/entfernen/(?P<sp>[0-9]+)/(?P<dateiname>.+)$', views.dokumente_entfernen_ok, name='dokumente_entfernen_ok'),
url(r'^sitzungen/$', views.sitzungen, name='sitzungen'),
url(r'^sitzungen/entfernen/$', views.sitzungen_entfernen, name='sitzungen_entfernen'),
url(r'^sitzungen/entfernen/(?P<sp>[0-9]+)/(?P<dateiname>[^/]+)$', views.sitzungen_entfernen_ok, name='sitzungen_entfernen_ok'),
url(r'^sitzungen/edit/(?P<sp>[0-9]+)/(?P<dateiname>[^/]+)/copyfrom/(?P<sp_copy>[0-9]+)/(?P<dateiname_copy>[^/]+)$', views.sitzungen_edit, name='sitzungen_edit_copy'),
url(r'^sitzungen/edit/(?P<sp>[0-9]+)/(?P<dateiname>[^/]+)$', views.sitzungen_edit, name='sitzungen_edit'),
url(r'^history/$', views.history, name='history'),
]
|
7b1ca5d0d8ee89840587d9d9f0b74bd55359176b
|
[
"Markdown",
"Python",
"JavaScript"
] | 14
|
Python
|
HSZemi/espenhain
|
565f10b4b9c8d82992a4821ea3f69c39bee3fe3f
|
83802af8a128973908561d57a37cadc7861d7ab7
|
refs/heads/master
|
<file_sep>package com.zulu.fragmentstate;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.zulu.fragmentstate.fragments.FragmentA;
import com.zulu.fragmentstate.fragments.FragmentB;
public class MainActivity extends AppCompatActivity implements FragmentA.Communicator {
public static final String INDEX_KEY = "key";
private FragmentA fragmentA;
private FragmentB fragmentB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeVariables();
}
private void initializeVariables() {
fragmentA = (FragmentA) getSupportFragmentManager().findFragmentById(R.id.first_fragment);
fragmentA.setComunicador(this);
}
@Override
public void respond(int index) {
//Initialize fragmentB and chech if its in portrait or landscape mode
fragmentB = (FragmentB) getSupportFragmentManager().findFragmentById(R.id.second_fragment);
//Check if landscape mode is the current mode
if(fragmentB!=null && fragmentB.isVisible()){
//Change the content of the fragment
fragmentB.changeData(index);
}else{
//Portrairt mode only fragmentA visible
Intent i = new Intent(this,DetailActivity.class);
i.putExtra(INDEX_KEY,index);
startActivity(i);
}
}
}
<file_sep>package com.zulu.fragmentstate;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.zulu.fragmentstate.fragments.FragmentB;
public class DetailActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
int index = getIntent().getIntExtra(MainActivity.INDEX_KEY,0);
FragmentB fragmentoB = (FragmentB) getSupportFragmentManager().findFragmentById(R.id.second_fragment);
if(fragmentoB!=null){
fragmentoB.changeData(index);
}
}
}
|
b9107d1ecca6bc6a33eb718e0b9a29093ab7942f
|
[
"Java"
] | 2
|
Java
|
zulu15/FlexibleUIExample
|
c1db75ddd471d2da9916781dfdf1e3c3c86a056f
|
f0a07d58373604be0f8678c8feda9b1f37b9b31c
|
refs/heads/master
|
<file_sep>[](https://packagist.org/packages/ismail0234/trendyol-php-api)
[](https://packagist.org/packages/ismail0234/trendyol-php-api)
[](https://packagist.org/packages/ismail0234/trendyol-php-api)
# Trendyol PHP Api
Bu api trendyol için yazılmıştır. Trendyol pazaryeri için yazılmış olan gelişmiş bir php apisi. Ekstra olarak trendyol üzerinde mağazanıza gelen siparişleri websitenize aktaracak bir fonksiyonda mevcuttur.
## Katkı Çağrısı
Çok fazla vaktim olmadığından Trendyolun bütün api fonksiyonları tamamlanmamıştır. Eksik fonksiyonları isterseniz tamamlayarak **pull request** gönderebilirsiniz veya istediğiniz fonksiyonun eklenmesi için **issue** açabilirsiniz.
### Change Log
- See [ChangeLog](https://github.com/ismail0234/trendyol-php-api/blob/master/CHANGELOG.md)
### Licence
- See [ChangeLog](https://github.com/ismail0234/trendyol-php-api/blob/master/LICENCE)
## Hızlı Bakış
* [Kurulum](#kurulum)
* [Kullanım](#kullanım)
* [Marka Servisi (Brand Service)](#marka-servisi-brand-service)
* [Kargo Servisi (Cargo Service)](#kargo-servisi-cargo-service)
* [Kategori Servisi (Category Service)](#kategori-servisi-category-service)
* [Ürün Servisi (Product Service)](#ürün-servisi-product-service)
* [Sipariş Servisi (Order Service)](#sipariş-servisi-order-service)
* [Trendyol Sipariş Bildirimi WebHook (Trendyol Order WebHook)](#trendyol-sipariş-bildirimi-webhook-trendyol-order-webhook)
## Kurulum
Kurulum için composer kullanmanız gerekmektedir. Composer'a sahip değilseniz windows için [Buradan](https://getcomposer.org/) indirebilirsiniz.
```php
composer require ismail0234/trendyol-php-api
```
## Kullanım
```php
include "vendor/autoload.php";
use IS\PazarYeri\Trendyol\TrendyolClient;
use IS\PazarYeri\Trendyol\Helper\TrendyolException;
$trendyol = new TrendyolClient();
$trendyol->setSupplierId(100000);
$trendyol->setUsername("xxxxxxxxxxxxxxxxxxxx");
$trendyol->setPassword("<PASSWORD>");
```
### Marka Servisi (Brand Service)
```php
/**
*
* createProduct servisine yapılacak isteklerde gönderilecek brandId bilgisi bu servis kullanılarak alınacaktır.
* Bir sayfada en fazla 500 adet brand bilgisi alınabilmektedir.
*
* @author <NAME> <<EMAIL>>
* @param int $size
* @param int $pageId
* @return array
*
*/
$trendyol->brand->getBrands(100, 0);
/**
*
* Marka araması yapmak için kullanılır.
* BÜYÜK / küçük harf ayrımına dikkat etmelisiniz.
*
* @author <NAME> <<EMAIL>>
* @param string $brandName
* @return array
*
*/
$trendyol->brand->getBrandByName("Milla");
```
### Kargo Servisi (Cargo Service)
```php
/**
*
* Trendyol üzerindeki bütün kargo şirketlerini getirir.
*
* createProduct V2 servisine yapılacak isteklerde gönderilecek kargo firma bilgileri
* ve bu bilgilere ait ID değerleri bu servis kullanılarak alınacaktır.
*
* Ürün gönderimi yaparken gönderdiğiniz kargo şirketleri, Trendyol sözleşmenizde
* onayladığınız kargo firmasından farklı olmamalıdır. Bu durum ürünlerinizi yayına çıkmasını engelleyecektir.
*
* @author <NAME> <<EMAIL>>
* @return array
*
*/
$trendyol->cargo->getProviders();
/**
*
* Trendyol üzerindeki tedarikçi adreslerinizi getirir.
*
* createProduct V2 servisine yapılacak isteklerde gönderilecek sipariş ve sevkiyat kargo
* firma bilgileri ve bu bilgilere ait ID değerleri bu servis kullanılarak alınacaktır.
*
* "SATICI BAŞVURU SÜRECİM" tam olarak tamamlanmadı ise bu servisi kullanmamanız gerekir.
*
* Ürün gönderimi yaparken adresi ID değerlerini kontrol etmelisiniz. Hatalı gönderim
* yapılması halinde ürün aktarımı gerçekleşmeyecektir.
*
* @author <NAME> <<EMAIL>>
* @return array
*
*/
$trendyol->cargo->getSuppliersAddresses();
```
### Kategori Servisi (Category Service)
```php
/**
*
* Trendyol üzerindeki bütün kategorileri getirir.
* createProduct V2 servisine yapılacak isteklerde gönderilecek categoryId
* bilgisi bu servis kullanılarak alınacaktır.
*
* createProduct yapmak için en alt seviyedeki kategori ID bilgisi kullanılmalıdır.
* Seçtiğiniz kategorinin alt kategorileri var ise bu kategori bilgisi ile ürün aktarımı yapamazsınız.
*
* @author <NAME> <<EMAIL>>
* @return array
*
*/
$trendyol->category->getCategoryTree();
/**
*
* Trendyol üzerindeki kategorinin özelliklerini döndürür.
* createProduct servisine yapılacak isteklerde gönderilecek attributes bilgileri
* ve bu bilgilere ait detaylar bu servis kullanılarak alınacaktır.
*
* createProduct yapmak için en alt seviyedeki kategori ID bilgisi kullanılmalıdır.
* Seçtiğiniz kategorinin alt kategorileri var ise (leaf:true) bu kategori bilgisi ile ürün aktarımı yapamazsınız.
*
* @author <NAME> <<EMAIL>>
* @param int $categoryId
* @return array
*
*/
$trendyol->category->getCategoryAttributes(411);
```
### Ürün Servisi (Product Service)
```php
/**
*
* Trendyol üzerindeki ürünleri filtrelemek için kullanılır.
*
* @author <NAME> <<EMAIL>>
* @note İsteğe bağlı olarak dizideki alanların istenilen bölümleri eklenmeyebilir veya dizi hiç gönderilmeyebilir.
* @return array
*
*/
$trendyol->product->filterProducts(
array(
// Ürün onaylı ya da onaysız kontrolü için kullanılır. Onaylı için true gönderilmelidir
'approved' => true,
// Tekil barkod sorgulamak için gönderilmelidir
'barcode' => '',
// Belirli bir tarihten sonraki ürünleri getirir. Timestamp olarak gönderilmelidir.
'startDate' => time() - (86400 * 7),
//Belirli bir tarihten sonraki önceki getirir. Timestamp olarak gönderilmelidir.
'endDate' => time(),
//Sadece belirtilen sayfadaki bilgileri döndürür.
'page' => 0,
// Tarih filtresinin çalışacağı tarih CREATED_DATE ya da LAST_MODIFIED_DATE gönderilebilir
'dateQueryType' => 'CREATED_DATE',
// Bir sayfada listelenecek maksimum adeti belirtir.
'size' => 50
)
);
```
### Sipariş Servisi (Order Service)
```php
/**
*
* Trendyol sistemine ilettiğiniz ürünler ile planlanın butik sonrası müşteriler tarafından verilen her siparişin bilgisini
* bu method yardımıyla alabilirsiniz. Trendyol.com'da müşteriler tarafından verilen siparişler, sistem tarafından otomatik
* paketlenerek sipariş paketleri oluşturulur. Bu yüzden sistem çektiğiniz bir adet OrderNumber'a karşılık birden fazla
* shipmentPackageID gelebilir.
*
* @note İsteğe bağlı olarak dizideki alanların istenilen bölümleri eklenmeyebilir veya dizi hiç gönderilmeyebilir.
* @param array
*
*/
$trendyol->order->orderList(
array(
// Belirli bir tarihten sonraki siparişleri getirir. Timestamp olarak gönderilmelidir.
'startDate' => time() - (86400 * 14),
// Belirtilen tarihe kadar olan siparişleri getirir. Timestamp olarak gönderilmelidir ve startDate ve endDate aralığı en fazla 2 hafta olmalıdır
'endDate' => time(),
// Sadece belirtilen sayfadaki bilgileri döndürür
'page' => 0,
// Bir sayfada listelenecek maksimum adeti belirtir. (Max 200)
'size' => 200,
// Sadece belirli bir sipariş numarası verilerek o siparişin bilgilerini getirir
'orderNumber' => '',
// Siparişlerin statülerine göre bilgileri getirir. (Created, Picking, Invoiced, Shipped, Cancelled, Delivered, UnDelivered, Returned, Repack, UnSupplied)
'status' => '',
// Siparişler neye göre sıralanacak? (PackageLastModifiedDate, CreatedDate)
'orderByField' => 'CreatedDate',
// Siparişleri sıralama türü? (ASC, DESC)
'orderByDirection' => 'DESC',
// Paket numarasıyla sorgu atılır.
'shipmentPackagesId' => '',
)
);
```
### Trendyol Sipariş Bildirimi WebHook (Trendyol Order WebHook)
Trendyol Tarafından sipariş bildirimleri için bir webhook verilmediği için bu işlemi yapmak isteyenler kişiler için yazılmış olan bir webhook dur. Webhook'u kullanabilmeniz için sunucunuzda **sqlite** pdo driver kurulu olması gerekmektedir.
**Not:** Oluşturacağınız bu dosyayı linux tarafında arkaplanda sürekli çalışır halde kalması gerekmektedir. Bunu yapmak için **tmux** veya **servis yazarak** kullanabilirsiniz. **Cronjob ile kullanmayınız!**
```php
include "vendor/autoload.php";
use IS\PazarYeri\Trendyol\TrendyolClient;
$trendyol = new TrendyolClient();
$trendyol->setSupplierId(100000);
$trendyol->setUsername("xxxxxxxxxxxxxxxxxxxx");
$trendyol->setPassword("<PASSWORD>");
/**
*
* @description Webhook istek hızı
* @param string
* 'slow' => 300 saniye,
* 'medium' => 180 saniye (default/taviye edilen),
* 'fast' => 60 saniye
* 'vfast' => 30 saniye
*
*/
$trendyol->webhook->setRequestMode('medium');
/**
*
* @description Trendyol sonuçlarında kaç siparişin getirileceği
* @param string
* 'vmax' => 200 adet,
* 'max' => 150 adet,
* 'medium' => 100 adet (default/taviye edilen),
* 'min' => 50 adet
*
*/
$trendyol->webhook->setResultMode('medium');
/* Anonymous function ile siparişleri almak */
$trendyol->webhook->orderConsume(function($order){
echo "Sipariş Bilgileri";
echo "<pre>";
print_r($order);
echo "</pre>";
});
/* Class ile siparişleri almak */
Class TrendyolOrders
{
public function consume($order)
{
echo "Sipariş Bilgileri";
echo "<pre>";
print_r($order);
echo "</pre>";
}
}
$trendyol->webhook->orderConsume(array(new TrendyolOrders(), 'consume'));
```
<file_sep><?php
namespace IS\PazarYeri\Trendyol;
use IS\PazarYeri\Trendyol\Helper\Gateway;
Class TrendyolClient extends Gateway
{
/**
*
* @description Trendyol Api SupplierId
* @param string $apiSupplierId
*
*/
public function setSupplierId($apiSupplierId)
{
$this->apiSupplierId = $apiSupplierId;
}
/**
*
* @description Trendyol Api Kullanıcı Adı
* @param string $apiUsername
*
*/
public function setUsername($apiUsername)
{
$this->apiUsername = $apiUsername;
}
/**
*
* @description Trendyol Api Şifre
* @param string $apiPassword
*
*/
public function setPassword($apiPassword)
{
$this->apiPassword = $api<PASSWORD>;
}
/**
*
* @description Trendyol Api Şifre
* @param string $apiPassword
*
*/
public function setTestMode($apiTestMode=false)
{
$this->apiTestMode = $apiTestMode;
}
}
<file_sep><?php
namespace IS\PazarYeri\Trendyol\Helper;
Class TrendyolException extends \Exception {}<file_sep><?php
namespace IS\PazarYeri\Trendyol\Services;
use IS\PazarYeri\Trendyol\Helper\Request;
Class CargoService extends Request
{
/**
*
* Default API Url Adresi
*
* @author <NAME> <<EMAIL>>
* @var string
*
*/
public $apiUrl = '';
/**
*
* Request sınıfı için gerekli ayarların yapılması
*
* @author <NAME> <<EMAIL>>
*
*/
public function __construct($supplierId, $username, $password,$testmode)
{
parent::__construct($this->apiUrl, $supplierId, $username, $password, $testmode);
}
/**
*
* Trendyol üzerindeki bütün kargo şirketlerini getirir.
*
* createProduct servisine yapılacak isteklerde gönderilecek kargo firma bilgileri
* ve bu bilgilere ait ID değerleri bu servis kullanılarak alınacaktır.
*
* Ürün gönderimi yaparken gönderdiğiniz kargo şirketleri, Trendyol sözleşmenizde
* onayladığınız kargo firmasından farklı olmamalıdır. Bu durum ürünlerinizi yayına çıkmasını engelleyecektir.
*
* @author <NAME> <<EMAIL>>
* @return array
*
*/
public function getProviders()
{
$this->setApiUrl('https://api.trendyol.com/sapigw/shipment-providers');
return $this->getResponse(true, true, false);
}
/**
*
* Trendyol üzerindeki tedarikçi adreslerinizi getirir.
*
* createProduct V2 servisine yapılacak isteklerde gönderilecek sipariş ve sevkiyat kargo
* firma bilgileri ve bu bilgilere ait ID değerleri bu servis kullanılarak alınacaktır.
*
* "SATICI BAŞVURU SÜRECİM" tam olarak tamamlanmadı ise bu servisi kullanmamanız gerekir.
*
* Ürün gönderimi yaparken adresi ID değerlerini kontrol etmelisiniz. Hatalı gönderim
* yapılması halinde ürün aktarımı gerçekleşmeyecektir.
*
* @author <NAME> <<EMAIL>>
* @return array
*
*/
public function getSuppliersAddresses()
{
$this->setApiUrl('https://api.trendyol.com/sapigw/suppliers/{supplierId}/addresses');
return $this->getResponse(true, true);
}
}
<file_sep><?php
namespace IS\PazarYeri\Trendyol\Services;
use IS\PazarYeri\Trendyol\Helper\Request;
use IS\PazarYeri\Trendyol\Helper\TrendyolException;
Class ProductService extends Request
{
/**
*
* Default API Url Adresi
*
* @author <NAME> <<EMAIL>>
* @var string
*
*/
public $apiUrl = 'https://api.trendyol.com/sapigw/suppliers/{supplierId}/products';
/**
*
* Request sınıfı için gerekli ayarların yapılması
*
* @author <NAME> <<EMAIL>>
*
*/
public function __construct($supplierId, $username, $password,$testmode)
{
parent::__construct($this->apiUrl, $supplierId, $username, $password, $testmode);
}
/**
*
* Trendyol üzerindeki ürünleri filtrelemek için kullanılır.
*
* @author <NAME> <<EMAIL>>
* @return array
*
*/
public function filterProducts($data = array())
{
$query = array(
'approved' => '',
'barcode' => '',
'startDate' => array('format' => 'unixTime'),
'endDate' => array('format' => 'unixTime'),
'page' => '',
'dateQueryType' => array('required' => array('CREATED_DATE' , 'LAST_MODIFIED_DATE')),
'size' => ''
);
return $this->getResponse($query, $data);
}
/**
* Bu servis kullanılarak gönderilen ürünler Trendyol.com'da daha hızlı yayına alınmaktadır. (Ürün Aktarımı v2)
*
*
* @param array $data
* @return array
* @throws TrendyolException
*/
public function createProducts($data = array())
{
$this->setApiUrl('https://api.trendyol.com/sapigw/suppliers/{supplierId}/v2/products');
$this->setMethod("POST");
$query = array(
'items'=> array(
'barcode' => '',
'title' => '',
'productMainId' => '',
'brandId' => '',
'categoryId' => '',
'quantity' => '',
'stockCode' => '',
'dimensionalWeight' => '',
'description' => '',
'currencyType' => '',
'listPrice' => '',
'salePrice' => '',
'cargoCompanyId' => '',
'deliveryDuration' => '',
'images' => '',
'vatRate' => '',
'shipmentAddressId' => '',
'returningAddressId' => '',
'attributes' => ''
)
);
return $this->getResponse($query, $data);
}
/**
* Ürün bilgilerini güncellemek için kullanılır. (Fiyat ve stok güncellemek için updatePriceAndInventory fonksiyonu kullanılmalıdır)
*
*
* @param array $data
* @return array
* @throws TrendyolException
*/
public function updateProducts($data = array())
{
$this->setApiUrl('https://api.trendyol.com/sapigw/suppliers/{supplierId}/v2/products');
$this->setMethod("PUT");
$query = array(
'items'=> array(
'barcode' => '',
'title' => '',
'productMainId' => '',
'brandId' => '',
'categoryId' => '',
'quantity' => '',
'stockCode' => '',
'dimensionalWeight' => '',
'description' => '',
'currencyType' => '',
'listPrice' => '',
'salePrice' => '',
'cargoCompanyId' => '',
'deliveryDuration' => '',
'images' => '',
'vatRate' => '',
'shipmentAddressId' => '',
'returningAddressId' => '',
'attributes' => ''
),
);
return $this->getResponse($query, $data);
}
/**
* Trendyol'a aktarılan ve onaylanan ürünlerin fiyat ve stok bilgileri eş zamana yakın güncellenir. Stok ve fiyat bligilerini istek içerisinde ayrı ayrı gönderebilirsiniz.
*
* @param array $data
* @return array
* @throws TrendyolException
*/
public function updatePriceAndInventory(array $data = array())
{
$this->setApiUrl('https://api.trendyol.com/sapigw/suppliers/{supplierId}/products/price-and-inventory');
$this->setMethod("POST");
$query = array(
'items'=> array(
'barcode' => '',
'quantity' => '',
'listPrice' => '',
'salePrice' => '',
)
);
return $this->getResponse($query, $data);
}
/**
* Bu method yardımıyla batchRequestId ile alınan işlemlerin sonucunun kontrolü yapılabilir.
*
* @param string $batchRequestId
* @return array
* @throws TrendyolException
*/
public function getBatchRequestResult($batchRequestId)
{
$this->setApiUrl('https://api.trendyol.com/sapigw/suppliers/{supplierId}/products/batch-requests/{batchRequestId}');
return $this->getResponse(true, array('batchRequestId' => $batchRequestId));
}
}
<file_sep><?php
namespace IS\PazarYeri\Trendyol\Helper;
Class Database
{
/**
*
* SQLite Veritabanı Bağlantısı
*
* @author <NAME> <<EMAIL>>
*
*/
protected $db = null;
/**
*
* SQLite Veritabanı Sınıfı Oluşturucu
*
* @author <NAME> <<EMAIL>>
*
*/
public function __construct($firstSetupDate)
{
$this->checkSQLiteAndPDODriver();
$SQLitePath = __DIR__ . '/../Data/';
if (!file_exists($SQLitePath)) {
mkdir($SQLitePath, 0777);
}
$this->db = new \PDO("sqlite:" . $SQLitePath . 'trendyol.sqlite');
$this->db->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->checkAndCreateTables($firstSetupDate);
}
/**
*
* SQLite ve PDO sürücülerini kontrol etme
*
* @author <NAME> <<EMAIL>>
*
*/
protected function checkSQLiteAndPDODriver()
{
$response = \PDO::getAvailableDrivers();
if (count($response) <= 0 || empty($response)) {
throw new TrendyolException("Sunucunuzda PDO Aktif Olmalıdır.");
}
if (!in_array('sqlite', $response)) {
throw new TrendyolException("Sunucunuzda SQLite PDO Sürücüsü Aktif Olmalıdır.");
}
}
/**
*
* SQLite Veritabanı tablolarını kontrol etme ve oluşturma
*
* @author <NAME> <<EMAIL>>
*
*/
public function checkAndCreateTables($firstSetupDate)
{
$sqlQuerys = array(
'CREATE TABLE IF NOT EXISTS `orders` (
`orderid` INTEGER NOT NULL ,
`status` TINYINT NOT NULL DEFAULT \'0\' ,
`date` INTEGER NOT NULL ,
PRIMARY KEY (`orderid`)
);',
'CREATE TABLE IF NOT EXISTS `settings` (
`lastOrderDate` INTEGER NOT NULL DEFAULT \'0\'
);',
);
foreach ($sqlQuerys as $sql) {
$this->db->query($sql);
}
$settings = $this->selectSettings();
if (!isset($settings->lastOrderId)) {
$prepare = $this->db->prepare('INSERT INTO settings (lastOrderDate) VALUES(?)');
$prepare->execute(array($firstSetupDate));
}
}
/**
*
* Siparişleri SQLite üzerinde tamamlandı olarak işaretleme
*
* @author <NAME> <<EMAIL>>
* @param int $orderId
* @return bool
*
*/
public function updateStartDate($startDate)
{
$prepare = $this->db->prepare('UPDATE `settings` SET lastOrderDate = ?');
return $prepare->execute(array($startDate));
}
/**
*
* Siparişleri SQLite üzerinde tutma
*
* @author <NAME> <<EMAIL>>
* @param int $orderId
* @return int
*
*/
public function addOrder($orderId)
{
$prepare = $this->db->prepare('INSERT INTO `orders` (orderid, status, date) VALUES(?, ?, ?)');
$prepare->execute(array($orderId, 0 , time()));
return $this->db->lastInsertId();
}
/**
*
* Siparişleri SQLite üzerinde kontrol etme
*
* @author <NAME> <<EMAIL>>
* @param int $orderId
* @return object
*
*/
public function selectOrder($orderId)
{
$prepare = $this->db->prepare('SELECT * FROM `orders` WHERE orderid = ?');
$prepare->execute(array($orderId));
return $prepare->fetch(\PDO::FETCH_OBJ);
}
/**
*
* Siparişleri SQLite üzerinde tamamlandı olarak işaretleme
*
* @author <NAME> <<EMAIL>>
* @param int $orderId
* @return bool
*
*/
public function finishOrder($orderId)
{
$prepare = $this->db->prepare('UPDATE `orders` SET status = ? WHERE orderid = ?');
return $prepare->execute(array(1 , $orderId));
}
/**
*
* WebHookService Ayarlarını getirir.
*
* @author <NAME> <<EMAIL>>
* @return object
*
*/
public function selectSettings()
{
$prepare = $this->db->prepare('SELECT * FROM `settings`');
$prepare->execute();
return $prepare->fetch(\PDO::FETCH_OBJ);
}
}
<file_sep><?php
namespace IS\PazarYeri\Trendyol\Helper;
Class Format
{
/**
*
* Sınıf ayarlamalarını yapar.
*
* @author <NAME> <<EMAIL>>
*
*/
public static function initialize($query, $data)
{
if ($data === true) {
$data = array();
}
if ($query === true) {
$query = $data;
}
$responseList = array();
foreach ($query as $key => $value)
{
if (!isset($data[$key])) {
continue;
}
if (isset($value['required']) && !in_array($data[$key], $value['required'] )) {
continue;
}
if (isset($value['format'])) {
$formatName = $value['format'];
$data[$key] = self::$formatName($data[$key]);
}
$responseList[$key] = self::trim($data[$key]);
}
return $responseList;
}
/**
*
* Url içerisindeki özel parametleri ayıklar
*
* @author <NAME> <<EMAIL>>
* @param string $apiUrl
* @return array
*
*/
public static function getUrlSpecialParameters($apiUrl)
{
if(preg_match_all('@\{(.*?)\}@si', $apiUrl, $output))
{
return $output[1];
}
return array();
}
/**
*
* UnixTime değerini milisaniye cinsine çevririr.
*
* @author <NAME> <<EMAIL>>
* @param int $timestamp
*
*/
public static function unixTime($timestamp)
{
return $timestamp * 1000;
}
/**
*
* Metnin başındaki ve sonundaki boşlukları siler.
*
* @author <NAME> <<EMAIL>>
* @param int $timestamp
*
*/
public static function trim($text)
{
if(is_string($text)){
return trim($text);
}
return $text;
}
}<file_sep><?php
namespace IS\PazarYeri\Trendyol\Services;
use IS\PazarYeri\Trendyol\Helper\Request;
use IS\PazarYeri\Trendyol\Helper\TrendyolException;
Class SettlementService extends Request
{
/**
*
* Default API Url Adresi
*
* @author <NAME> <<EMAIL>>
* @var string
*
*/
public $apiUrl = 'https://api.trendyol.com/integration/finance/che/sellers/{supplierId}/settlements';
/**
*
* Request sınıfı için gerekli ayarların yapılması
*
* @author <NAME> <<EMAIL>>
*
*/
public function __construct($supplierId, $username, $password, $testmode)
{
parent::__construct($this->apiUrl, $supplierId, $username, $password, $testmode);
}
/**
*
* Trendyol sisteminde oluşan muhasebesel kayıtlarınızı bu servis aracılığı ile entegrasyon üzerinden çekebilirsiniz.
*
* @author <NAME> <<EMAIL>>
* @return array
*
*/
public function getSettlements($data = array())
{
$query = array(
'transactionType' => array('required' => array("Sale", "Return", "Discount", "DiscountCancel", "Coupon", "CouponCancel", "ProvisionPositive", "ProvisionNegative")),
'startDate' => array('required' => array('format' => 'unixTime')),
'endDate' => array('required' => array('format' => 'unixTime')),
'page' => '',
'size' => '',
'supplierId' => array('required' => ''),
);
$this->setApiUrl($this->apiUrl);
return $this->getResponse($query, $data);
}
}<file_sep><?php
namespace IS\PazarYeri\Trendyol\Helper;
use IS\PazarYeri\Trendyol\Services;
Class GateWay
{
/**
*
* @description Trendyol Api Supplier Id
*
*/
public $apiSupplierId;
/**
*
* @description Trendyol Api Kullanıcı Adı
*
*/
public $apiUsername;
/**
*
* @description Trendyol Api Şifre
*
*/
public $apiPassword;
/**
*
* @description Trendyol Test Mode
*
*/
public $apiTestMode;
/**
*
* @description REST Api için kabul edilen servisler
*
*/
protected $allowedServices = array(
'brand' => 'BrandService',
'cargo' => 'CargoService',
'category' => 'CategoryService',
'product' => 'ProductService',
'order' => 'OrderService',
'webhook' => 'WebhookService',
'settlement' => 'SettlementService',
);
/**
*
* @description REST Api servislerinin ilk çağırma için hazırlanması
* @param string
* @return service
*
*/
public function __get($name)
{
if (!isset($this->allowedServices[$name])) {
throw new TrendyolException("Geçersiz Servis!");
}
if (isset($this->$name)) {
return $this->$name;
}
$this->$name = $this->createServiceInstance($this->allowedServices[$name]);
return $this->$name;
}
/**
*
* Servis sınıfının ilk örneğini oluşturma
*
* @author <NAME> <<EMAIL>>
* @param string $serviceName
* @return string
*
*/
protected function createServiceInstance($serviceName)
{
$serviceName = "IS\PazarYeri\Trendyol\Services\\" . $serviceName;
if (!class_exists($serviceName)) {
throw new TrendyolException("Geçersiz Servis!");
}
return new $serviceName($this->apiSupplierId, $this->apiUsername, $this->apiPassword, $this->apiTestMode);
}
}
<file_sep><?php
namespace IS\PazarYeri\Trendyol\Services;
use IS\PazarYeri\Trendyol\Helper\Database;
Class WebhookService extends Database
{
/**
*
* Trendyol Üzerinde yeni siparişlerin sorgulanacağı aralık (saniye)
*
* @author <NAME> <<EMAIL>>
* @var int
*
*/
protected $requestTime = 180;
/**
*
* Son yapılan istek zamanı
*
* @author <NAME> <<EMAIL>>
* @var int
*
*/
protected $requestEndTime;
/**
*
* İlk başlama zamanı
*
* @author <NAME> <<EMAIL>>
* @var int
*
*/
protected $startedTime;
/**
*
* Sipariş listesinden kaç adet sipariş getirileceği.
*
* @author <NAME> <<EMAIL>>
* @var int
*
*/
protected $orderMaxResult = 50;
/**
*
* İlk kurulum için geçerli geçmiş tarih
*
* @author <NAME> <<EMAIL>>
* @var int
*
*/
protected $firstSetupDate;
/**
*
* 1 Yıl için sabit değer
*
* @author <NAME> <<EMAIL>>
* @var int
*
*/
const ONE_YEAR = 86400 * 365;
/**
*
* 2 Hafta için sabit değer
*
* @author <NAME> <<EMAIL>>
* @var int
*
*/
const TWO_WEEK = 86400 * 14;
/**
*
* Request sınıfı için gerekli ayarların yapılması
*
* @author <NAME> <<EMAIL>>
*
*/
public function __construct($supplierId, $username, $password,$testmode)
{
$this->startedTime = time();
$this->requestEndTime = time();
$this->firstSetupDate = time() - self::ONE_YEAR;
$this->order = new OrderService($supplierId, $username, $password,$testmode);
parent::__construct($this->firstSetupDate);
}
/**
*
* Trendyol üzerinden gelen yeni siparişleri tüketir.
*
* @author <NAME> <<EMAIL>>
* @param Class $client
*
*/
public function orderConsume($work)
{
while (true)
{
if (time() >= $this->requestEndTime)
{
$this->requestEndTime = time() + $this->requestTime;
$this->setting = $this->selectSettings();
foreach ($this->getDateBetweenWeeks($this->setting->lastOrderDate) as $date)
{
$orderList = $this->getOrderList($date['startDate'], $date['endDate']);
$this->callEvent($orderList, $work);
for ($pageId = 1; $pageId < $orderList['maxPage']; $pageId++)
{
$orderList = $this->getOrderList($date['startDate'], $date['endDate'], $pageId);
$this->callEvent($orderList, $work);
}
$this->updateStartDate($date['startDate']);
}
}
sleep(1);
}
}
/**
*
* Başlangıç tarihinden itibaren şimdiki zamana kadar haftaları listeler.
*
* @author <NAME> <<EMAIL>>
* @param int $startDate
* @return array
*
*/
protected function getDateBetweenWeeks($startDate)
{
$maxWeek = ceil((time() - $startDate) / self::TWO_WEEK);
if ($maxWeek <= 1) {
return array(array('startDate' => time() - self::TWO_WEEK, 'endDate' => time()));
}
if ($maxWeek > 20) {
$maxWeek = 20;
}
$responseList = array();
for ($i = 0; $i < $maxWeek; $i++) {
$endDate = $startDate + self::TWO_WEEK;
$responseList[] = array('startDate' => $startDate, 'endDate' => $endDate);
$startDate += self::TWO_WEEK;
}
return $responseList;
}
/**
*
* Trenyol siparişlerini getirir.
*
* @author <NAME> <<EMAIL>>
* @param int $startDate
* @param int $endDate
* @param int $pageId = 0
* @return array
*
*/
protected function getOrderList($startDate, $endDate, $pageId = 0)
{
$orderList = $this->order->orderList(array(
'orderByField' => 'CreatedDate',
'orderByDirection' => 'DESC',
'page' => $pageId,
'size' => $this->orderMaxResult,
'startDate' => $startDate,
'endDate' => $endDate
));
$orderResponseList = array();
if (isset($orderList->content) && count($orderList->content) > 0) {
$orderResponseList = $orderList->content;
}
return array('maxPage' => $orderList->totalPages, 'datas' => $orderResponseList);
}
/**
*
* Yeni siparişleri kancalar.
*
* @author <NAME> <<EMAIL>>
* @param array $orderList
* @param Class $work
*
*/
protected function callEvent($orderList, $work)
{
foreach ($orderList['datas'] as $order)
{
$dborder = $this->selectOrder($order->orderNumber);
if (isset($dborder->orderid)) {
continue;
}
$this->addOrder($order->orderNumber);
if (is_array($work)) {
call_user_func_array(array($work[0], $work[1]), array($order));
}else{
$work($order);
}
$this->finishOrder($order->orderNumber);
}
}
/**
*
* Trendyol Siparişlerinin en kadar hızlı tüketileceği.
*
* @author <NAME> <<EMAIL>>
* @param string $mode
*
*/
public function setRequestMode($mode)
{
switch ($mode)
{
case 'slow' : $this->requestTime = 300; break;
case 'fast' : $this->requestTime = 60; break;
case 'vfast' : $this->requestTime = 30; break;
case 'medium':
default:
$this->requestTime = 180;
break;
}
}
/**
*
* Trendyol Sipariş listesinde kaç adet siparişin getirileceği
*
* @author <NAME> <<EMAIL>>
* @param string $mode
*
*/
public function setResultMode($mode)
{
switch ($mode)
{
case 'vmax' : $this->orderMaxResult = 200; break;
case 'max' : $this->orderMaxResult = 150; break;
case 'min' : $this->orderMaxResult = 50; break;
case 'medium' :
default:
$this->orderMaxResult = 100;
break;
}
}
}
<file_sep><?php
namespace IS\PazarYeri\Trendyol\Services;
use IS\PazarYeri\Trendyol\Helper\Request;
Class CategoryService extends Request
{
/**
*
* Default API Url Adresi
*
* @author <NAME> <<EMAIL>>
* @var string
*
*/
public $apiUrl = 'https://api.trendyol.com/sapigw/product-categories';
/**
*
* Request sınıfı için gerekli ayarların yapılması
*
* @author <NAME> <<EMAIL>>
*
*/
public function __construct($supplierId, $username, $password,$testmode)
{
parent::__construct($this->apiUrl, $supplierId, $username, $password, $testmode);
}
/**
*
* Trendyol üzerindeki bütün kategorileri getirir.
* createProduct servisine yapılacak isteklerde gönderilecek categoryId
* bilgisi bu servis kullanılarak alınacaktır.
*
* createProduct yapmak için en alt seviyedeki kategori ID bilgisi kullanılmalıdır.
* Seçtiğiniz kategorinin alt kategorileri var ise bu kategori bilgisi ile ürün aktarımı yapamazsınız.
*
* @author <NAME> <<EMAIL>>
* @return array
*
*/
public function getCategoryTree()
{
$this->setApiUrl($this->apiUrl);
return $this->getResponse(true, true, false);
}
/**
*
* Trendyol üzerindeki kategorinin özelliklerini döndürür.
* createProduct servisine yapılacak isteklerde gönderilecek attributes bilgileri
* ve bu bilgilere ait detaylar bu servis kullanılarak alınacaktır.
*
* createProduct yapmak için en alt seviyedeki kategori ID bilgisi kullanılmalıdır.
* Seçtiğiniz kategorinin alt kategorileri var ise (leaf:true) bu kategori bilgisi ile ürün aktarımı yapamazsınız.
*
* @author <NAME> <<EMAIL>>
* @param int $categoryId
* @return array
*
*/
public function getCategoryAttributes($categoryId)
{
$this->setApiUrl($this->apiUrl . '/{categoryId}/attributes');
return $this->getResponse(true, array('categoryId' => $categoryId), false);
}
}
<file_sep><?php
namespace IS\PazarYeri\Trendyol\Helper;
use IS\PazarYeri\Trendyol\Helper\Format;
Class Request
{
/**
*
* Trendyol Api Software Partner (1 Ocak 2021 Güncellemesi)
* @var string
*
*/
public $apiSoftwarePartner = 'SelfIntegration';
/**
*
* Trendyol Api Software Partner Test Mode
* @var string
*
*/
public $apiTestMode = false;
/**
*
* Trendyol Api Url
* @var string
*
*/
public $apiUrl;
/**
*
* Trendyol Api SupplierId
* @var int
*
*/
protected $apiSupplierId;
/**
*
* Trendyol Api Kullanıcı Adı
* @var string
*
*/
protected $apiUsername;
/**
*
* Trendyol Api Şifre
* @var string
*
*/
protected $apiPassword;
/**
*
* Trendyol Api Şifre
* @var string
*
*/
protected $method;
/**
*
* Get veya post için verileri barındırır.
*
* @author <NAME> <<EMAIL>>
* @var array
*
*/
protected $datas = array();
/**
*
* Service Ayarlarını yapar
* @param string
*
*/
public function __construct($apiUrl, $supplierId, $username, $password,$testmode, $method = 'GET')
{
$this->setApiSupplierId($supplierId);
$this->setApiUsername($username);
$this->setApiPassword($password);
$this->setApiUrl($apiUrl);
$this->setMethod($method);
$this->setApiTestMode($testmode);
}
/**
*
* API SupplierId değerini değiştirir.
*
* @param string $apiUrl
*
*/
public function setApiTestMode($is_test_mode = false)
{
$this->apiTestMode = $is_test_mode;
}
/**
*
* API SupplierId değerini değiştirir.
*
* @param string $apiUrl
*
*/
public function setApiSupplierId($supplierId)
{
$this->apiSupplierId = $supplierId;
}
/**
*
* API Kullanıcı adını değiştirir.
*
* @param string $apiUrl
*
*/
public function setApiUsername($username)
{
$this->apiUsername = $username;
}
/**
*
* API Şifresini değiştirir.
*
* @param string $apiUrl
*
*/
public function setApiPassword($password)
{
$this->apiPassword = $password;
}
/**
*
* Api Linkini ayarlar.
*
* @param string $apiUrl
*
*/
public function setApiUrl($apiUrl)
{
if ($this->apiTestMode) {
$apiUrl = str_replace('api.trendyol.com/sapigw','stageapi.trendyol.com/stagesapigw',$apiUrl);
}
$this->apiUrl = $apiUrl;
}
/**
*
* Method türünü ayarlama POST|GET...
*
* @param string $method
*
*/
public function setMethod($method)
{
$this->method = strtoupper($method);
}
/**
*
* Trendyol için User Agent Döndürür (1 Ocak 2021 Güncellemesi)
*
* @author <NAME> <<EMAIL>>
* @return string
*
*/
protected function userAgent()
{
return $this->apiSupplierId . ' - ' . $this->apiSoftwarePartner;
}
/**
*
* Trendyol için basic auth döndürür
*
* @author <NAME> <<EMAIL>>
* @return string
*
*/
protected function authorization()
{
return base64_encode($this->apiUsername . ':' . $this->apiPassword);
}
/**
*
* Api url bilgisini döner.
*
* @author <NAME> <<EMAIL>>
* @param array $datas
*
*/
public function getApiUrl($requestData)
{
$apiUrl = $this->apiUrl;
foreach (Format::getUrlSpecialParameters($apiUrl) as $key)
{
if (isset($requestData[$key]))
{
$apiUrl = str_replace('{' . $key . '}', $requestData[$key], $apiUrl);
unset($requestData[$key]);
}
}
$apiUrl = str_replace('{supplierId}', $this->apiSupplierId, $apiUrl);
if ($this->method == 'POST' || $this->method == 'PUT' || !is_array($requestData) || count($requestData) <= 0) {
return $apiUrl;
}
return $apiUrl . '?' . http_build_query($requestData);
}
/**
*
* Hazırlanan isteği apiye iletir ve yanıtı json olarak döner.
*
* @author <NAME> <<EMAIL>>
* @param array $query
* @param array $data
* @param boolean $authorization
* @return array
*
*/
public function getResponse($query, $data, $authorization = true)
{
$requestData = Format::initialize($query, $data);
$ch = curl_init();
$header = [];
curl_setopt($ch, CURLOPT_URL, $this->getApiUrl($requestData));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->method);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent());
if ($authorization) {
$header[] = 'Authorization: Basic ' . $this->authorization();
}
if ($this->method == 'POST' || $this->method == 'PUT') {
$header[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($requestData));
}
curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
$response = trim(curl_exec($ch));
if (empty($response)) {
throw new TrendyolException("Trendyol boş yanıt döndürdü.");
}
$response = json_decode($response);
curl_close($ch);
return $response;
}
}
<file_sep><?php
namespace IS\PazarYeri\Trendyol\Services;
use IS\PazarYeri\Trendyol\Helper\Request;
Class BrandService extends Request
{
/**
*
* Default API Url Adresi
*
* @author <NAME> <<EMAIL>>
* @var string
*
*/
public $apiUrl = 'https://api.trendyol.com/sapigw/brands';
/**
*
* Request sınıfı için gerekli ayarların yapılması
*
* @author <NAME> <<EMAIL>>
*
*/
public function __construct($supplierId, $username, $password,$testmode)
{
parent::__construct($this->apiUrl, $supplierId, $username, $password, $testmode);
}
/**
*
* createProduct servisine yapılacak isteklerde gönderilecek brandId bilgisi bu servis kullanılarak alınacaktır.
* Bir sayfada en fazla 500 adet brand bilgisi alınabilmektedir.
*
* @author <NAME> <<EMAIL>>
* @param string $degisken
* @return string
*
*/
public function getBrands($size = 100, $pageId = 0)
{
$this->setApiUrl($this->apiUrl);
return $this->getResponse(true, array('page' => $pageId, 'size' => $size), false);
}
/**
*
* Marka araması yapmak için kullanılır.
* BÜYÜK / küçük harf ayrımına dikkat etmelisiniz.
*
* @author <NAME> <<EMAIL>>
* @param string $degisken
* @return string
*
*/
public function getBrandByName($brandName)
{
$this->setApiUrl($this->apiUrl . '/by-name');
return $this->getResponse(true, array('name' => $brandName), false);
}
}
<file_sep><?php
namespace IS\PazarYeri\Trendyol\Services;
use IS\PazarYeri\Trendyol\Helper\Request;
Class OrderService extends Request
{
/**
*
* Default API Url Adresi
*
* @author <NAME> <<EMAIL>>
* @var string
*
*/
public $apiUrl = 'https://api.trendyol.com/sapigw/suppliers/{supplierId}/orders';
/**
*
* Request sınıfı için gerekli ayarların yapılması
*
* @author <NAME> <<EMAIL>>
*
*/
public function __construct($supplierId, $username, $password,$testmode)
{
parent::__construct($this->apiUrl, $supplierId, $username, $password, $testmode);
}
/**
*
* Trendyol üzerinde siparişleri arar.
*
* @author <NAME> <<EMAIL>>
* @param string $degisken
* @return string
*
*/
public function orderList($data = array())
{
$query = array(
'startDate' => array('format' => 'unixTime'),
'endDate' => array('format' => 'unixTime'),
'page' => '',
'size' => '',
'orderNumber' => '',
'status' => array('required' => array('Created', 'Picking', 'Invoiced', 'Shipped', 'Cancelled', 'Delivered', 'UnDelivered', 'Returned', 'Repack', 'UnSupplied')),
'orderByField' => array('required' => array('PackageLastModifiedDate', 'CreatedDate')),
'orderByDirection' => array('required' => array('ASC', 'DESC')),
'shipmentPackagesId' => '',
);
return $this->getResponse($query, $data);
}
}
|
9666f76064306907d6cc1d96ed9cb9533c693210
|
[
"Markdown",
"PHP"
] | 14
|
Markdown
|
ismail0234/trendyol-php-api
|
c20c3278cf21396b61f28cd7081b17dd9f70fcb8
|
33ba4b00e0f386462608a21c5892f08b72a6afa3
|
refs/heads/master
|
<repo_name>lenis96/store<file_sep>/models/Category.js
module.exports = function (sequelize, Sequelize) {
return sequelize.define('categories', {
description: Sequelize.STRING,
}, {
timestamps: false
}
)
}<file_sep>/models/index.js
var Sequelize = require('sequelize');
// http://www.redotheweb.com/2013/02/20/sequelize-the-javascript-orm-in-practice.html
// initialize database connection
const sequelize = new Sequelize(`mysql://root:@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_DATA_BASE}`,{logging:false});
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.')
})
.catch(err => {
console.error('Unable to connect to the database:', err)
})
// load models
var models = [
'Product',
'Category'
]
models.forEach(function(model) {
module.exports[model] = sequelize.import(__dirname + '/' + model);
})
// export connection
module.exports.sequelize = sequelize;<file_sep>/models/Product.js
module.exports = function (sequelize, Sequelize) {
return sequelize.define('products', {
description: Sequelize.STRING,
price:Sequelize.FLOAT,
quantity:Sequelize.INTEGER
}, {
timestamps: false
}
)
}<file_sep>/controllers/categoriesController.js
'use strict'
const sequalize=require('sequelize')
const models=require('./../models')
const categoriesController={
getCategories:(req,res)=>{
models.Category.findAll().then(categories=>{
res.json({categories:categories})
}).catch((err)=>{
res.json(err)
})
},
getCategoryById:(req,res)=>{
models.Category.findByPk(req.params.id).then(category=>{
res.json(category)
}).catch((err)=>{
})
},
createCategory:(req,res)=>{
models.Category.create(
{
description:req.body.description,
}
).then((categoryId)=>{
models.Category.findByPk(categoryId.id).then((category)=>{
res.json(category)
})
})
},
updateCategoryById:(req,res)=>{
models.Category.findByPk(req.params.id).then(category=>{
return category
}).then((category)=>{
category.description=req.body.description
category.save().then((category)=>{
res.json(category)
}).catch((err)=>{
res.json(err)
})
}).catch((err)=>{
res.json(err)
})
},
deleteCategoryById:(req,res)=>{
models.Category.destroy({
where:{
id:req.params.id
}
}).then((e)=>{
res.json(e)
})
}
}
module.exports=categoriesController<file_sep>/front/src/components/ProductsList.jsx
import React, { Component } from 'react';
import ProductRow from './ProductRow.jsx'
import { withStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import {getProducts} from './../utils/api'
class ProductsList extends Component {
constructor(props){
super(props)
this.state={products:[],content:null}
}
componentDidMount(){
this.setState({content:<div>
<h2>Loading...</h2>
</div>})
getProducts().then(res=>{
this.setState({products:res.data.products})
this.setState({content:<Table>
<TableHead>
<TableRow>
<TableCell>Description</TableCell>
<TableCell>Prices</TableCell>
<TableCell>Quantity</TableCell>
<TableCell>Edit</TableCell>
</TableRow>
</TableHead>
<TableBody>
{this.state.products.map((elem)=>{
return <ProductRow key={elem.id} idProduct={elem.id} description={elem.description} price={elem.price} quantity={elem.quantity}/>
})}
</TableBody>
</Table>})
})
}
render() {
return (
<div>
<h2>Product List</h2>
<div>
{this.state.content}
</div>
</div>
);
}
}
export default ProductsList;
<file_sep>/index.js
'use strict'
require('dotenv').load();
const express=require('express')
const bodyParser=require('body-parser')
const path = require('path');
const app=express()
const api=require('./routes/api')
const passport = require('passport');
require('./passport');
app.use(bodyParser.json())
app.use(express.static('public'))
app.get('/',(req,res)=>{
})
app.use('/api',api)
app.get('*', (req,res) =>{
res.sendFile(path.join(__dirname+'/public/index.html'));
});
app.listen(process.env.PORT,()=>{
console.log(`server running on port ${process.env.PORT}`)
})<file_sep>/README.md
# Store Project with React and Express
## Future:
* Integration with GRAPHQL<file_sep>/front/src/utils/api.js
import axios from 'axios';
// import * as consts from '../config/constants';
export function getProducts(){
return axios.get('/api/product')
}
export function getProduct(id){
return axios.get(`/api/product/${id}`)
}
export function createProduct(product){
return axios.post('/api/product',product)
}
export function deleteProduct(id){
return axios.delete(`/api/product/${id}`)
}
export function updateProduct(id,product){
return axios.put(`/api/product/${id}`,product)
}
<file_sep>/routes/categoriesRoutes.js
const express=require('express')
const categoriesRoutes=express.Router()
const categoriesController=require('./../controllers/categoriesController')
categoriesRoutes.get('/',categoriesController.getCategories)
categoriesRoutes.get('/:id',categoriesController.getCategoryById)
categoriesRoutes.post('/',categoriesController.createCategory)
categoriesRoutes.put('/:id',categoriesController.updateCategoryById)
categoriesRoutes.delete('/:id',categoriesController.deleteCategoryById)
module.exports=categoriesRoutes<file_sep>/front/src/components/LoginForm.jsx
import React, {Component} from 'react'
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
class LoginForm extends Component{
constructor(props){
super(props)
this.state={email:'',password:''}
}
handleChange=(event)=>{
this.setState({[event.target.name]:event.target.value},()=>{
})
}
handleSubmit=(event)=>{
if(this.state.email=='<EMAIL>' && this.state.password=='<PASSWORD>'){
this.setState({message:(
<div>
<h2>OK</h2>
</div>
)})
}
else{
this.setState({message:(
<div>
<h2>email or password incorrect</h2>
</div>
)})
}
}
render(){
return(
<form action="">
<TextField label="email" name="email" value={this.state.email} type="text" onChange={this.handleChange}/>
<TextField label="password" type="password" name="password" value={this.state.password} type="password" onChange={this.handleChange}/>
<Button variant="contained" color="primary" onClick={this.handleSubmit}>Login</Button>
{this.state.message}
</form>
)
}
}
export default LoginForm<file_sep>/controllers/productsController.js
'use strict'
const sequalize=require('sequelize')
const models=require('./../models')
const productsController={
getProducts:(req,res)=>{
models.Product.findAll().then(products=>{
res.json({products:products})
}).catch((err)=>{
})
},
getProductById:(req,res)=>{
models.Product.findByPk(req.params.id).then(product=>{
res.json(product)
}).catch((err)=>{
})
},
createProduct:(req,res)=>{
models.Product.create(
{
description:req.body.description,
price:req.body.price,
quantity:req.body.quantity
}
).then((productId)=>{
models.Product.findByPk(productId.id).then((product)=>{
res.json(product)
})
})
},
updateProductById:(req,res)=>{
models.Product.findByPk(req.params.id).then(product=>{
return product
}).then((product)=>{
product.description=req.body.description
product.price=req.body.price
product.quantity=req.body.quantity
product.save().then((product)=>{
res.json(product)
}).catch((err)=>{
res.json(err)
})
}).catch((err)=>{
res.json(err)
})
},
deleteProductById:(req,res)=>{
models.Product.destroy({
where:{
id:req.params.id
}
}).then((e)=>{
res.json(e)
})
}
}
module.exports=productsController<file_sep>/routes/productsRoutes.js
const express=require('express')
const productsRoutes=express.Router()
const prodructsController=require('./../controllers/productsController')
productsRoutes.get('/',prodructsController.getProducts)
productsRoutes.get('/:id',prodructsController.getProductById)
productsRoutes.post('/',prodructsController.createProduct)
productsRoutes.put('/:id',prodructsController.updateProductById)
productsRoutes.delete('/:id',prodructsController.deleteProductById)
module.exports=productsRoutes<file_sep>/front/src/components/ProductForm.jsx
import React, { Component } from 'react';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import {createProduct,getProduct,updateProduct,deleteProduct} from '../utils/api'
import { Redirect } from 'react-router'
class ProductsForm extends Component {
constructor(props){
super(props)
this.state={description:'',price:'',quantity:'',showConfirmationDelete:false,redirection: null}
}
componentDidMount(){
if(this.props.match.params.id!=null){
getProduct(this.props.match.params.id).then(res=>{
this.setState(res.data)
})
}
}
handleSubmit=(event)=>{
event.preventDefault()
}
handleChange=(event)=>{
this.setState({[event.target.name]:event.target.value})
}
handleClick=()=>{
if(this.props.match.params.id!=null){
updateProduct(this.props.match.params.id,this.state).then(res => {
this.setState({redirection: <Redirect to="/products"/>})
})
} else {
createProduct(this.state).then(res => {
this.setState({redirection: <Redirect to="/products"/>})
})
}
this.setState({description:'',price:'',quantity:''})
}
deleteProduct=()=>{
this.setState({showConfirmationDelete:true})
}
confirmDeleteProduct=()=>{
deleteProduct(this.props.match.params.id).then(res=>{
this.setState({redirection: <Redirect to="/products"/>})
})
}
render() {
let buttons
let buttonsDelete
if(this.props.match.params.id!=null){
buttons=<div>
<Button variant="contained" color="primary" onClick={this.handleClick}>
update Product
</Button>
<Button variant="contained" color="primary" onClick={this.deleteProduct}>
Delete Product
</Button>
</div>
if(this.state.showConfirmationDelete){
buttonsDelete=<Button variant="contained" color="primary" onClick={this.confirmDeleteProduct}>
DConfirm Delete Product
</Button>
}
} else {
buttons=<div>
<Button variant="contained" color="primary" onClick={this.handleClick}>
Add Product
</Button>
</div>
}
return (
<div>
{this.state.redirection}
<form action="" onSubmit={this.handleSubmit}>
<TextField id="standard-name" label="Description" name="description" value={this.state.description} onChange={this.handleChange} margin="normal" />
<TextField id="standard-name" label="Price" name="price" value={this.state.price} onChange={this.handleChange} margin="normal" />
<TextField id="standard-name" label="Quantity" name="quantity" value={this.state.quantity} onChange={this.handleChange} margin="normal" />
{/* <input type="text" value={this.state.description} name="description" onChange={this.handleChange}/> */}
{buttons}
{buttonsDelete}
</form>
</div>
);
}
}
export default ProductsForm;
<file_sep>/front/src/components/ProductRow.jsx
import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import TableCell from '@material-ui/core/TableCell';
import TableRow from '@material-ui/core/TableRow';
class ProductRow extends Component {
// constructor(props){
// super(props)
// }
render() {
return (
<TableRow>
<TableCell>{this.props.description}</TableCell>
<TableCell>$ {this.props.price}</TableCell>
<TableCell>{this.props.quantity}</TableCell>
<TableCell><a href={`/product/${this.props.idProduct}`}>Edit</a></TableCell>
</TableRow>
);
}
}
export default ProductRow;
|
7a56eb5a252172324de61e1c717533dd4f0b1c58
|
[
"JavaScript",
"Markdown"
] | 14
|
JavaScript
|
lenis96/store
|
4aa3e7779bfe20ed637c7e1d6c9f40bdd72e3a59
|
136a265ecd7752fff2af832b77f8d92ee2721ea7
|
refs/heads/master
|
<repo_name>Jamamm/music163<file_sep>/README.md
# 音乐播放器
## 后台 admin 页面预览
<file_sep>/src/js/admin/dialog.js
{
let view = {
el: '#mask',
template: `
<div id="dialog" class="dialog">
<header>
<h2>警告</h2>
<div id="close" class="close">
<svg class="icon">
<use xlink:href="#icon-close1"></use>
</svg>
</div>
</header>
<div id="content" class="content">
<div class="icon-wrapper">
<svg class="icon">
<use xlink:href="#icon-warn1"></use>
</svg>
</div>
<div class="prompt">您尚未保存,是否放弃编辑歌曲</div>
</div>
<div id="action" class="action">
<div id="confirm">确认</div>
<div id="cancel">取消</div>
</div>
</div>`,
init() {
this.$el = $(this.el)
},
render() {
$(this.el).html(this.template)
},
active() {
$(this.el).addClass('active')
},
deactive() {
$(this.el).removeClass('active')
}
}
let model = {
data: {}
}
let controller = {
init(view, model) {
this.view = view
this.model = model
this.view.init()
this.view.render()
this.bindEvents()
this.bindEventHub()
},
bindEventHub() {
window.eventHub.on('dialog', (data) => {
this.view.active()
this.model.data = data
})
},
bindEvents() {
this.view.$el.on('click', '#close', (e) => {
this.view.deactive()
})
this.view.$el.on('click', '#cancel', (e) => {
this.view.deactive()
})
this.view.$el.on('click', '#confirm', (e) => {
this.view.deactive()
window.eventHub.emit('giveUpEdit', this.model.data)
})
}
}
controller.init(view, model)
}<file_sep>/src/js/songPlay/main.js
{
let view = {
el: 'div#app',
template: `
<div id="loading" class="loading">
<div class="lds-default">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
</div>
<div id="bg" class="bg" ></div>
<div class="logo"></div>
<div class="wrapper">
<div class="rotate-wrapper">
<div id="rotate" class="rotate active">
<div id="record" class="record">
<img src="./img/disc-ip6.png" alt="record" width=296 height=296/>
</div>
<div id="recordLight" class="recordLight">
<img src="./img/disc_light-ip6.png" alt="recordLight" width=296 height=296/>
</div>
<div id="cover" class="cover">
<img src="#" alt="cover" width=186 height=186 />
</div>
</div>
<div id="pause" class="pause">
<img src="./img/pause.png" alt="pause" width=56 height=56 />
</div>
</div>
<div class="play"></div>
</div>
<div id="showLyric" class="showLyric">
<h1></h1>
<div id="lyric-wrapper" class="lyric-wrapper">
<div id="lyric" class="lyric">
<p>xxxxxxxx</p>
<p class="active">yyyyyyyyy</p>
<p>zzzzzzzzz</p>
<p>rrrrrrrrr</p>
<p>ttttttttt</p>
<p>zzzzzzzzz</p>
<p>rrrrrrrrr</p>
<p>ttttttttt</p>
<p>zzzzzzzzz</p>
<p>rrrrrrrrr</p>
<p>ttttttttt</p>
<p>zzzzzzzzz</p>
<p>rrrrrrrrr</p>
<p>ttttttttt</p>
<p>zzzzzzzzz</p>
<p>rrrrrrrrr</p>
<p>ttttttttt</p>
<p>zzzzzzzzz</p>
<p>rrrrrrrrr</p>
<p>ttttttttt</p>
<p>zzzzzzzzz</p>
<p>rrrrrrrrr</p>
<p>ttttttttt</p>
<p>zzzzzzzzz</p>
<p>rrrrrrrrr</p>
<p>ttttttttt</p>
<p>zzzzzzzzz</p>
<p>rrrrrrrrr</p>
<p>ttttttttt</p>
</div>
</div>
</div>
<div id="action" class="action">
<div><a href="#">打开</a></div>
<div><a href="#">下载</a></div>
</div>`,
init() {
this.$el = $(this.el)
},
render(data) {
this.$el.html(this.template)
},
update(data) {
console.log(data)
this.$el.find('div#bg').css({'background-image': `url(${data.cover})`})
this.$el.find('div#cover > img').attr('src', data.cover).on('load', () => {
window.eventHub.emit('imgSuccess', true)
})
this.$el.find('div#showLyric>h1').text(`${data.name} - ${data.singer}`)
},
createAudio(data) {
let audio = document.createElement('audio')
audio.src = data.url
this.$el.append(audio)
this.$el.find('audio')[0].addEventListener('canplaythrough', () => {
window.eventHub.emit('canPlay', true)
})
},
changeStatus(currentStatus) {
if(currentStatus === 'pause'){ // 暂停
this.$el.find('#pause').addClass('active') // 暂停
this.$el.find('#rotate').addClass('active') // 暂停
}else if(currentStatus === 'play'){ // 播放
this.$el.find('#pause').removeClass('active') // 播放
this.$el.find('#rotate').removeClass('active') // 播放
}
},
loadingDeactive() {
this.$el.find('div#loading').addClass('active')
},
active(data) {},
deactive(data) {}
}
let model = {
data: {
id: '',
name: '',
singer: '',
url: '',
cover: '',
lyric: ''
},
init() {
},
create() {
},
update() {
let query = new AV.Query('Song')
return query.get(this.data.id).then(song => Object.assign(this.data, {...song.attributes}))
}
}
let controller = {
currentStatus: 'pause',
init(view, model){
this.view = view
this.model = model
this.view.init()
this.model.init()
this.view.render(this.model.data)
this.getId()
this.update()
this.bindEventHub()
},
update() {
this.model.update().then(() => {
this.view.update(this.model.data)
})
},
play() {
this.view.$el.find('audio')[0].play()
},
pause() {
this.view.$el.find('audio')[0].pause()
},
getId() {
let searchStr = window.location.search
startPos = searchStr.indexOf('?')
if(startPos !== -1){
searchStr = searchStr.slice(startPos+1)
}
let searchArr = searchStr.split('&').filter(it => it) // filter 过滤空字符串
searchArr.some((item) => {
if(item.split('=')[0] === 'id'){
this.model.data.id = item.split('=')[1]
return true
}
})
},
changeStatus() {
if(this.currentStatus === 'play'){
this.currentStatus = 'pause'
this.pause()
}else if(this.currentStatus === 'pause'){
this.currentStatus = 'play'
this.play()
}
},
bindEvents() {
this.view.$el.on('click', () => {
this.changeStatus()
this.view.changeStatus(this.currentStatus)
})
},
bindEventHub() {
window.eventHub.on('imgSuccess', () => {
this.view.loadingDeactive()
this.view.createAudio(this.model.data)
window.eventHub.on('canPlay', () => {
this.changeStatus()
this.view.changeStatus(this.currentStatus)
this.bindEvents()
})
})
}
}
controller.init(view, model)
}<file_sep>/src/js/home/topNav.js
{
let view = {
el: '#topNav',
template: `
<ul>
<li data-page="recommendedMusic" class="active">推荐音乐</li>
<li data-page="hotSongList">热歌榜</li>
<li data-page="search">搜索</li>
</ul>`,
init() {
this.$el = $(this.el)
},
render(data = {}) {
$(this.el).html(this.template)
},
active(li) {
$(li).addClass('active').siblings('.active').removeClass('active')
},
deactive() {
}
}
let model = {
data: {},
init() {},
create() {},
update() {}
}
let controller = {
init(view, model){
this.view = view
this.model = model
this.view.init()
this.model.init()
this.view.render(this.model.data)
this.bindEvents()
this.bindEventHub()
},
bindEvents() {
this.view.$el.on('click', 'li', (e) => {
this.view.active(e.currentTarget)
window.eventHub.emit('changePage', $(e.currentTarget).attr('data-page'))
})
},
bindEventHub() {
}
}
controller.init(view, model)
}<file_sep>/src/js/admin/songList.js
{
let view = {
el: '#songList',
template: ``,
init() {
this.$el = $(this.el)
},
render(data) {
$(this.el).html(this.template)
let {songs} = data
songs.map(song => $(this.el).append($(`<li data-song-id=${song.id}>${song.name}-${song.singer}</li>`)))
},
create(data) {
$(this.el).append($(`<li data-song-id=${data.id}>${data.name}-${data.singer}</li>`))
},
updata(data) {
$(this.el).find('.active').text(`${data.name}-${data.singer}`)
},
active(li) {
$(li).addClass('active').siblings('.active').removeClass('active')
},
deactive() {
$(this.el).find('.active').removeClass('active')
}
}
let model = {
data: {
songs: [], // [{},{},{},{}]
},
init() {
let query = new AV.Query('Song');
return query.find().then((songs) => {
this.data.songs = songs.map(song => {
return {id: song.id, ...song.attributes}
})
})
},
create(data) {
this.data.songs.push(data)
},
update(data) {
this.data.songs.map((song, index, thisArr) => {
if (song.id === data.id) {
Object.assign(thisArr[index], { ...data })
}
})
},
}
let controller = {
init(view, model) {
this.view = view
this.model = model
this.view.init()
this.bindEvents()
this.bindEventHub()
this.getAllSongs()
},
getAllSongs() {
this.model.init().then(() => this.view.render(this.model.data))
},
bindEvents() {
this.view.$el.on('click', 'li', (e) => {
this.view.active(e.currentTarget)
let editSongId = $(e.currentTarget).attr('data-song-id')
let data = {}
this.model.data.songs.some((song) => {
if(song.id === editSongId){
data = song
return true
}
})
window.eventHub.emit('editSong', data)
})
},
bindEventHub() {
window.eventHub.on('newSong', data => this.view.deactive())
window.eventHub.on('createSong', (newSong) => {
// 此处存在两种选择,songs 是从数据库中去,还是直接添加
// 数据库取 ==> init 即可,之后重新渲染
// push + update 局部更新 ==> 疑问:更改信息时是否有问题
this.model.create(newSong)
this.view.create(newSong)
})
window.eventHub.on('updateSong', (editSong) => {
this.model.update(editSong)
this.view.updata(editSong)
})
}
}
controller.init(view, model)
}<file_sep>/src/js/admin/uploadAndEdit.js
{
let view = {
el: '#uploadAndEdit',
template: `
<div id="upload-outer" class="upload-outer">
<div id="uploadArea" class="uploadArea">
<p>拖曳音乐到此区域上传</p>
<p>文件大小不能超过 40MB</p>
</div>
<div id="upload" class="upload">
<span>选择音乐</span>
</div>
</div>
<div id="editSong" class="editSong">
<header>
<h2>编辑歌曲</h2>
<svg class="icon" aria-hidden="true">
<use xlink: href="#icon-edit01"></use>
</svg>
</header>
<form>
<div class="row">
<label>歌名:
<input name="name" type="text" value="{{name}}" />
</label>
</div>
<div class="row">
<label>歌手:
<input name="singer" type="text" value="{{singer}}" />
</label>
</div>
<div class="row">
<label>外链:
<input name="url" type="text" value="{{url}}" />
</label>
</div>
<div class="row">
<label>封面:
<input name="cover" type="text" value="{{cover}}" />
</label>
</div>
<div class="row">
<label class="lyric">歌词:
<textarea name="lyric" rows="4" type="text">{{lyric}}</textarea>
</label>
</div>
<div class="row">
<button id="submit" type="submit" class="submit">保存</button>
</div>
</form>
</div>`,
init() {
this.$el = $(this.el)
},
render(data = {}) { // data = {} 保证了render() 参数为空时 保底
let needs = 'name singer url cover lyric'.split(' ')
let html = this.template
needs.map(string => html = html.replace(`{{${string}}}`, data[string] || ''))
$(this.el).html(html)
},
update(data) {
let needs = 'name singer url cover lyric'.split(' ')
needs.map(string => $(this.el).find(`[name=${string}]`).val(data[string] || ''))
},
uploadActive() {
$(this.el).find('#upload-outer').removeClass('deactive')
$(this.el).find('#editSong').removeClass('active')
},
loadingActive() {
$(this.el).find('#uploadArea').addClass('active')
$(this.el).find('#upload').addClass('active')
},
editActive() {
$(this.el).find('#upload').removeClass('active')
$(this.el).find('#uploadArea').removeClass('active')
$(this.el).find('#upload-outer').addClass('deactive')
$(this.el).find('#editSong').addClass('active')
},
}
let model = {
data: {},
init() {
this.data = {
id: '',
name: '',
singer: '',
url: '',
cover: '',
lyric: ''
}
},
create(data) {
let Song = AV.Object.extend('Song')
let song = new Song()
song.set('name', data.name)
song.set('singer', data.singer)
song.set('url', data.url)
song.set('cover', data.cover)
song.set('lyric', data.lyric)
return song.save().then((newSong) => {
// 更新 this.data 方案一
// let {attributes:{name, singer, url}, id} = newSong
// Object.assign(this.data, {id, name, url, singer})
// 更新 this.data 方案二
let { id, attributes } = newSong
Object.assign(this.data, { id, ...attributes })
})
},
update(data) {
let song = AV.Object.createWithoutData('Song', this.data.id)
song.set('name', data.name)
song.set('url', data.url)
song.set('singer', data.singer)
song.set('cover', data.cover)
song.set('lyric', data.lyric)
return song.save().then((updateSong) => {
let { id, attributes } = updateSong
Object.assign(this.data, { id, ...attributes })
})
}
}
let controller = {
init(view, model) {
this.view = view
this.model = model
this.view.init()
this.model.init()
this.view.render(this.model.data)
this.initQiniu()
this.bindEventHub()
this.bindEvents()
},
bindEvents() {
this.view.$el.on('click', '#submit', (e) => {
e.preventDefault()
let needs = 'name singer url cover lyric'.split(' ')
let data = {}
needs.map(string => data[string] = this.view.$el.find(`[name=${string}]`).val())
if (this.model.data.id) {
this.model.update(data).then(() => {
this.view.update(this.model.data)
window.eventHub.emit('updateSong', JSON.parse(JSON.stringify(this.model.data)))
})
} else {
this.model.create(data).then(() => {
window.eventHub.emit('createSong', JSON.parse(JSON.stringify(this.model.data)))
this.model.init()
this.view.update(this.model.data)
this.view.uploadActive()
})
}
})
},
bindEventHub() {
window.eventHub.on('giveUpEdit', (data) => {
this.view.uploadActive()
})
window.eventHub.on('newSong', (data) => {
this.model.init()
this.view.update(this.model.data)
this.view.uploadActive()
})
window.eventHub.on('editSong', (data) => {
this.view.editActive()
this.model.data = data
this.view.update(this.model.data)
this.monitorUserInput()
})
},
monitorUserInput() {
this.view.$el.on('input', '[type=text]', (e) => {
let userInput = {}
this.view.$el.find('[type=text]').each((index, item) => {
userInput[$(item).attr('name')] = $(item).val()
})
let needs = 'name singer url cover lyric'.split(' ')
needs.every((it) => userInput[it] === this.model.data[it]) ?
window.eventHub.emit('changeSong', {}) :
window.eventHub.emit('changeSong', JSON.parse(JSON.stringify(this.model.data)))
})
},
initQiniu() {
//引入Plupload 、qiniu.js后
let uploader = Qiniu.uploader({
runtimes: 'html5', //上传模式,依次退化
browse_button: this.view.$el.find('#upload')[0], //上传选择的点选按钮,**必需**
uptoken_url: 'http://127.0.0.1:8888/uptoken', //Ajax请求upToken的Url,**强烈建议设置**(服务端提供)
domain: 'p46s4losm.bkt.clouddn.com', //bucket 域名,下载资源时用到,**必需**
get_new_uptoken: false, //设置上传文件的时候是否每次都重新获取新的token
max_file_size: '20mb', //最大文件体积限制
dragdrop: true, //开启可拖曳上传
drop_element: this.view.$el.find('#uploadArea')[0], //拖曳上传区域元素的ID,拖曳文件或文件夹后可触发上传
auto_start: true, //选择文件后自动上传,若关闭需要自己绑定事件触发上传
init: {
'FilesAdded': (up, files) => {
plupload.each(files, function (file) {
// 文件添加进队列后,处理相关的事情
});
},
'BeforeUpload': (up, file) => {
// 每个文件上传前,处理相关的事情
},
'UploadProgress': (up, file) => {
this.view.loadingActive()
window.eventHub.emit('loading', this.model.data)
// 每个文件上传时,处理相关的事情
},
'FileUploaded': (up, file, info) => {
this.view.editActive()
window.eventHub.emit('loaded', this.model.data)
// domain 是 bucket(篮子) 域名
let domain = up.getOption('domain')
// info.response 服务端返回的json,res 解析后的响应对象
let res = JSON.parse(info.response)
// sourceLink 上传成功后的文件的Url
let sourceLink = 'http://' + domain + '/' + encodeURIComponent(res.key)
this.model.data = {
name: res.key,
url: sourceLink
}
this.view.update(this.model.data)
window.eventHub.emit('upload', JSON.parse(JSON.stringify(this.model.data)))
// 每个文件上传成功后,处理相关的事情
// 其中 info.response 是文件上传成功后,服务端返回的json,形式如
// {
// "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
// "key": "<KEY>"
// }
},
'Error': (up, err, errTip) => {
//上传出错时,处理相关的事情
},
'UploadComplete': () => {
//队列文件处理完毕后,处理相关的事情
},
}
});
}
}
controller.init(view, model)
}<file_sep>/src/README.md
## 概述
#### 需求分析
###### 用例图

###### 系统框架图

#### 七牛依赖
```
moxie.js + plupload.js + qiniu.js
```
#### 使用本地 server.js 生成 uptoken
官方代码
```
var accessKey = 'your access key'
var secretKey = 'your secret key'
var mac = new qiniu.auth.digest.Mac(accessKey, secretKey)
var options = {
scope: bucket,
};
var putPolicy = new qiniu.rs.PutPolicy(options);
var uploadToken=putPolicy.uploadToken(mac);
```
其中:
- ` scope ` ==> 本项目七牛篮子的名称
- ` uploadToken ` ==> uptoken 值
**注意:**不要将 accessKey + secretKey 上传到 github,使用读取文件获取 AK + SK
```
// uptokenConfig.json 是保存 AK + SK 的文件
let content = JSON.parse(fs.readFileSync('./uptokenConfig.json'))
let {accessKey, secretKey} = content
```
###### 使用说明
如要生成 uptoken 需要打开 server,执行命令 ` node server.js ` 即可
## admin 页面
#### CSS
歌曲 ==> li ==> active
上传区 ==> uploadArea ==> active ==> 正在上传歌曲
上传区 ==> upload ==> active ==> 正在上传歌曲
上传区 ==> uploadArea ==> deactive ==> 歌曲上传成功,编辑歌曲
选择音乐 ==> upload ==> active ==> 正在上传歌曲
正在上传歌曲 ==> uploading ==> active ==> 正在上传歌曲(正常情况是隐藏)
编辑歌曲 ==> editSong ==> active ==> 歌曲上传成功,编辑歌曲
#### JS
歌曲列表(音乐库) ==> songList.js ==> ul
新建歌曲 ==> newSong.js ==> newSong
上传歌曲 + 编辑歌曲 ==> uploadArea + editSong(uploadAndEdit.js) ==> main
###### MVC
###### songList.js
```
{
let view = {
el: '',
template: ``,
init() {}, // 初始化
render() {}, // 初始 render
create() {}, // 创建一条新的数据 li
update() {}, // 局部更新视图
active() {}, // 激活,添加 active 类
deactive() {}, // 移除激活,移除 active 类
}
let model = {
data: {},
init() {}, // 初始化
create() {}, // 创建歌曲后更新 data
update() {}, // 编辑歌曲信息后更新 data
}
let controller = {
init() {}, // 初始化 + view 初始化 + 调用绑定事件
getAllSongs() {}, // 获取所有歌曲,this.model.init + this.view.render
bindEvents() {}, // 歌曲项 click 事件,active + 获取歌曲项的所有信息 + 发布 editSong eventHub
bindEventHub() {
// 订阅 newSong eventHub,view ==> deactive
// 订阅 createSong eventHub,model + view ==> create()
// 订阅 update eventHub,model + view ==> update()
}
}
}
```
###### newSong.js
```
{
let view = {
el: '',
template: ``,
init() {}, // 初始化
render() {}, // 初始 render
}
let model = {
data: {},
init() {}, // 初始化 data(置空)
}
let controller = {
init() {}, // 初始化 + view 初始化 + view render + 调用绑定事件
bindEvents() {}, // 监听 click 事件,有歌名发布 dialog[eventHub] + 无歌名 newSong[eventHub]
bindEventHub() {
// 订阅 changeSong eventHub ==> 更新 this.model.data
// 订阅 upload eventHub ==> 更新 this.model.data
// 订阅 updateSong eventHub ==> init data(置空)
// 订阅 createSong eventHub ==> init data(置空)
},
}
}
```
###### uploadAndEdit.js
```
{
let view = {
el: '',
template: ``,
init() {}, // 初始化
render() {}, // 初始 render
update() {}, // 局部更新视图
uploadActive() {}, // status === upload
loadingActive() {}, // status === loading
editActive() {}, // status === edit
}
let model = {
data: {},
init() {}, // 初始化 data(置空)
create() {}, // 创建数据 + 保存到数据库 + 更新data
update() {}, // 更新数据 + 保存到数据库 + 更新data
}
let controller = {
init() {}, // 初始化 + view 初始化 + view render + model init + 调用绑定事件
bindEvents() {}, // 监听 submit 事件 + 获取用户输入 ==> 根据 ID 判断 ==> model >> update(view update + 发布 updateSong[eventHub]) | create(发布 createSong[eventHub] + model init + view update + view uploadActive)
bindEventHub() {
// 订阅 giveUpEdit[eventHub] ==> view uploadActive
// 订阅 newSong[eventHub] ==> model init + view update + view uploadActive
// 订阅 editSong[eventHub] ==> view editActive + 更新 model.data + 调用 monitorUserInput 事件(监听用户输入事件)
},
initQiniu() {
// 每个文件上传时 ==> view loadingActive
// 每个文件上传成功后 ==> view editActive + 获取歌名 + 外链(url) + view update + 发布 upload[eventHub]
},
monitorUserInput(){}, // 监听用户输入事件 ==> 拿到用户输入 ==> 与 model.data 对比 ==> 发布 changeSong[eventHub] ==> 一致(参数 >> {}) + 不一致(参数 >> model.data)
}
}
```
###### dialog.js
```
{
let view = {
el: '',
template: ``,
init() {}, // 初始化
render() {}, // 初始 render
active() {}, // 激活,添加 active 类
deactive() {}, // 移除激活,移除 active 类
}
let model = {
data: {},
}
let controller = {
init() {}, // 初始化 + view init + view render + 调用绑定事件
bindEvents() {
// click close ==> view deactive
// click cancel ==> view deactive
// click confirm ==> view deactive + 发布 giveUpEdit[eventHub]
},
bindEventHub() {}, // 订阅 dialog[eventHub] ==> view active + 更新 render
}
}
```
#### 套路
```
{
let view = {
el: '',
template: ``,
init() { // 初始化
},
render(data = {}) { // 初始 render
},
create(data) { // 创建新的项
console.log(data)
},
update(data) { // 局部更新视图
},
<!-- 切换状态函数 -->
active() { // 激活,添加 active 类
},
deactive() { // 移除激活,移除 active 类
},
}
let model = {
data: {},
init() { // 初始化
},
create(data) { // 创建数据 ==> 更新 data
console.log(data)
},
update(data) { // 编辑数据 ==> 更新 data
console.log(data)
},
}
let controller = {
init(view, model) {
this.view = view
this.model = model
this.view.init()
this.model.init()
this.view.render(this.model.data)
this.bindEvents()
this.bindEventhub()
},
bindEvents(){
},
bindEventHub() {
window.eventHub.on('', (data) => {
console.log(data)
})
},
}
controller.init(view, model)
}
```
#### 增
1. 保存到七牛 ==> 问题1: 同名覆盖(最新为主)?
#### 删
#### 改
#### 查
## 相关知识点
1. 传递对象采用深拷贝
```
JSON.parse(JSON.stringfy(obj))
===
Object.assign({}, {...obj})
```
2. 更新 model.data
- ` this.model.update() `
- ` Object.assign(this.model.data, {...data}) `
- ` this.model.data = data `
3. 拿到数据 data 后
1. 更新 ` model.data `
2. ` view ` 相关操作 ==> ` this.view.render(this.model.data) + this.view.create(this.model.data) + this.view.update(this.model.date) `
4. forEach 不能跳出循环,可以使用 ` some() ` + `return true` | every() ` + ` return false ` 跳出循环
5. ` ... + Object.assign ` 一起使用需要 ` Object.assign(obj1, {...obj2}) `
<file_sep>/src/js/admin/newSong.js
{
let view = {
el: '#newSong',
template: `新建歌曲`,
init() {
this.$el = $(this.el)
},
render(data) {
$(this.el).html(this.template)
}
}
let model = {
data: {},
init() {
this.data = {
id: '',
name: '',
singer: '',
url: '',
cover: '',
lyric: ''
}
},
}
let controller = {
init(view, model) {
this.view = view
this.model = model
this.view.init()
this.view.render(this.model.data)
this.bindEvents()
this.bindEventHub()
},
bindEvents() {
this.view.$el.on('click', () => {
this.model.data.name ?
window.eventHub.emit('dialog', JSON.parse(JSON.stringify(this.model.data))) :
window.eventHub.emit('newSong', JSON.parse(JSON.stringify(this.model.data)))
})
},
bindEventHub() {
window.eventHub.on('changeSong', (data) => {
this.model.data = data
// this.model.init()
})
window.eventHub.on('upload', (data) => {
this.model.data = data
// this.model.init()
})
window.eventHub.on('updateSong', () => {
this.model.init()
})
window.eventHub.on('createSong', () => {
this.model.init()
})
}
}
controller.init(view, model)
}<file_sep>/src/js/home/newSong.js
{
let view = {
el: 'div.newSong',
template:`
<h2>最新音乐</h2>
<ul class="songList">
</ul >`,
init() {
this.$el = $(this.el)
},
render(data = {}) {
$(this.el).html(this.template)
let {songs} = data
songs.map((song) => {
$(this.el).find('ul.songList').append($(`
<li>
<a href=./songPlay.html?id=${song.id}>
<div class="song">
<h3 data-song-id=${ song.id } class="songName">${ song.name }</h3>
<span class="songDescription">
<div class="icon-wrapper">
<svg class="icon">
<use xlink: href="#icon-sq1"></use>
</svg>
</div>
<div data-song-url=${ song.url } class="descriptionText">${ song.singer }</div>
</span>
</div>
<div class="play">
<svg class="icon">
<use xlink: href="#icon-bofang1"></use>
</svg>
</div>
</a>
</li>`))
})
},
active(data) {
},
deactive(data) {
}
}
let model = {
data: {
songs: [ ],
},
init() {
var query = new AV.Query('Song')
return query.find().then((songs) => {
this.data.songs = songs.map(song => {
return {id: song.id, ...song.attributes}
})
})
},
create() {
},
update() {}
}
let controller = {
init(view, model){
this.view = view
this.model = model
this.view.init()
this.model.init().then(() => {
this.view.render(this.model.data)
})
this.bindEvents()
this.bindEventHub()
},
bindEvents() {},
bindEventHub() {}
}
controller.init(view, model)
}
|
07181ca3a3eb1205c65dad40d17d225c6e46a5fe
|
[
"Markdown",
"JavaScript"
] | 9
|
Markdown
|
Jamamm/music163
|
2ec9d65044dea0f3e22a9deda6460ebc180e0a24
|
b49d8ec829de46de96217a2a9345d1046e384a36
|
refs/heads/master
|
<file_sep>TOPDIR = ..
include $(TOPDIR)/defs.mk
CATEGORY = common
include $(TOPDIR)/rules.mk
<file_sep>/*
* <:copyright-BRCM:2016-2020:Apache:standard
*
* Copyright (c) 2016-2020 Broadcom. All Rights Reserved
*
* The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* :>
*
*****************************************************************************/
/*
* netconf_modules_init.h
*
* Created on: 17 Jun 2016
* Author: igort
*/
#ifndef NETCONF_MODULES_INIT_H_
#define NETCONF_MODULES_INIT_H_
#include <bcmos_system.h>
#include <libyang/libyang.h>
#include <sysrepo.h>
// !!! temporary
#define SR_DATA_SEARCH_DIR "sysrepo/data"
#define SR_MODELS_SEARCH_DIR "sysrepo/yang"
/** Startup uptions */
typedef struct nc_startup_options
{
uint8_t olt;
bcmos_bool restore_running; /**< Restore last "running" configuration on startup */
bcmos_bool reset_cfg; /**< Reset configuration on startup */
bcmos_bool tr451_onu_management; /**< Use TR-451 ONU management */
bcmos_bool dummy_tr385_management; /**< Enable dummy TR-385 management */
} nc_startup_options;
bcmos_errno bcm_netconf_modules_init(sr_session_ctx_t *srs, struct ly_ctx *ly_ctx, const nc_startup_options *startup_options);
void bcm_netconf_modules_exit(sr_session_ctx_t *srs, struct ly_ctx *ly_ctx);
sr_session_ctx_t *bcm_netconf_session_get(void);
/** Get startup options list
* \returns startup options
*/
const nc_startup_options *netconf_agent_startup_options_get(void);
uint8_t netconf_agent_olt_id(void);
/* TR-451 support */
bcmos_bool bcm_tr451_onu_management_is_enabled(void);
#endif /* NETCONF_MODULES_INIT_H_ */
<file_sep># By default, disable CMCC vOMCI ONU Management
bcm_make_normal_option(TR451_VOMCI_POLT BOOL "Enable TR-451 vOMCI ONU Management" n)
if(TR451_VOMCI_POLT)
bcm_module_name(tr451_polt)
bcm_module_definitions(PUBLIC -DTR451_VOMCI)
bcm_module_dependencies(PUBLIC os dev_log cli tr451_polt_vendor)
bcm_module_dependencies(PRIVATE tr451_sbi grpc)
bcm_module_header_paths(PUBLIC .)
bcm_module_srcs(bcm_tr451_polt_common.cc bcm_tr451_polt_client.cc bcm_tr451_polt_server.cc bcm_tr451_polt_cli.cc)
bcm_create_lib_target()
bcm_release_install(${CMAKE_INSTALL_PREFIX}/fs/tr451_polt_daemon RELEASE ${BCM_HOST_IMAGES_RELEASE}/netconf_server)
bcm_release_install(${CMAKE_INSTALL_PREFIX}/fs/start_tr451_polt.sh RELEASE ${BCM_HOST_IMAGES_RELEASE}/netconf_server)
endif()
# Include subdirectories unconditionally to make sure that entire module gets included in ONU_MGMT release
bcm_add_subdirectory(message_definition)
bcm_add_subdirectory(polt_daemon)
bcm_add_subdirectory(tr451_polt_vendor)
<file_sep># Netconf modules
if(NETCONF_SERVER)
bcm_module_name(netconf_modules)
bcm_module_dependencies(PUBLIC os dev_log sysrepo libnetconf2)
if(TR451_VOMCI_POLT)
bcm_module_dependencies(PUBLIC netconf_bbf-polt-vomci)
endif()
if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/bbf-xpon OR EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/bbf-xpon-dummy)
bcm_module_dependencies(PUBLIC netconf_bbf-xpon)
endif()
if(TR385_ISSUE2)
bcm_module_definitions(PUBLIC -DTR385_ISSUE2)
endif()
if(USE_OBBAA_YANG_MODELS)
bcm_module_definitions(PUBLIC -DOB_BAA)
endif()
bcm_module_header_paths(PUBLIC .)
bcm_module_srcs(
b64.c
bcmolt_netconf_module_utils.c
bcmolt_netconf_module_init.c
bcmolt_netconf_notifications.c)
bcm_create_lib_target()
if (EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/bbf-xpon)
bcm_add_subdirectory(bbf-xpon)
else()
bcm_add_subdirectory(bbf-xpon-dummy)
endif()
if(TR451_VOMCI_POLT)
bcm_add_subdirectory(bbf-vomci)
endif()
endif()
<file_sep>/*
<:copyright-BRCM:2016-2019:Apache:standard
Copyright (c) 2016-2019 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
* :>
*/
#ifndef BCMOS_TYPES_H_
#define BCMOS_TYPES_H_
#ifndef BCMOS_SYSTEM_H_
#error Please do not include bcmos_types.h directly. Include bcmos_system.h
#endif
#include "bcmos_pack.h"
/** \defgroup system_types Generic types
* @{
*/
/*
* Limits of integer types.
*/
/* Minimum of signed integer types. */
#ifndef INT8_MIN
#define INT8_MIN (0x80)
#endif
#ifndef INT16_MIN
#define INT16_MIN (0x8000)
#endif
#ifndef INT32_MIN
#define INT32_MIN (0x80000000)
#endif
#ifndef INT64_MIN
#define INT64_MIN (0x8000000000000000)
#endif
/* Maximum of signed integer types. */
#ifndef INT8_MAX
#define INT8_MAX (0x7F)
#endif
#ifndef INT16_MAX
#define INT16_MAX (0x7FFF)
#endif
#ifndef INT32_MAX
#define INT32_MAX (0x7FFFFFFF)
#endif
#ifndef INT64_MAX
#define INT64_MAX (0x7FFFFFFFFFFFFFFF)
#endif
/* Maximum of unsigned integer types. */
#ifndef UINT8_MAX
#define UINT8_MAX (0xFF)
#endif
#ifndef UINT16_MAX
#define UINT16_MAX (0xFFFF)
#endif
#ifndef UINT32_MAX
#define UINT32_MAX (0xFFFFFFFF)
#endif
#ifndef UINT64_MAX
#define UINT64_MAX (0xFFFFFFFFFFFFFFFF)
#endif
/** Endianness */
#define BCMOS_ENDIAN_BIG 0
#define BCMOS_ENDIAN_LITTLE 1
typedef enum
{
BCMOS_ENDIAN_BIG_E = BCMOS_ENDIAN_BIG,
BCMOS_ENDIAN_LITTLE_E = BCMOS_ENDIAN_LITTLE,
} bcmos_endian;
/* If endianness is not set explicitly, try to autodetect it.
* Modern gcc versions (over 4.8) define __BYTE_ORDER__
* see "gcc -E -dM - < /dev/null | grep ENDIAN"
*/
#ifndef BCM_CPU_ENDIAN
#ifdef __BYTE_ORDER__
#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
#define BCM_CPU_ENDIAN BCMOS_ENDIAN_LITTLE
#else
#define BCM_CPU_ENDIAN BCMOS_ENDIAN_BIG
#endif
#else
/* We are dealing with compiler that doesn't set __BYTE_ORDER__.
* If it is simulation build than it must be LE x86.
* Otherwise, no way to tell.
*/
#ifdef SIMULATION_BUILD
#define BCM_CPU_ENDIAN BCMOS_ENDIAN_LITTLE
#endif
#endif /* #ifdef __BYTE_ORDER */
#endif /* #ifndef BCM_CPU_ENDIAN */
#include <bcm_config.h>
/** 24-bit unsigned integer */
typedef union
{
uint8_t u8[3];
struct __PACKED_ATTR_START__
{
#if (BCM_CPU_ENDIAN == BCMOS_ENDIAN_BIG)
uint8_t hi;
uint8_t mid;
uint8_t low;
#elif (BCM_CPU_ENDIAN == BCMOS_ENDIAN_LITTLE)
uint8_t low;
uint8_t mid;
uint8_t hi;
#else
#error BCM_CPU_ENDIAN must be BCMOS_ENDIAN_BIG or _LITTLE
#endif
} __PACKED_ATTR_END__ low_hi;
} uint24_t;
static inline uint32_t uint24_to_32(uint24_t u24)
{
return (u24.low_hi.hi << 16) | (u24.low_hi.mid << 8) | u24.low_hi.low;
}
static inline uint24_t uint32_to_24(uint32_t u32)
{
uint24_t u24;
u24.low_hi.hi = (u32 >> 16) & 0xff;
u24.low_hi.mid = (u32 >> 8) & 0xff;
u24.low_hi.low = u32 & 0xff;
return u24;
}
/** VLAN tag (CoS/CFI/VID) */
typedef uint16_t bcmos_vlan_tag;
#define BCMOS_ETH_ALEN 6
/** MAC address */
typedef struct
{
uint8_t u8[BCMOS_ETH_ALEN];
} bcmos_mac_address;
/** IPv4 address. It is stored in network byte order. */
typedef union
{
uint32_t u32;
uint8_t u8[4];
} bcmos_ipv4_address;
/** IPv6 address */
typedef struct
{
uint8_t u8[16];
} bcmos_ipv6_address;
typedef enum
{
BCMOS_IP_VERSION_UNKNOWN = 0,
BCMOS_IP_VERSION_4 = 4,
BCMOS_IP_VERSION_6 = 6
} bcmos_ip_version;
typedef struct
{
bcmos_ip_version version;
union
{
bcmos_ipv4_address ipv4;
bcmos_ipv6_address ipv6;
};
} bcmos_ip_address;
static inline void bcmos_mac_address_init(bcmos_mac_address *mac)
{
memset(mac, 0, sizeof(*mac));
}
static inline void bcmos_ipv4_address_init(bcmos_ipv4_address *ip)
{
memset(ip, 0, sizeof(*ip));
}
static inline void bcmos_ipv6_address_init(bcmos_ipv6_address *ip)
{
memset(ip, 0, sizeof(*ip));
}
/* Convert IPv4/IPv6 address from internal presentation to string */
bcmos_errno bcmos_ip_to_str(const bcmos_ip_address *ip, char *ip_str, int32_t ip_str_size);
/* Convert IPv4/IPv6 address from string to internal presentation */
bcmos_errno bcmos_str_to_ip(const char *ip_str, bcmos_ip_address *ip);
char *bcmos_inet_ntoa(bcmos_ipv4_address *ip, char *ip_str);
#ifndef container_of
#define container_of(ptr, type, member) ({ \
const typeof( ((type *)0)->member ) *__mptr = (ptr); \
(type *)( (long)__mptr - offsetof(type,member) );})
#endif
/** @} */
#endif /* BCMOS_TYPES_H_ */
<file_sep># CMake module for defining compile of either Host or Embedded for simulation envirionment.
# Simulation is anything built to run on a Linux host and uses the native gcc compiler.
#====
# Bring in the common GCC settings
#====
include(gcc)
#====
# Compile definitions specific to building a simulation target
#====
set(SIMULATION_BUILD y)
add_definitions(-DSIMULATION_BUILD)
#====
# Add the compile and link flags we use for simulation
#====
set(BCM_CFLAGS ${GCC_COMMON_CFLAGS} -ggdb -O0)
set(BCM_CXXFLAGS ${GCC_COMMON_CXXFLAGS} -ggdb -O0)
set(BCM_LFLAGS ${BCM_CFLAGS})
set(BCM_EXTRA_C_WARNINGS ${BCM_EXTRA_C_WARNINGS} -Wno-switch-bool)
set(BCM_OBJCOPY objcopy)
#====
# Unset toolchain variables that might've been set by platform/board-specific target
# Set the compiler to use gcc. If not set, it would default to 'cc' which is 'gcc' anyway, so this isn't
# strictly necessary.
#====
set(CMAKE_C_COMPILER gcc)
set(CMAKE_CXX_COMPILER g++)
set(CMAKE_C_COMPILER_AR ar)
set(CMAKE_CXX_COMPILER_AR ar)
set(CMAKE_C_COMPILER_RANLIB ranlib)
set(CMAKE_CXX_COMPILER_RANLIB ranlib)
set(CMAKE_LINKER gcc)
#====
# Set the supported manifest files (a.k.a. configuration profiles)
#====
set(BCM_MANIFESTS x86)
#====
# --host setting for 3rd-party packages using automake
#====
set(BCM_CONFIG_HOST x86_64-linux)
<file_sep>/*
* <:copyright-BRCM:2016-2020:Apache:standard
*
* Copyright (c) 2016-2020 Broadcom. All Rights Reserved
*
* The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* :>
*
*****************************************************************************/
/*
* bbf-xpon.c
*/
#include <bcmos_system.h>
#include <bcmolt_netconf_module_utils.h>
#include <bcmolt_netconf_constants.h>
#include <bbf-vomci.h>
#include <bcm_tr451_polt.h>
#include <bcmolt_netconf_notifications.h>
#ifndef TR451_VOMCI
#error TR451_VOMCI support is required
#endif
#define BCM_MAX_YANG_NAME_LENGTH 32
static sr_subscription_ctx_t *sr_ctx;
static sr_subscription_ctx_t *sr_ctx_state;
static const char* bbf_polt_vomci_features[] = {
"nf-client-supported",
"nf-server-supported",
NULL
};
#define CLIENT_REMOTE_ENDPOINT_XPATH "client-parameters/nf-initiate/remote-endpoints"
/* Data store change indication callback */
static int bbf_polt_vomci_server_change_cb(sr_session_ctx_t *srs, const char *module_name,
const char *xpath, sr_event_t event, uint32_t request_id, void *private_ctx)
{
sr_change_iter_t *sr_iter = NULL;
sr_change_oper_t sr_oper;
const struct lyd_node *node;
const char *prev_val, *prev_list;
bool prev_dflt;
tr451_server_endpoint server_ep = {};
char qualified_xpath[BCM_MAX_XPATH_LENGTH];
int sr_rc;
bcmos_errno err = BCM_ERR_OK;
nc_config_lock();
NC_LOG_INFO("xpath=%s event=%d\n", xpath, event);
/* We only handle CHANGE and ABORT events.
* Since there is no way to reserve resources in advance and no way to fail the APPLY event,
* configuration is applied in VERIFY event.
* There are no other verifiers, but if there are and they fail,
* ABORT event will roll-back the changes.
*/
if (event == SR_EV_DONE)
{
nc_config_unlock();
return SR_ERR_OK;
}
snprintf(qualified_xpath, sizeof(qualified_xpath)-1, "%s//.", xpath);
qualified_xpath[sizeof(qualified_xpath)-1] = 0;
sr_rc = sr_get_changes_iter(srs, qualified_xpath, &sr_iter);
while ((err == BCM_ERR_OK) && (sr_rc == SR_ERR_OK) &&
((sr_rc = sr_get_change_tree_next(srs, sr_iter, &sr_oper,
&node, &prev_val, &prev_list, &prev_dflt)) == SR_ERR_OK))
{
const char *node_name = node->schema->name;
NC_LOG_DBG("op=%s node=%s\n", sr_op_name(sr_oper), node_name);
/* Handle attributes */
if (!strcmp(node_name, "enabled"))
{
bcm_tr451_polt_grpc_server_enable_disable(
(sr_oper != SR_OP_DELETED) &&
((const struct lyd_node_leaf_list *)node)->value.bln);
continue;
}
if (sr_oper != SR_OP_DELETED)
{
if (!strcmp(node_name, "local-port") ||
!strcmp(node_name, "local-address") ||
!strcmp(node_name, "local-endpoint-name"))
{
/* access points */
const struct lyd_node *endpoint_name_node;
const char *endpoint_name;
endpoint_name_node = nc_ly_get_sibling_or_parent_node(node, "name");
if (endpoint_name_node == NULL)
{
NC_LOG_ERR("can't find listen-endpoint node\n");
continue;
}
NC_LOG_DBG("Handling listen-endpoint[%s]\n", endpoint_name_node->schema->name);
endpoint_name = ((const struct lyd_node_leaf_list *)endpoint_name_node)->value.string;
if (server_ep.endpoint.name != NULL && strcmp(server_ep.endpoint.name, endpoint_name))
{
err = bcm_tr451_polt_grpc_server_create(&server_ep);
memset(&server_ep, 0, sizeof(server_ep));
}
server_ep.endpoint.name = endpoint_name;
if (!strcmp(node_name, "local-port"))
server_ep.endpoint.port = ((const struct lyd_node_leaf_list *)node)->value.uint16;
else if (!strcmp(node_name, "local-address"))
server_ep.endpoint.host_name = ((const struct lyd_node_leaf_list *)node)->value_str;
else if (!strcmp(node_name, "local-endpoint-name"))
server_ep.local_name = ((const struct lyd_node_leaf_list *)node)->value_str;
}
}
else
{
const struct lyd_node *endpoint_node;
const char *entity_name = ((const struct lyd_node_leaf_list *)node)->value.string;
/* Deleted */
if (!strcmp(node_name, "name"))
{
endpoint_node = nc_ly_get_sibling_or_parent_node(node, "listen-endpoint");
if (endpoint_node != NULL)
{
bcm_tr451_polt_grpc_server_delete(entity_name);
}
}
}
}
if (server_ep.endpoint.name && err == BCM_ERR_OK)
{
err = bcm_tr451_polt_grpc_server_create(&server_ep);
}
sr_free_change_iter(sr_iter);
nc_config_unlock();
return nc_bcmos_errno_to_sr_errno(err);
}
/* Data store change indication callback */
static int bbf_polt_vomci_client_change_cb(sr_session_ctx_t *srs, const char *module_name,
const char *xpath, sr_event_t event, uint32_t request_id, void *private_ctx)
{
sr_change_iter_t *sr_iter = NULL;
sr_change_oper_t sr_oper;
const struct lyd_node *node;
const char *prev_val, *prev_list;
bool prev_dflt;
tr451_client_endpoint *client_ep = NULL;
tr451_endpoint entry = {};
char qualified_xpath[BCM_MAX_XPATH_LENGTH];
int sr_rc;
bcmos_errno err = BCM_ERR_OK;
nc_config_lock();
NC_LOG_INFO("xpath=%s event=%d\n", xpath, event);
/* We only handle CHANGE and ABORT events.
* Since there is no way to reserve resources in advance and no way to fail the APPLY event,
* configuration is applied in VERIFY event.
* There are no other verifiers, but if there are and they fail,
* ABORT event will roll-back the changes.
*/
if (event == SR_EV_DONE)
{
nc_config_unlock();
return SR_ERR_OK;
}
snprintf(qualified_xpath, sizeof(qualified_xpath)-1, "%s//.", xpath);
qualified_xpath[sizeof(qualified_xpath)-1] = 0;
sr_rc = sr_get_changes_iter(srs, qualified_xpath, &sr_iter);
while ((err == BCM_ERR_OK) && (sr_rc == SR_ERR_OK) &&
((sr_rc = sr_get_change_tree_next(srs, sr_iter, &sr_oper,
&node, &prev_val, &prev_list, &prev_dflt)) == SR_ERR_OK))
{
const char *node_name = node->schema->name;
NC_LOG_DBG("op=%s node=%s\n", sr_op_name(sr_oper), node_name);
/* Handle attributes */
if (!strcmp(node_name, "enabled"))
{
bcm_tr451_polt_grpc_client_enable_disable(
(sr_oper != SR_OP_DELETED) &&
((const struct lyd_node_leaf_list *)node)->value.bln);
continue;
}
if (sr_oper != SR_OP_DELETED)
{
const struct lyd_node *endpoint_name_node;
const char *endpoint_name;
if (!strcmp(node_name, "remote-port") ||
!strcmp(node_name, "remote-address"))
{
/* access points */
const struct lyd_node *access_name_node;
const char *access_point_name;
access_name_node = nc_ly_get_sibling_or_parent_node(node, "name");
NC_LOG_DBG("access-node %s\n", access_name_node ? access_name_node->schema->name : "*undefined*");
if (access_name_node == NULL)
{
NC_LOG_ERR("can't find access-node\n");
continue;
}
endpoint_name_node = nc_ly_get_sibling_or_parent_node(access_name_node, "name");
if (endpoint_name_node == NULL)
{
NC_LOG_ERR("can't find remote-endpoint node\n");
continue;
}
NC_LOG_DBG("Handling remote-endpoint[%s]/access-points[%s]\n",
endpoint_name_node->schema->name, access_name_node->schema->name);
endpoint_name = ((const struct lyd_node_leaf_list *)endpoint_name_node)->value.string;
access_point_name = ((const struct lyd_node_leaf_list *)access_name_node)->value.string;
if (client_ep != NULL && strcmp(client_ep->name, endpoint_name))
{
err = bcm_tr451_polt_grpc_client_create(client_ep);
client_ep = NULL;
}
if (client_ep == NULL)
{
client_ep = bcm_tr451_client_endpoint_alloc(endpoint_name);
}
/* access-point name changed ? */
if (entry.name && strcmp(entry.name, access_point_name))
{
bcm_tr451_client_endpoint_add_entry(client_ep, &entry);
memset(&entry, 0, sizeof(entry));
}
entry.name = access_point_name;
if (!strcmp(node_name, "remote-port"))
entry.port = ((const struct lyd_node_leaf_list *)node)->value.uint16;
else if (!strcmp(node_name, "remote-address"))
entry.host_name = ((const struct lyd_node_leaf_list *)node)->value_str;
}
else if (!strcmp(node_name, "local-endpoint-name"))
{
endpoint_name_node = nc_ly_get_sibling_or_parent_node(node, "name");
if (endpoint_name_node == NULL)
{
NC_LOG_ERR("can't find remote-endpoint node\n");
continue;
}
NC_LOG_DBG("Handling remote-endpoint[%s]/grpc/local-endpoint-name\n",
endpoint_name_node->schema->name);
endpoint_name = ((const struct lyd_node_leaf_list *)endpoint_name_node)->value.string;
if (client_ep != NULL && strcmp(client_ep->name, endpoint_name))
{
err = bcm_tr451_polt_grpc_client_create(client_ep);
client_ep = NULL;
}
if (client_ep == NULL)
{
client_ep = bcm_tr451_client_endpoint_alloc(endpoint_name);
}
client_ep->local_name = ((const struct lyd_node_leaf_list *)node)->value_str;
}
}
else
{
const struct lyd_node *endpoint_node;
const struct lyd_node *access_node;
const char *entity_name = ((const struct lyd_node_leaf_list *)node)->value.string;
/* Deleted */
if (!strcmp(node_name, "name"))
{
access_node = nc_ly_get_sibling_or_parent_node(node, "access-points");
endpoint_node = nc_ly_get_sibling_or_parent_node(node, "remote-endpoints");
if (access_node)
{
NC_LOG_DBG("Deleting access-points [%s] is not supported. Request ignored\n",
entity_name);
}
else if (endpoint_node != NULL)
{
err = bcm_tr451_polt_grpc_client_delete(entity_name);
}
}
}
}
if (client_ep && err == BCM_ERR_OK)
{
if (entry.name)
{
bcm_tr451_client_endpoint_add_entry(client_ep, &entry);
memset(&entry, 0, sizeof(entry));
}
err = bcm_tr451_polt_grpc_client_create(client_ep);
client_ep = NULL;
}
if (client_ep != NULL)
bcm_tr451_client_endpoint_free(client_ep);
sr_free_change_iter(sr_iter);
nc_config_unlock();
return nc_bcmos_errno_to_sr_errno(err);
}
/* Data store change indication callback */
static int bbf_polt_vomci_filter_change_cb(sr_session_ctx_t *srs, const char *module_name,
const char *xpath, sr_event_t event, uint32_t request_id, void *private_ctx)
{
sr_change_iter_t *sr_iter = NULL;
sr_change_oper_t sr_oper;
const struct lyd_node *node;
const char *prev_val, *prev_list;
bool prev_dflt;
tr451_polt_filter filter = {};
const char *filter_endpoint_name = NULL;
char qualified_xpath[BCM_MAX_XPATH_LENGTH];
int sr_rc;
bcmos_errno err = BCM_ERR_OK;
nc_config_lock();
NC_LOG_INFO("xpath=%s event=%d\n", xpath, event);
/* We only handle CHANGE and ABORT events.
* Since there is no way to reserve resources in advance and no way to fail the APPLY event,
* configuration is applied in VERIFY event.
* There are no other verifiers, but if there are and they fail,
* ABORT event will roll-back the changes.
*/
if (event == SR_EV_DONE)
{
nc_config_unlock();
return SR_ERR_OK;
}
snprintf(qualified_xpath, sizeof(qualified_xpath)-1, "%s//.", xpath);
qualified_xpath[sizeof(qualified_xpath)-1] = 0;
sr_rc = sr_get_changes_iter(srs, qualified_xpath, &sr_iter);
while ((err == BCM_ERR_OK) && (sr_rc == SR_ERR_OK) &&
((sr_rc = sr_get_change_tree_next(srs, sr_iter, &sr_oper,
&node, &prev_val, &prev_list, &prev_dflt)) == SR_ERR_OK))
{
const char *node_name = node->schema->name;
NC_LOG_DBG("op=%s node=%s\n", sr_op_name(sr_oper), node_name);
/* Handle attributes */
if (sr_oper != SR_OP_DELETED)
{
if (!strcmp(node_name, "priority") || !strcmp(node_name, "resulting-endpoint") ||
!strcmp(node_name, "any-onu") || !strcmp(node_name, "onu-vendor") ||
!strcmp(node_name, "onu-serial-number"))
{
/* endpoint filter */
const struct lyd_node *filter_name_node;
const char *rule_name;
filter_name_node = nc_ly_get_sibling_or_parent_node(node, "name");
if (filter_name_node == NULL)
{
NC_LOG_ERR("can't find nf-endpoint-filter/rule\n");
continue;
}
rule_name = ((const struct lyd_node_leaf_list *)filter_name_node)->value.string;
/* Filter rule changed ? */
if (filter.name && strcmp(filter.name, rule_name))
{
if (filter_endpoint_name)
{
err = bcm_tr451_polt_filter_set(&filter, filter_endpoint_name);
}
memset(&filter, 0, sizeof(filter));
filter_endpoint_name = NULL;
}
filter.name = rule_name;
if (!strcmp(node_name, "priority"))
filter.priority = ((const struct lyd_node_leaf_list *)node)->value.uint16;
else if (!strcmp(node_name, "resulting-endpoint"))
filter_endpoint_name = ((const struct lyd_node_leaf_list *)node)->value_str;
else if (!strcmp(node_name, "any-onu"))
filter.type = TR451_FILTER_TYPE_ANY;
else if (!strcmp(node_name, "onu-vendor"))
{
filter.type = TR451_FILTER_TYPE_VENDOR_ID;
strncpy((char *)&filter.serial_number[0], ((const struct lyd_node_leaf_list *)node)->value.string, 4);
}
else if (!strcmp(node_name, "onu-serial-number"))
{
const char *serial_number = ((const struct lyd_node_leaf_list *)node)->value.string;
if (serial_number == NULL || strlen(serial_number) < 6)
{
NC_LOG_ERR("invalid onu-serial-number: NULL or too short\n");
continue;
}
strncpy((char *)&filter.serial_number[0], serial_number, 4);
/* Serial number consists of 4xASCII vendor_id + 8xHex string vendor-specific id */
if (nc_hex_to_bin(serial_number + 4, &filter.serial_number[4], 4) < 0)
{
NC_LOG_ERR("invalid onu-serial-number format: %s\n", serial_number);
continue;
}
filter.type = TR451_FILTER_TYPE_SERIAL_NUMBER;
}
}
}
}
if (filter.name)
{
err = bcm_tr451_polt_filter_set(&filter, filter_endpoint_name);
}
sr_free_change_iter(sr_iter);
nc_config_unlock();
return nc_bcmos_errno_to_sr_errno(err);
}
bcmos_errno bbf_polt_vomci_module_init(sr_session_ctx_t *srs, struct ly_ctx *ly_ctx)
{
bcmos_errno err = BCM_ERR_INTERNAL;
const struct lys_module *bbf_polt_mod;
int i;
do {
/* make sure that ietf-interfaces module is loaded */
bbf_polt_mod = ly_ctx_get_module(ly_ctx, BBF_POLT_VOMCI_MODULE_NAME, NULL, 1);
if (bbf_polt_mod == NULL)
{
bbf_polt_mod = ly_ctx_load_module(ly_ctx, BBF_POLT_VOMCI_MODULE_NAME, NULL);
if (bbf_polt_mod == NULL)
{
NC_LOG_ERR(BBF_POLT_VOMCI_MODULE_NAME ": can't find the schema in sysrepo\n");
break;
}
}
/* Enable all relevant features are enabled in sysrepo */
for (i = 0; bbf_polt_vomci_features[i]; i++)
{
if (lys_features_enable(bbf_polt_mod, bbf_polt_vomci_features[i]))
{
NC_LOG_ERR("%s: can't enable feature %s\n", BBF_POLT_VOMCI_MODULE_NAME, bbf_polt_vomci_features[i]);
break;
}
}
if (bbf_polt_vomci_features[i])
break;
err = BCM_ERR_OK;
} while (0);
return err;
}
static char *_get_date_time_string(char *buf, uint32_t buf_size)
{
time_t t = time(NULL);
struct tm tm = *localtime(&t);
snprintf(buf, buf_size,
"%.4d-%.2d-%.2dT%.2d:%.2d:%.2dZ",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
return buf;
}
/* Server endpoint connect/disconnect notification */
static void _server_connect_disconnect_cb(void *data, const char *server_name,
const char *client_name, bcmos_bool is_connected)
{
sr_session_ctx_t *session = (sr_session_ctx_t *)data;
const struct ly_ctx *ctx = sr_get_context(sr_session_get_connection(session));
struct lyd_node *notif = NULL;
char notif_xpath[200];
char node_xpath[256];
char date_time_string[64];
int sr_rc;
do
{
snprintf(notif_xpath, sizeof(notif_xpath)-1,
"%s[name='%s']/remote-endpoints/remote-endpoint-status-change",
BBF_POLT_VOMCI_SERVER_LISTEN_ENDPOINTS_PATH, server_name);
notif = lyd_new_path(NULL, ctx, notif_xpath, NULL, 0, 0);
if (notif == NULL)
{
NC_LOG_ERR("Failed to create notification %s.\n", notif_xpath);
break;
}
snprintf(node_xpath, sizeof(node_xpath)-1, "%s/remote-endpoint", notif_xpath);
if (lyd_new_path(notif, NULL, node_xpath, (void *)(long)client_name, 0, 0) == NULL)
{
NC_LOG_ERR("Failed to add 'remote-endpoint' node to notification %s.\n", notif_xpath);
break;
}
snprintf(node_xpath, sizeof(node_xpath)-1, "%s/connected", notif_xpath);
if (lyd_new_path(notif, NULL, node_xpath, is_connected ? "true" : "false", 0, 0) == NULL)
{
NC_LOG_ERR("Failed to add 'connected' node to notification %s.\n", notif_xpath);
break;
}
snprintf(node_xpath, sizeof(node_xpath)-1, "%s/remote-endpoint-state-last-change", notif_xpath);
if (lyd_new_path(notif, NULL, node_xpath,
_get_date_time_string(date_time_string, sizeof(date_time_string)), 0, 0) == NULL)
{
NC_LOG_ERR("Failed to add 'remote-endpoint-state-last-change' node to notification %s.\n", notif_xpath);
break;
}
sr_rc = sr_event_notif_send_tree(session, notif);
if (sr_rc != SR_ERR_OK)
{
NC_LOG_ERR("Failed to sent %s notification. Error '%s'\n",
notif_xpath, sr_strerror(sr_rc));
break;
}
NC_LOG_DBG("Sent %s notification: remote_endpoint %s: %sconnected\n",
notif_xpath, client_name, is_connected ? "" : "dis");
} while (0);
if (notif != NULL)
lyd_free_withsiblings(notif);
}
/* Client endpoint connected/disconnected notification */
static void _client_connect_disconnect_cb(void *data, const char *remote_endpoint_name,
const char *access_point_name, bcmos_bool is_connected)
{
sr_session_ctx_t *session = (sr_session_ctx_t *)data;
const struct ly_ctx *ctx = sr_get_context(sr_session_get_connection(session));
struct lyd_node *notif = NULL;
char notif_xpath[200];
char node_xpath[256];
char date_time_string[64];
int sr_rc;
do
{
snprintf(notif_xpath, sizeof(notif_xpath)-1,
"%s/remote-endpoint[name='%s']/remote-endpoint-status-change",
BBF_POLT_VOMCI_CLIENT_REMOTE_ENDPOINTS_PATH, remote_endpoint_name);
notif = lyd_new_path(NULL, ctx, notif_xpath, NULL, 0, 0);
if (notif == NULL)
{
NC_LOG_ERR("Failed to create notification %s.\n", notif_xpath);
break;
}
snprintf(node_xpath, sizeof(node_xpath)-1, "%s/access-point", notif_xpath);
if (lyd_new_path(notif, NULL, node_xpath, (void *)(long)access_point_name, 0, 0) == NULL)
{
NC_LOG_ERR("Failed to add 'access-point' node to notification %s.\n", notif_xpath);
break;
}
snprintf(node_xpath, sizeof(node_xpath)-1, "%s/connected", notif_xpath);
if (lyd_new_path(notif, NULL, node_xpath, is_connected ? "true" : "false", 0, 0) == NULL)
{
NC_LOG_ERR("Failed to add 'connected' node to notification %s.\n", notif_xpath);
break;
}
snprintf(node_xpath, sizeof(node_xpath)-1, "%s/remote-endpoint-state-last-change", notif_xpath);
if (lyd_new_path(notif, NULL, node_xpath,
_get_date_time_string(date_time_string, sizeof(date_time_string)), 0, 0) == NULL)
{
NC_LOG_ERR("Failed to add 'remote-endpoint-state-last-change' node to notification %s.\n", notif_xpath);
break;
}
sr_rc = sr_event_notif_send_tree(session, notif);
if (sr_rc != SR_ERR_OK)
{
NC_LOG_ERR("Failed to sent %s notification. Error '%s'\n",
notif_xpath, sr_strerror(sr_rc));
break;
}
NC_LOG_DBG("Sent %s notification: remote_endpoint %s, access_point %s: %sconnected\n",
notif_xpath, remote_endpoint_name, access_point_name, is_connected ? "" : "dis");
} while (0);
if (notif != NULL)
lyd_free_withsiblings(notif);
}
/* Get server/remote-endpoints list */
static int _server_remote_endpoints_get_cb(sr_session_ctx_t *session, const char *module_name,
const char *xpath, const char *request_path, uint32_t request_id,
struct lyd_node **parent, void *private_data)
{
const struct ly_ctx *ctx = sr_get_context(sr_session_get_connection(session));
char full_xpath[256];
const char *ep_name = NULL;
NC_LOG_INFO("module=%s xpath=%s request=%s\n", module_name, xpath, request_path);
while ((ep_name = bcm_tr451_polt_grpc_server_client_get_next(ep_name)) != NULL)
{
snprintf(full_xpath, sizeof(full_xpath)-1, "%s[name='%s']", xpath, ep_name);
*parent = nc_ly_sub_value_add(ctx, *parent, full_xpath, "name", ep_name);
}
return SR_ERR_OK;
}
bcmos_errno bbf_polt_vomci_module_start(sr_session_ctx_t *srs, struct ly_ctx *ly_ctx)
{
int sr_rc;
bcmos_errno err;
/* subscribe to events */
sr_rc = sr_module_change_subscribe(srs, BBF_POLT_VOMCI_MODULE_NAME, BBF_POLT_VOMCI_SERVER_PATH,
bbf_polt_vomci_server_change_cb, NULL, 0, SR_SUBSCR_ENABLED | SR_SUBSCR_CTX_REUSE,
&sr_ctx);
if (SR_ERR_OK == sr_rc)
{
NC_LOG_INFO("Subscribed to %s subtree changes.\n", BBF_POLT_VOMCI_SERVER_PATH);
}
else
{
NC_LOG_ERR("Failed to subscribe to %s subtree changes (%s).\n",
BBF_POLT_VOMCI_SERVER_PATH, sr_strerror(sr_rc));
return nc_sr_errno_to_bcmos_errno(sr_rc);
}
/* subscribe to events */
sr_rc = sr_module_change_subscribe(srs, BBF_POLT_VOMCI_MODULE_NAME, BBF_POLT_VOMCI_CLIENT_PATH,
bbf_polt_vomci_client_change_cb, NULL, 0, SR_SUBSCR_ENABLED | SR_SUBSCR_CTX_REUSE,
&sr_ctx);
if (SR_ERR_OK == sr_rc)
{
NC_LOG_INFO("Subscribed to %s subtree changes.\n", BBF_POLT_VOMCI_CLIENT_PATH);
}
else
{
NC_LOG_ERR("Failed to subscribe to %s subtree changes (%s).\n",
BBF_POLT_VOMCI_CLIENT_PATH, sr_strerror(sr_rc));
sr_unsubscribe(sr_ctx);
sr_ctx = NULL;
return nc_sr_errno_to_bcmos_errno(sr_rc);
}
/* subscribe to events */
sr_rc = sr_module_change_subscribe(srs, BBF_POLT_VOMCI_MODULE_NAME, BBF_POLT_VOMCI_FILTER_PATH,
bbf_polt_vomci_filter_change_cb, NULL, 0, SR_SUBSCR_ENABLED | SR_SUBSCR_CTX_REUSE,
&sr_ctx);
if (SR_ERR_OK == sr_rc)
{
NC_LOG_INFO("Subscribed to %s subtree changes.\n", BBF_POLT_VOMCI_FILTER_PATH);
}
else
{
NC_LOG_ERR("Failed to subscribe to %s subtree changes (%s).\n",
BBF_POLT_VOMCI_CLIENT_PATH, sr_strerror(sr_rc));
sr_unsubscribe(sr_ctx);
sr_ctx = NULL;
return nc_sr_errno_to_bcmos_errno(sr_rc);
}
/* Subscribe for server's remote-endpoint retrieval */
sr_rc = sr_oper_get_items_subscribe(srs, BBF_POLT_VOMCI_MODULE_NAME,
BBF_POLT_VOMCI_SERVER_REMOTE_ENDPOINTS_PATH,
_server_remote_endpoints_get_cb, NULL, 0, &sr_ctx_state);
if (SR_ERR_OK == sr_rc)
{
NC_LOG_INFO("Subscribed to %s subtree operation data retrieval.\n",
BBF_POLT_VOMCI_SERVER_REMOTE_ENDPOINTS_PATH);
}
else
{
NC_LOG_ERR("Failed to subscribe to %s subtree operation data retrieval (%s).\n",
BBF_POLT_VOMCI_SERVER_REMOTE_ENDPOINTS_PATH, sr_strerror(sr_rc));
sr_unsubscribe(sr_ctx);
sr_ctx = NULL;
return nc_sr_errno_to_bcmos_errno(sr_rc);
}
/* Register for gRPC connect/disconnect notifications */
err = bcm_tr451_polt_grpc_server_connect_disconnect_cb_register(_server_connect_disconnect_cb, srs);
err = err ? err : bcm_tr451_polt_grpc_client_connect_disconnect_cb_register(_client_connect_disconnect_cb, srs);
err = err ? err : bcm_tr451_onu_state_change_notify_cb_register(bcmolt_xpon_v_ani_state_change);
if (err != BCM_ERR_OK)
{
NC_LOG_ERR("Failed to subscribe to pOLT connect/disconnect notifications (%s).\n",
bcmos_strerror(err));
sr_unsubscribe(sr_ctx);
sr_ctx = NULL;
return err;
}
return BCM_ERR_OK;
}
void bbf_polt_vomci_module_exit(sr_session_ctx_t *srs, struct ly_ctx *ly_ctx)
{
if (sr_ctx != NULL)
{
sr_unsubscribe(sr_ctx);
sr_ctx = NULL;
}
if (sr_ctx_state != NULL)
{
sr_unsubscribe(sr_ctx_state);
sr_ctx_state = NULL;
}
bcm_tr451_polt_grpc_server_connect_disconnect_cb_register(NULL, srs);
bcm_tr451_polt_grpc_client_connect_disconnect_cb_register(NULL, srs);
}
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#include "bcmos_system.h"
#ifdef BCMOS_MSG_QUEUE_DOMAIN_SOCKET
#include <sys/un.h>
#endif
#include <sys/resource.h>
#include <arpa/inet.h>
/* task control blocks */
extern STAILQ_HEAD(task_list, bcmos_task) task_list;
/* global OS lock */
extern bcmos_mutex bcmos_res_lock;
/*
* Init
*/
#define TIMER_SIG SIGRTMIN
#if defined(CONFIG_ONU_SIM) && defined(SIMULATION_BUILD)
bcmos_bool is_high_resolution;
#endif
/* Initialize system library */
bcmos_errno bcmos_sys_init(void)
{
#if defined(CONFIG_ONU_SIM) && defined(SIMULATION_BUILD)
is_high_resolution = BCMOS_TRUE;
struct timespec res;
clock_getres(CLOCK_REALTIME, &res);
if (res.tv_nsec > 1000 && res.tv_sec == 0)
{
is_high_resolution = BCMOS_FALSE;
}
#endif
srand(bcmos_timestamp());
return BCM_ERR_OK;
}
/* Clean-up system library */
void bcmos_sys_exit(void)
{
}
/*
* Task management
*/
/*
* Default task handler
*/
/* Create a new task */
bcmos_errno bcmos_task_create(bcmos_task *task, const bcmos_task_parm *parm)
{
F_bcmos_task_handler handler;
pthread_attr_t pthread_attr;
struct sched_param pthread_sched_param = {};
int pthread_prio;
uint32_t stack_size;
void *data;
int rc;
if (!task || !parm)
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "task %p, parm %p\n", task, parm);
memset(task, 0, sizeof(*task));
if (parm->handler)
{
/* "traditional task */
handler = parm->handler;
data = (void *)parm->data;
}
else
{
/* "integrated" task */
handler = bcmos_dft_task_handler;
data = task;
/* Initialize and lock mutex to wait on */
rc = bcmos_sem_create(&task->active_sem, 0, task->parm.flags, parm->name);
if (rc)
{
BCMOS_TRACE_ERR("Task %s: can't create active_sem. Error %s (%d)\n",
parm->name, bcmos_strerror(rc), rc);
return rc;
}
}
task->parm = *parm;
/* Copy name to make sure that it is not released - in case it was on the stack */
if (task->parm.name && task->name != task->parm.name)
{
strncpy(task->name, task->parm.name, sizeof(task->name) - 1);
task->parm.name = task->name;
}
bcmos_fastlock_init(&task->active_lock, 0);
bcmos_mutex_lock(&bcmos_res_lock);
STAILQ_INSERT_TAIL(&task_list, task, list);
bcmos_mutex_unlock(&bcmos_res_lock);
task->magic = BCMOS_TASK_MAGIC;
/* pthread priorities are 1..32, 32 being the highest */
pthread_prio = 32 - (int)parm->priority;
if (pthread_prio <= 0)
pthread_prio = 1;
stack_size = PTHREAD_STACK_MIN + (parm->stack_size ? parm->stack_size : BCMOS_DEFAULT_STACK_SIZE);
rc = pthread_attr_init(&pthread_attr);
pthread_sched_param.sched_priority = pthread_prio;
rc = rc ? rc : pthread_attr_setinheritsched(&pthread_attr, PTHREAD_EXPLICIT_SCHED);
rc = rc ? rc : pthread_attr_setschedpolicy(&pthread_attr, SCHED_RR);
rc = rc ? rc : pthread_attr_setschedparam(&pthread_attr, &pthread_sched_param);
rc = rc ? rc : pthread_attr_setstacksize(&pthread_attr, stack_size);
#if __GNUC__ > 7
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wcast-function-type" /* (void *(*)(void *)) cast requires this */
#endif
rc = rc ? rc : pthread_create(&task->sys_task.t, &pthread_attr, (void *(*)(void *))handler, data);
pthread_attr_destroy(&pthread_attr);
if (rc == EPERM)
{
BCMOS_TRACE_INFO("Thread %s: priority %d is ignored. Start as root to honor priorities\n",
parm->name, (int)parm->priority);
rc = pthread_attr_init(&pthread_attr);
rc = rc ? rc : pthread_attr_setstacksize(&pthread_attr, stack_size);
rc = rc ? rc : pthread_create(&task->sys_task.t, NULL, (void *(*)(void *))handler, data);
}
#if __GNUC__ > 7
#pragma GCC diagnostic pop
#endif
if (rc)
{
bcmos_mutex_lock(&bcmos_res_lock);
STAILQ_REMOVE(&task_list, task, bcmos_task, list);
bcmos_mutex_unlock(&bcmos_res_lock);
task->magic = 0;
if (!parm->handler)
{
bcmos_sem_destroy(&task->active_sem);
}
BCMOS_TRACE_RETURN(BCM_ERR_SYSCALL_ERR, "%s (%d)\n", strerror(rc), rc);
}
return BCM_ERR_OK;
}
/* Destroy task */
bcmos_errno bcmos_task_destroy(bcmos_task *task)
{
void *res;
int rc_cancel;
int rc;
if (task->magic != BCMOS_TASK_MAGIC)
{
return BCM_ERR_PARM;
}
task->destroy_request = BCMOS_TRUE;
task->magic = BCMOS_TASK_MAGIC_DESTROYED;
bcmos_mutex_lock(&bcmos_res_lock);
STAILQ_REMOVE(&task_list, task, bcmos_task, list);
bcmos_mutex_unlock(&bcmos_res_lock);
/* The task may be waiting on semaphore. Kick it */
if (!task->parm.handler)
{
bcmos_sem_post(&task->active_sem);
}
rc_cancel = pthread_cancel(task->sys_task.t);
rc = pthread_join(task->sys_task.t, &res);
return (rc || ((!rc_cancel) && (res != PTHREAD_CANCELED))) ? BCM_ERR_SYSCALL_ERR : 0;
}
/** Get current task
* \returns task handle or NULL if not in task context
*/
bcmos_task *bcmos_task_current(void)
{
pthread_t pt = pthread_self();
bcmos_task *t, *tmp;
STAILQ_FOREACH_SAFE(t, &task_list, list, tmp)
{
if (pthread_equal(pt, t->sys_task.t))
break;
}
return t;
}
/*
* Recursive mutex
*/
/* Create recursive mutex */
bcmos_errno bcmos_mutex_create(bcmos_mutex *mutex, uint32_t flags, const char *name)
{
int err;
err = pthread_mutexattr_init(&mutex->attr);
err = err ? err : pthread_mutexattr_settype(&mutex->attr, PTHREAD_MUTEX_RECURSIVE_NP);
err = err ? err : pthread_mutex_init(&mutex->m, &mutex->attr);
if (err)
BCMOS_TRACE_RETURN(BCM_ERR_SYSCALL_ERR, "errno=%s\n", strerror(err));
return BCM_ERR_OK;
}
/** Destroy mutex
* \param[in] mutex Mutex control block
*/
void bcmos_mutex_destroy(bcmos_mutex *mutex)
{
pthread_mutex_destroy(&mutex->m);
pthread_mutexattr_destroy(&mutex->attr);
}
/* calculate absolute time equal to the current time + timeout */
static inline void _bcmos_get_abs_time(struct timespec *ts, uint32_t timeout)
{
int rc;
rc = clock_gettime(CLOCK_REALTIME, ts);
BUG_ON(rc);
#if defined(CONFIG_ONU_SIM) && defined(SIMULATION_BUILD)
if (!is_high_resolution)
{
ts->tv_sec += timeout / 1000;
ts->tv_nsec += (timeout % 1000) * 1000000;
}
else
#endif
{
ts->tv_sec += timeout / 1000000;
ts->tv_nsec += (timeout % 1000000) * 1000;
}
if (ts->tv_nsec > 1000000000)
{
ts->tv_sec += ts->tv_nsec / 1000000000;
ts->tv_nsec %= 1000000000;
}
}
/** Lock mutex
*/
void bcmos_mutex_lock(bcmos_mutex *mutex)
{
int rc;
rc = pthread_mutex_lock(&mutex->m);
if (rc)
BCMOS_TRACE_ERR("pthread_mutex_lock()->%d\n", rc);
BUG_ON(rc);
return;
}
/** Release mutex
* \param[in] mutex Mutex control block
*/
void bcmos_mutex_unlock(bcmos_mutex *mutex)
{
int rc;
rc = pthread_mutex_unlock(&mutex->m);
if (rc)
BCMOS_TRACE_ERR("pthread_mutex_unlock()->%d\n", rc);
BUG_ON(rc);
}
/*
* Semaphores
* Most of semaphore functions are inline
*/
/* Create semaphore */
bcmos_errno bcmos_sem_create(bcmos_sem *sem, uint32_t count, uint32_t flags, const char *name)
{
sem_init(&sem->s, 0, count);
return BCM_ERR_OK;
}
/* Destroy semaphore */
void bcmos_sem_destroy(bcmos_sem *sem)
{
sem_destroy(&sem->s);
}
/* Decrement semaphore counter. Wait if the counter is 0 */
bcmos_errno bcmos_sem_wait(bcmos_sem *sem, uint32_t timeout)
{
int rc;
struct timespec ts;
/* Init end time if necessary */
if (timeout && timeout != BCMOS_WAIT_FOREVER)
{
_bcmos_get_abs_time(&ts, timeout);
}
do
{
if (timeout == BCMOS_WAIT_FOREVER)
{
rc = sem_wait(&sem->s);
}
else if (timeout)
{
rc = sem_timedwait(&sem->s, &ts);
}
else
{
rc = sem_trywait(&sem->s);
}
} while (rc && errno == EINTR);
if (rc)
{
bcmos_errno err;
rc = errno;
if (rc == ETIMEDOUT)
{
err = BCM_ERR_TIMEOUT;
}
else
{
err = BCM_ERR_INTERNAL;
BCMOS_TRACE_ERR("sem_wait()->%d\n", rc);
}
return err;
}
return BCM_ERR_OK;
}
/*
* Timers
*/
/** Get current timestamp
* \returns the current system timestamp (us)
*/
uint32_t bcmos_timestamp(void)
{
struct timespec tp;
clock_gettime(CLOCK_MONOTONIC, &tp);
uint32_t timestamp = tp.tv_sec * 1000000 + tp.tv_nsec / 1000;
#if defined(CONFIG_ONU_SIM) && defined(SIMULATION_BUILD)
if (!is_high_resolution)
{
timestamp *= 1000;
}
#endif
return timestamp;
}
/** Get current timestamp - 64 bit
* \returns the current system timestamp (us)
*/
uint64_t bcmos_timestamp64(void)
{
struct timespec tp;
clock_gettime(CLOCK_MONOTONIC, &tp);
uint64_t timestamp = (uint64_t)tp.tv_sec * 1000000LL + (uint64_t)tp.tv_nsec / 1000LL;
#if defined(CONFIG_ONU_SIM) && defined(SIMULATION_BUILD)
if (!is_high_resolution)
{
timestamp *= 1000LL;
}
#endif
return timestamp;
}
/*
* Timer handlers
*/
/* For posix we must create timer task, because there is no way
* to enforce protection between a signal handler and a thread
*/
static bcmos_task _bcmos_timer_task;
static sem_t _bcmos_timer_lock;
static int _bcmos_tmr_task_handler(long data)
{
bcmos_sys_timer *timer = (bcmos_sys_timer *)data;
bcmos_task *this_task = bcmos_task_current();
if (!this_task)
return 0;
while(!this_task->destroy_request)
{
sem_wait(&_bcmos_timer_lock);
timer->handler(timer->data);
}
this_task->destroyed = BCMOS_TRUE;
return 0;
}
/* timer signal handler */
static void timer_sig_handler(int sig, siginfo_t *si, void *uc)
{
BUG_ON(si->si_code != SI_TIMER);
sem_post(&_bcmos_timer_lock);
}
/* Create timer */
bcmos_errno bcmos_sys_timer_create(bcmos_sys_timer *timer, bcmos_sys_timer_handler handler, void *data)
{
static bcmos_task_parm tmr_task_parm = {
.name = "tmr_task",
.priority = BCMOS_TASK_PRIORITY_0,
.handler = _bcmos_tmr_task_handler
};
bcmos_errno rc;
struct sigaction sa;
struct sigevent sev = {};
if (!timer || !handler)
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "timer %p, handler %p\n", timer, handler);
timer->destroyed = BCMOS_FALSE;
timer->handler = handler;
timer->data = data;
sem_init(&_bcmos_timer_lock, 0, 0);
tmr_task_parm.data = (long)timer;
rc = bcmos_task_create(&_bcmos_timer_task, &tmr_task_parm);
if (rc)
BCMOS_TRACE_RETURN(rc, "Can't create timer task\n");
sa.sa_flags = SA_SIGINFO;
sa.sa_sigaction = timer_sig_handler;
sigemptyset(&sa.sa_mask);
if (sigaction(TIMER_SIG, &sa, NULL) == -1)
perror("sigaction");
/* Prevent timer signal from interrupting system calls */
if (siginterrupt(TIMER_SIG, 0) == -1)
perror("siginterrupt");
/* Create librt timer */
sev.sigev_notify = SIGEV_SIGNAL;
sev.sigev_signo = TIMER_SIG;
sev.sigev_value.sival_ptr = timer;
if (timer_create(CLOCK_REALTIME, &sev, &timer->t) == -1)
BCMOS_TRACE_RETURN(BCM_ERR_SYSCALL_ERR, "errno %s\n", strerror(errno));
return BCM_ERR_OK;
}
/* Destroy timer */
void bcmos_sys_timer_destroy(bcmos_sys_timer *timer)
{
timer->destroyed = BCMOS_TRUE;
timer_delete(timer->t);
sem_destroy(&_bcmos_timer_lock);
bcmos_task_destroy(&_bcmos_timer_task);
}
/* (Re)start timer */
void bcmos_sys_timer_start(bcmos_sys_timer *timer, uint32_t delay)
{
struct itimerspec its;
if (timer->destroyed)
{
return;
}
#if defined(CONFIG_ONU_SIM) && defined(SIMULATION_BUILD)
if (!is_high_resolution)
{
its.it_value.tv_sec = delay / 1000;
its.it_value.tv_nsec = (delay % 1000) * 1000000;
}
else
#endif
{
its.it_value.tv_sec = delay / 1000000;
its.it_value.tv_nsec = (delay % 1000000) * 1000;
}
its.it_interval.tv_sec = 0;
its.it_interval.tv_nsec = 0;
if (timer_settime(timer->t, 0, &its, NULL) == -1)
{
BCMOS_TRACE_ERR("timer_settime errno %s\n", strerror(errno));
BUG();
}
}
/* Stop timer if running */
void bcmos_sys_timer_stop(bcmos_sys_timer *timer)
{
struct itimerspec its;
BUG_ON(!timer);
memset(&its, 0, sizeof(its));
timer_settime(timer->t, 0, &its, NULL);
}
/* Suspend current task for a time */
void bcmos_usleep(uint32_t us)
{
uint32_t ts = bcmos_timestamp();
uint32_t tse = ts + us;
int32_t d = (us > 1000000) ? 1000000 : us;
do
{
usleep(d);
d = tse - bcmos_timestamp();
if (d > 1000000) d = 1000000;
} while (d > 0);
}
/*
* Memory management
*/
/** Allocate memory from the main heap */
#ifndef BCMOS_HEAP_DEBUG
void *bcmos_alloc(uint32_t size)
#else
void *_bcmos_alloc(uint32_t size)
#endif
{
void *ptr;
bcmos_dynamic_memory_allocation_block_check(size);
ptr = malloc(size);
if (!ptr)
return ptr;
#ifdef BCMOS_HEAP_DEBUG
ptr = bcmos_heap_debug_hdr_to_user_ptr(ptr);
#endif
return ptr;
}
/** Release memory to the main pool
* \param[in] ptr
*/
#ifndef BCMOS_HEAP_DEBUG
void bcmos_free(void *ptr)
#else
void _bcmos_free(void *ptr)
#endif
{
#ifdef BCMOS_HEAP_DEBUG
ptr = (void *)bcmos_heap_user_ptr_to_debug_hdr(ptr);
#endif
free(ptr);
}
/*
* Byte memory pool
*/
/* Memory block header */
typedef struct bcmos_byte_memblk
{
bcmos_byte_pool *pool; /** pool that owns the block */
uint32_t size; /** block size (bytes) including bcmos_byte_memblk header */
#ifdef BCMOS_MEM_CHECK
uint32_t magic; /** magic number */
#define BCMOS_MEM_MAGIC_ALLOC (('m'<<24) | ('b' << 16) | ('l' << 8) | 'k')
#define BCMOS_MEM_MAGIC_FREE (('m'<<24) | ('b' << 16) | ('l' << 8) | '~')
#endif
} bcmos_byte_memblk;
/* Create byte memory pool */
bcmos_errno bcmos_byte_pool_create(bcmos_byte_pool *pool, const bcmos_byte_pool_parm *parm)
{
if (!pool || !parm)
{
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "pool %p, parm %p\n", pool, parm);
}
BCM_MEMZERO_STRUCT(pool);
pool->parm = *parm;
if (!pool->parm.size)
{
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "size %u\n", parm->size);
}
#ifdef BCMOS_MEM_CHECK
pool->magic = BCMOS_BYTE_POOL_VALID;
#endif
return BCM_ERR_OK;
}
/* Destroy memory pool */
bcmos_errno bcmos_byte_pool_destroy(bcmos_byte_pool *pool)
{
if (pool->allocated)
{
BCMOS_TRACE_RETURN(BCM_ERR_STATE, "%u bytes of memory are still allocated from the pool %s\n",
pool->allocated, pool->parm.name);
}
#ifdef BCMOS_MEM_CHECK
pool->magic = BCMOS_BYTE_POOL_DELETED;
#endif
return BCM_ERR_OK;
}
/* Allocate memory from memory pool */
void *bcmos_byte_pool_alloc(bcmos_byte_pool *pool, uint32_t size)
{
bcmos_byte_memblk *blk;
uint32_t byte_size;
void *ptr;
#ifdef BCMOS_MEM_CHECK
BUG_ON(pool->magic != BCMOS_BYTE_POOL_VALID);
#endif
if (size + pool->allocated > pool->parm.size)
return NULL;
byte_size = size + sizeof(bcmos_byte_memblk);
#ifdef BCMOS_MEM_CHECK
byte_size += sizeof(uint32_t); /* block suffix */
#endif
/* ToDo: Maintain LL of allocated blocks */
blk = (bcmos_byte_memblk *)malloc(byte_size);
if (!blk)
return NULL;
ptr = (void *)(blk + 1);
blk->size = byte_size;
pool->allocated += byte_size;
blk->pool = pool;
#ifdef BCMOS_MEM_CHECK
blk->magic = BCMOS_MEM_MAGIC_ALLOC;
*(uint32_t *)((long)blk + byte_size - sizeof(uint32_t)) = BCMOS_MEM_MAGIC_ALLOC;
#endif
return ptr;
}
/* Release memory allocated using bcmos_byte_pool_alloc() */
void bcmos_byte_pool_free(void *ptr)
{
bcmos_byte_memblk *blk;
bcmos_byte_pool *pool;
BUG_ON(!ptr);
blk = (bcmos_byte_memblk *)((long)ptr - sizeof(bcmos_byte_memblk));
pool = blk->pool;
#ifdef BCMOS_MEM_CHECK
BUG_ON(pool->magic != BCMOS_BYTE_POOL_VALID);
BUG_ON(blk->magic != BCMOS_MEM_MAGIC_ALLOC);
BUG_ON(*(uint32_t *)((long)blk + blk->size - sizeof(uint32_t)) != BCMOS_MEM_MAGIC_ALLOC);
blk->magic = BCMOS_MEM_MAGIC_FREE;
#endif
pool->allocated -= blk->size;
free(blk);
}
void _bcmos_backtrace(void)
{
void *array[32];
size_t size;
char **strings;
size_t i;
size = backtrace(array, sizeof(array)/sizeof(array[0]));
strings = backtrace_symbols(array, size);
printf("Obtained %zd stack frames.\n", size);
for (i = 0; i < size; i++)
printf("%s\n", strings[i]);
free(strings);
}
#ifdef SIMULATION_BUILD
#define BCMOS_MAX_IRQS 256
typedef int (*F_isr)(int irq, void *priv);
static F_isr isr_handler[BCMOS_MAX_IRQS];
static void *isr_priv[BCMOS_MAX_IRQS];
static bcmos_bool irq_enabled[BCMOS_MAX_IRQS];
#endif
void bcmos_int_enable(int irq)
{
#ifdef SIMULATION_BUILD
if (irq >= BCMOS_MAX_IRQS)
{
BCMOS_TRACE_ERR("irq %d is out of range\n", irq);
return;
}
if (!isr_handler[irq])
{
BCMOS_TRACE_ERR("irq %d is not connected\n", irq);
return;
}
irq_enabled[irq] = BCMOS_TRUE;
#endif
}
void bcmos_int_disable(int irq)
{
#ifdef SIMULATION_BUILD
if (irq >= BCMOS_MAX_IRQS)
{
BCMOS_TRACE_ERR("irq %d is out of range\n", irq);
return;
}
irq_enabled[irq] = BCMOS_FALSE;
#endif
}
int bcmos_int_connect(int irq, int cpu, int flags,
int (*isr)(int irq, void *priv), const char *name, void *priv)
{
#ifdef SIMULATION_BUILD
if (irq >= BCMOS_MAX_IRQS)
{
BCMOS_TRACE_ERR("irq %d is out of range\n", irq);
return BCM_ERR_RANGE;
}
if (isr_handler[irq])
{
BCMOS_TRACE_ERR("irq %d is already connected\n", irq);
return BCM_ERR_ALREADY;
}
isr_handler[irq] = isr;
isr_priv[irq] = priv;
#endif
return 0;
}
void bcmos_int_disconnect(int irq, void *priv)
{
#ifdef SIMULATION_BUILD
isr_handler[irq] = NULL;
isr_priv[irq] = NULL;
#endif
}
#ifdef SIMULATION_BUILD
void bcmos_int_fire(int irq)
{
if (irq >= BCMOS_MAX_IRQS)
{
BCMOS_TRACE_ERR("irq %d is out of range\n", irq);
return;
}
if (!irq_enabled[irq])
{
BCMOS_TRACE_ERR("irq %d is disabled\n", irq);
return;
}
if (!isr_handler[irq])
{
BCMOS_TRACE_ERR("irq %d is not connected\n", irq);
return;
}
isr_handler[irq](irq, isr_priv[irq]);
}
#endif
/* Convert IPv4/IPv6 address from internal presentation to string */
bcmos_errno bcmos_ip_to_str(const bcmos_ip_address *ip, char *ip_str, int32_t ip_str_size)
{
const char *dst = NULL;
if (ip == NULL || ip_str == NULL)
return BCM_ERR_PARM;
if (ip->version == BCMOS_IP_VERSION_4)
{
struct in_addr addr = { .s_addr = ip->ipv4.u32 };
dst = inet_ntop(AF_INET, &addr, ip_str, ip_str_size);
}
else if (ip->version == BCMOS_IP_VERSION_6)
{
struct in6_addr addr;
memcpy(addr.s6_addr, ip->ipv6.u8, sizeof(addr.s6_addr));
dst = inet_ntop(AF_INET6, &addr, ip_str, ip_str_size);
}
return (dst != NULL) ? BCM_ERR_OK : BCM_ERR_PARM;
}
/* Convert IPv4/IPv6 address from string to internal presentation */
bcmos_errno bcmos_str_to_ip(const char *ip_str, bcmos_ip_address *ip)
{
if (ip == NULL || ip_str == NULL)
return BCM_ERR_PARM;
if (strchr(ip_str, ':') == NULL)
{
struct in_addr addr;
if (!inet_aton(ip_str, &addr))
return BCM_ERR_PARM;
ip->version = BCMOS_IP_VERSION_4;
ip->ipv4.u32 = addr.s_addr;
}
else
{
struct in6_addr addr;
if (!inet_pton(AF_INET6, ip_str, &addr))
return BCM_ERR_PARM;
ip->version = BCMOS_IP_VERSION_6;
memcpy(ip->ipv6.u8, addr.s6_addr, sizeof(ip->ipv6.u8));
}
return BCM_ERR_OK;
}
#ifdef BCMOS_MSG_QUEUE_REMOTE_SUPPORT
#ifdef BCMOS_MSG_QUEUE_UDP_SOCKET
static bcmos_errno _bcmos_parse_ip_port(const char *s, struct sockaddr_in *sa)
{
uint32_t ip;
int n;
uint32_t ip1, ip2, ip3, ip4, port;
/* ToDo: add support for
* - host name
* - IPv6
*/
n = sscanf(s, "%u.%u.%u.%u:%u", &ip1, &ip2, &ip3, &ip4, &port);
if (n != 5 || ip1 > 0xff || ip2 > 0xff || ip3 > 0xff || ip4 > 0xff || port > 0xffff)
{
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "Can't parse %s. Must be ip_address:port\n", s);
}
ip = (ip1 << 24) | (ip2 << 16) | (ip3 << 8) | ip4;
sa->sin_family = AF_INET;
sa->sin_port = htons(port);
sa->sin_addr.s_addr = htonl(ip);
return BCM_ERR_OK;
}
#endif
bcmos_errno bcmos_msg_address_parse(const char *addr_string, bcmos_msg_queue_ep_type ep_type, bcmos_msg_addr *addr)
{
bcmos_errno rc = BCM_ERR_OK;;
if (!addr_string || !addr || !addr->len || !addr->addr)
return BCM_ERR_PARM;
switch (ep_type)
{
#ifdef BCMOS_MSG_QUEUE_DOMAIN_SOCKET
case BCMOS_MSG_QUEUE_EP_DOMAIN_SOCKET: /**< Domain-socket address */
{
struct sockaddr_un sa = {};
/* In linux path can start from 0 character */
if (addr->len < sizeof(sa))
return BCM_ERR_OVERFLOW;
sa.sun_family = AF_UNIX;
addr->type = ep_type;
addr->len = sizeof(sa);
strncpy(sa.sun_path, addr_string, sizeof(sa.sun_path) - 1);
/* In linux path can start from 0 character */
if (!sa.sun_path[0])
strncpy(&sa.sun_path[1], addr_string + 1, sizeof(sa.sun_path) - 1);
memcpy(addr->addr, &sa, sizeof(sa));
break;
}
#endif
#ifdef BCMOS_MSG_QUEUE_UDP_SOCKET
case BCMOS_MSG_QUEUE_EP_UDP_SOCKET: /**< UDP socket-based address in format ipv4_addr:udp_port */
{
struct sockaddr_in in = {};
if (addr->len < sizeof(struct sockaddr_in))
return BCM_ERR_OVERFLOW;
rc = _bcmos_parse_ip_port(addr_string, &in);
if (rc != BCM_ERR_OK)
break;
addr->type = ep_type;
addr->len = sizeof(struct sockaddr_in);
memcpy(addr->addr, &in, sizeof(struct sockaddr_in));
break;
}
#endif
default:
rc = BCM_ERR_NOT_SUPPORTED;
}
return rc;
}
#endif
/* Functions common for domain socket and UDP socket - based message queues */
#if defined(BCMOS_MSG_QUEUE_DOMAIN_SOCKET) || defined(BCMOS_MSG_QUEUE_UDP_SOCKET)
/** "send" to socket */
static bcmos_errno _bcmos_socket_send(bcmos_msg_queue *queue, bcmos_msg *m, uint8_t *buf, uint32_t buf_length)
{
int rc;
struct iovec iov = { .iov_base = buf, .iov_len = buf_length };
struct msghdr msg = {
.msg_iov = &iov, .msg_iovlen = 1, .msg_flags = 0,
.msg_name = (void *)queue->ep_extra_data, .msg_namelen = queue->ep_extra_data_size
};
/* We must have transmit address either in message queue remote endpoint
* or in the message itself. Otherwise, transmit is not supported */
if (!queue->ep_extra_data_size)
{
if (!m->addr.len)
return BCM_ERR_NOT_SUPPORTED;
msg.msg_name = m->addr.addr;
msg.msg_namelen = m->addr.len;
}
rc = sendmsg(queue->ep, &msg, 0);
return (rc == buf_length) ? BCM_ERR_OK : BCM_ERR_COMM_FAIL;
}
/** "recv" from socket */
static bcmos_errno _bcmos_socket_recv(bcmos_msg_queue *queue, uint32_t timeout, uint8_t **buf, uint32_t *buf_length)
{
struct iovec iov = { .iov_base = queue->recv_buf, .iov_len = queue->q.parm.max_mtu };
struct msghdr msg = {
.msg_iov = &iov, .msg_iovlen = 1,
.msg_name = queue->last_addr.addr, .msg_namelen = BCMOS_MSG_MAX_ADDR_LENGTH
};
int rc;
int wait = 0;
if (timeout && timeout != BCMOS_WAIT_FOREVER)
{
fd_set read_fds;
struct timeval tv;
FD_ZERO(&read_fds);
FD_SET(queue->ep, &read_fds);
tv.tv_sec = timeout / 1000000;
tv.tv_usec = (timeout % 1000000) * 1000;
rc = select(queue->ep + 1, &read_fds, NULL, NULL, &tv);
if (rc < 0)
{
return BCM_ERR_COMM_FAIL;
}
if (!rc || !FD_ISSET(queue->ep, &read_fds))
return BCM_ERR_TIMEOUT;
wait = MSG_DONTWAIT;
}
rc = recvmsg(queue->ep, &msg, wait);
if (rc < 0)
{
return BCM_ERR_COMM_FAIL;
}
if (rc == 0)
return BCM_ERR_NOENT;
queue->last_addr.len = msg.msg_namelen;
*buf = queue->recv_buf;
*buf_length = rc;
return BCM_ERR_OK;
}
static bcmos_errno _bcmos_socket_close(bcmos_msg_queue *queue)
{
/* Close domain socket */
if (queue->ep > 0)
{
close(queue->ep);
}
if (queue->ep_extra_data)
{
bcmos_free(queue->ep_extra_data);
}
if (queue->last_addr.addr)
{
bcmos_free(queue->last_addr.addr);
}
return BCM_ERR_OK;
}
/* Pack message for over-the-socket transmission.
* This function is good for case when both queue ends are on the same CPU
* and there is no need to do any translation.
*/
static bcmos_errno _bcmos_transparent_pack(bcmos_msg_queue *queue, bcmos_msg *msg, uint8_t **buf, uint32_t *buf_length)
{
uint32_t size = BCMOS_MSG_HDR_SIZE + msg->size;
if (size > queue->q.parm.max_mtu)
{
BCMOS_TRACE_RETURN(BCM_ERR_OVERFLOW, "Attempt to send message longer than configured max_mtu %u > %u\n",
size, queue->q.parm.max_mtu);
}
/* If there is sufficient head-room in the message, pack header in place.
* Otherwise, copy the entire message to send_buf.
*/
if (msg->start && msg->data && ((unsigned long)msg->data - (unsigned long)msg->start >= BCMOS_MSG_HDR_SIZE))
{
bcmos_msg_hdr_pack(msg, (uint8_t *)msg->data - BCMOS_MSG_HDR_SIZE, msg->size);
*buf = (uint8_t *)msg->data - BCMOS_MSG_HDR_SIZE;
}
else
{
bcmos_msg_hdr_pack(msg, queue->send_buf, msg->size);
if (msg->size)
{
BUG_ON(msg->data == NULL);
memcpy(queue->send_buf + BCMOS_MSG_HDR_SIZE, msg->data, msg->size);
}
*buf = queue->send_buf;
}
*buf_length = size;
return BCM_ERR_OK;
}
/** "unpack" message. In case of domain socket both queue ends are in the same CPU.
* Message is sent as-is
*/
static bcmos_errno _bcmos_transparent_unpack(bcmos_msg_queue *queue, uint8_t *buf, uint32_t buf_length, bcmos_msg **msg)
{
bcmos_msg *m;
uint8_t *data_ptr;
if (buf_length < BCMOS_MSG_HDR_SIZE)
{
BCMOS_TRACE_RETURN(BCM_ERR_INTERNAL, "Received message is too short (%u)\n", buf_length);
}
/* Adjust buf_length to account for difference in packed and unpacked message header sizes */
buf_length -= BCMOS_MSG_HDR_SIZE;
buf_length += sizeof(bcmos_msg);
buf_length += queue->last_addr.len;
m = bcmos_alloc(buf_length);
if (!m)
{
BCMOS_TRACE_RETURN(BCM_ERR_NOMEM, "Received message discarded: %u bytes\n", buf_length);
}
bcmos_msg_hdr_unpack(buf, m);
m->release = NULL;
m->data_release = NULL;
if (m->size != buf_length - sizeof(bcmos_msg) - queue->last_addr.len)
{
BCMOS_TRACE_ERR("Received message is insane. Expected data length %u, got %lu\n",
m->size, buf_length - sizeof(bcmos_msg));
bcmos_free(m);
return BCM_ERR_INTERNAL;
}
data_ptr = (uint8_t *)(m + 1);
if (queue->last_addr.len)
{
m->addr.addr = data_ptr;
m->addr.len = queue->last_addr.len;
memcpy(m->addr.addr, queue->last_addr.addr, queue->last_addr.len);
data_ptr += queue->last_addr.len;;
}
else
{
m->addr.addr = NULL;
m->addr.len = 0;
}
if (m->size)
{
m->data = m->start = data_ptr;
memcpy(m->data, &buf[BCMOS_MSG_HDR_SIZE], m->size);
}
else
{
m->data = m->start = NULL;
}
*msg = m;
return BCM_ERR_OK;
}
#endif
/* Domain-socket-based inter-process communication */
#ifdef BCMOS_MSG_QUEUE_DOMAIN_SOCKET
bcmos_errno bcmos_sys_msg_queue_domain_socket_open(bcmos_msg_queue *queue)
{
struct sockaddr_un sa;
bcmos_msg_addr addr = { .len = sizeof(sa), .addr = &sa };
bcmos_errno rc = BCM_ERR_PARM;
do
{
/* Open domain socket */
queue->ep = socket(AF_UNIX, SOCK_DGRAM, 0);
if (queue->ep < 0)
{
BCMOS_TRACE_ERR("Can't create domain socket. error %s\n", strerror(errno));
break;
}
/* If local_ep_address is set - the queue supports receive */
if (queue->q.parm.local_ep_address)
{
rc = bcmos_msg_address_parse(queue->q.parm.local_ep_address, BCMOS_MSG_QUEUE_EP_DOMAIN_SOCKET, &addr);
if (rc)
{
BCMOS_TRACE_ERR("Can't parse domain socket address %s. error %s\n",
queue->q.parm.local_ep_address, bcmos_strerror(rc));
break;
}
if (bind(queue->ep, (struct sockaddr *)&sa, sizeof(sa)) < 0)
{
int err = errno;
BCMOS_TRACE_ERR("Can't bind domain socket to %s. error %s\n",
queue->q.parm.local_ep_address, strerror(err));
rc = BCM_ERR_PARM;
break;
}
}
/* If remote_ep_address is set - the queue supports transmit */
if (queue->q.parm.remote_ep_address)
{
queue->ep_extra_data = bcmos_calloc(sizeof(struct sockaddr_un));
if (!queue->ep_extra_data)
{
rc = BCM_ERR_NOMEM;
break;
}
rc = bcmos_msg_address_parse(queue->q.parm.remote_ep_address, BCMOS_MSG_QUEUE_EP_DOMAIN_SOCKET, &addr);
if (rc)
{
BCMOS_TRACE_ERR("Can't parse domain socket address %s. error %s\n",
queue->q.parm.remote_ep_address, bcmos_strerror(rc));
break;
}
memcpy(queue->ep_extra_data, &sa, sizeof(sa));
queue->ep_extra_data_size = sizeof(sa);
}
/* Allocate storage for last sender's address */
queue->last_addr.addr = bcmos_calloc(BCMOS_MSG_MAX_ADDR_LENGTH);
if (!queue->last_addr.addr)
{
rc = BCM_ERR_NOMEM;
break;
}
/* Set callbacks */
queue->q.parm.close = _bcmos_socket_close;
queue->q.parm.send = _bcmos_socket_send;
queue->q.parm.recv = _bcmos_socket_recv;
if (!queue->q.parm.pack)
queue->q.parm.pack = _bcmos_transparent_pack;
if (!queue->q.parm.unpack)
queue->q.parm.unpack = _bcmos_transparent_unpack;
rc = BCM_ERR_OK;
} while (0);
if (rc)
_bcmos_socket_close(queue);
return rc;
}
#endif
/* UDP-socket-based inter-process communication */
#ifdef BCMOS_MSG_QUEUE_UDP_SOCKET
bcmos_errno bcmos_sys_msg_queue_udp_socket_open(bcmos_msg_queue *queue)
{
struct sockaddr_in sa;
bcmos_msg_addr addr = { .len = sizeof(sa), .addr = &sa };
bcmos_errno rc = BCM_ERR_PARM;
do
{
/* Open UDP socket */
queue->ep = socket(AF_INET, SOCK_DGRAM, 0);
if (queue->ep < 0)
{
BCMOS_TRACE_ERR("Can't create UDP socket. error %s\n", strerror(errno));
break;
}
/* If local_ep_address is set - the queue supports receive */
if (queue->q.parm.local_ep_address)
{
rc = bcmos_msg_address_parse(queue->q.parm.local_ep_address, BCMOS_MSG_QUEUE_EP_UDP_SOCKET, &addr);
if (rc)
{
BCMOS_TRACE_ERR("Can't parse UDP socket address %s. error %s\n",
queue->q.parm.local_ep_address, bcmos_strerror(rc));
break;
}
if (bind(queue->ep, (struct sockaddr *)&sa, sizeof(sa)) < 0)
{
int err = errno;
BCMOS_TRACE_ERR("Can't bind UDP socket to %s. error %s\n",
queue->q.parm.local_ep_address, strerror(err));
rc = BCM_ERR_PARM;
break;
}
}
/* If remote_ep_address is set - the queue supports transmit */
if (queue->q.parm.remote_ep_address)
{
queue->ep_extra_data = bcmos_calloc(sizeof(sa));
if (!queue->ep_extra_data)
{
rc = BCM_ERR_NOMEM;
break;
}
rc = bcmos_msg_address_parse(queue->q.parm.remote_ep_address, BCMOS_MSG_QUEUE_EP_UDP_SOCKET, &addr);
if (rc)
{
BCMOS_TRACE_ERR("Can't parse domain socket address %s. error %s\n",
queue->q.parm.remote_ep_address, bcmos_strerror(rc));
break;
}
memcpy(queue->ep_extra_data, &sa, sizeof(sa));
queue->ep_extra_data_size = sizeof(sa);
}
/* Allocate storage for last sender's address */
queue->last_addr.addr = bcmos_calloc(BCMOS_MSG_MAX_ADDR_LENGTH);
if (!queue->last_addr.addr)
{
rc = BCM_ERR_NOMEM;
break;
}
/* Set callbacks */
queue->q.parm.close = _bcmos_socket_close;
queue->q.parm.send = _bcmos_socket_send;
queue->q.parm.recv = _bcmos_socket_recv;
if (!queue->q.parm.pack)
queue->q.parm.pack = _bcmos_transparent_pack;
if (!queue->q.parm.unpack)
queue->q.parm.unpack = _bcmos_transparent_unpack;
rc = BCM_ERR_OK;
} while (0);
if (rc)
_bcmos_socket_close(queue);
return rc;
}
#endif
/*
* File IO
*/
bcmos_file *bcmos_file_open(const char *path, bcmos_file_flag flags)
{
FILE *fd;
char *mode;
if (flags & BCMOS_FILE_FLAG_APPEND)
mode = "a";
else if ((flags & (BCMOS_FILE_FLAG_READ | BCMOS_FILE_FLAG_WRITE)) == (BCMOS_FILE_FLAG_READ | BCMOS_FILE_FLAG_WRITE))
mode = "r+";
else if (flags & BCMOS_FILE_FLAG_READ)
mode = "r";
else if (flags & BCMOS_FILE_FLAG_WRITE)
mode = "w";
else
return NULL;
fd = fopen(path, mode);
return (bcmos_file *)fd;
}
int bcmos_file_read(bcmos_file *file, void *data, uint32_t size)
{
uint32_t bytes_read;
bytes_read = fread(data, 1, size, (FILE *)file);
if ((bytes_read < size) && ferror((FILE *)file))
{
BCMOS_TRACE_ERR("fread returned error %s\n", strerror(errno));
return (int)BCM_ERR_IO;
}
return (int)bytes_read;
}
int bcmos_file_write(bcmos_file *file, const void *data, uint32_t size)
{
uint32_t bytes_written;
bytes_written = fwrite(data, 1, size, (FILE *)file);
if ((bytes_written < size) && ferror((FILE *)file))
{
BCMOS_TRACE_ERR("fwrite returned error %s\n", strerror(errno));
return (int)BCM_ERR_IO;
}
return (int)bytes_written;
}
bcmos_errno bcmos_file_seek(bcmos_file *file, unsigned long offset)
{
int rc;
rc = fseek((FILE *)file, offset, SEEK_SET);
if (rc)
{
BCMOS_TRACE_ERR("fseek returned error %s\n", strerror(errno));
return (int)BCM_ERR_IO;
}
return BCM_ERR_OK;
}
void bcmos_file_close(bcmos_file *file)
{
fclose((FILE *)file);
}
char *bcmos_file_gets(bcmos_file *file, char *s, int size)
{
return fgets(s, size, (FILE *)file);
}
void * __attribute__((weak)) bcmos_dma_alloc(uint8_t device, uint32_t size, dma_addr_t *dma_addr)
{
void *ptr = bcmos_alloc(size);
if (!ptr)
return NULL;
if (dma_addr)
*dma_addr = bcmos_virt_to_phys(ptr);
return ptr;
}
void __attribute__((weak)) bcmos_dma_free(uint8_t device, void *ptr)
{
bcmos_free(ptr);
}
void __attribute__((weak)) bcm_pci_write32(volatile uint32_t *address, uint32_t value)
{
#ifdef PCIE_HW_ENDIAN_SWAP
*address = BCMOS_ENDIAN_CPU_TO_BIG_U32(value);
#else
*address = BCMOS_ENDIAN_CPU_TO_LITTLE_U32(value);
#endif
}
uint32_t __attribute__((weak)) bcm_pci_read32(const volatile uint32_t *address)
{
#ifdef PCIE_HW_ENDIAN_SWAP
return BCMOS_ENDIAN_BIG_TO_CPU_U32(*address);
#else
return BCMOS_ENDIAN_LITTLE_TO_CPU_U32(*address);
#endif
}
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#ifndef _BCMOLT_UTILS_H_
#define _BCMOLT_UTILS_H_
#include "bcmos_system.h"
#include "bcmolt_calc_crc32_table.h"
#define BCMOS_MACADDR_FMT_STR "%02X:%02X:%02X:%02X:%02X:%02X"
#define BCMOS_MACADDR_PARAMS(mac) (mac)->u8[0],(mac)->u8[1],(mac)->u8[2],(mac)->u8[3],(mac)->u8[4],(mac)->u8[5]
#define MAC_STR_LEN 18
#define BYTES_IN_MEGABYTE(bytes) ((bytes) / (1024 * 1024))
/* Define the switch statement fall-through attribute for GCC compilers version 7 and newer. This indicates
* that an explicit fallthrough was expected.
*/
#if defined(__GNUC__) && __GNUC__ >= 7
#define BCMOLT_FALL_THROUGH __attribute__((fallthrough))
#else
#define BCMOLT_FALL_THROUGH
#endif
static inline char *bcmos_mac_2_str(const bcmos_mac_address *mac, char *buf)
{
snprintf(buf, MAC_STR_LEN, BCMOS_MACADDR_FMT_STR, BCMOS_MACADDR_PARAMS(mac));
return buf;
}
/** Swap a byte string of any length.
*
* \param[in] ptr pointer to a memory space.
* \param[in] len length
* \note
* {0, 1, 2, 3} becomes {3, 2, 1, 0}
*/
static inline void bcmos_swap_bytes_in_place(uint8_t *ptr, uint32_t len)
{
uint32_t ii;
uint8_t tmp;
for (ii = 0; ii < (len / 2); ii++)
{
tmp = ptr[len - ii - 1];
ptr[len - ii - 1] = ptr[ii];
ptr[ii] = tmp;
}
}
/** Swap a byte string of any length.
*
* \param[out] dst pointer to a memory space for the swapped bytes.
* \param[in] src pointer to a memory space for bytes to be swapped.
* \param[in] len length in bytes
* \note
* {0, 1, 2, 3} becomes {3, 2, 1, 0}
*/
static inline void bcmos_swap_bytes(uint8_t *dst, const uint8_t *src, const uint32_t len)
{
uint32_t ii;
for (ii = 0; ii < len; ii++)
{
dst[ii] = src[len - ii - 1];
}
}
/** Copy bits from a given range of the source to a different range of the
* destination
*
* \param[in] dst destination value to be merged to
* \param[in] dst_hi high bit position
* \param[in] dst_lo low bit position
* \param[in] src source value to copy the bits from
* \param[in] src_hi high bit position
* \param[in] src_lo low bit position
*
* \return destination value
*/
static inline uint32_t bcmos_bits_copy_u32(uint32_t dst, uint8_t dst_hi, uint8_t dst_lo,
uint32_t src, uint8_t src_hi, uint8_t src_lo)
{
dst &= (~(((1 << ((dst_hi - dst_lo) + 1)) - 1) << dst_lo));
src &= (((1 << ((src_hi - src_lo) + 1)) - 1) << src_lo);
dst |= ((dst_lo >= src_lo)? (src << (dst_lo - src_lo)): (src >> (src_lo - dst_lo)));
return dst;
}
/* network to host on unaligned array of uint32_t elements. Treat pointer p as a pointer to an array of uint32_t elements. Get element i. */
#define N2H32(p, i) ((((const uint8_t *)(p))[(i) * 4]<<24) | (((const uint8_t *)(p))[(i) * 4+1]<<16) | (((const uint8_t *)(p))[(i) * 4+2]<<8) | (((const uint8_t *)(p))[(i) * 4+3]))
/* network to host on unaligned array of uint16_t elements. Treat pointer p as a pointer to an array of uint16_t elements. Get element i. */
#define N2H16(p, i) ((((const uint8_t *)(p))[(i) * 2]<<8) | (((const uint8_t *)(p))[(i) * 2+1]))
/* network to host on unaligned array of uint8_t elements. Treat pointer p as a pointer to an array of uint8_t elements. Get element i. */
#define N2H8(p, i) (((const uint8_t *)(p))[(i)])
/* For internal use by the following H2N* macros */
#define H2N8(p, v) *((uint8_t *)p) = (uint8_t)(v)
/* host to network conversion of a uint16_t with support for non 16 bit aligned destination address. p is a (uint8_t *) destination pointer. v is a uint16_t value. v can be written to p even if p is unaligned to 16 bits. */
#define H2N16(p, v) (H2N8((p), (v) >> 8), H2N8(((uint8_t *)(p) + 1), (v)))
/* host to network conversion of a uint32_t with support for non 32 bit aligned destination address. p is a (uint8_t *) destination pointer. v is a uint32_t value. v can be written to p even if p is unaligned to 32 bits. */
#define H2N32(p, v) (H2N16((p), (v) >> 16), H2N16(((uint8_t *)(p) + 2), (v)))
#define NUM_ELEM(array) (sizeof(array) / sizeof((array)[0]))
void bcmos_hexdump(bcmos_msg_print_cb print_cb, void *context, const void *buffer, uint32_t offset, uint32_t count, const char *indent);
void bcmos_hexdump_one_line(const char *funcname,
uint32_t lineno,
bcmos_msg_print_cb print_cb,
void *context,
char *out_buf,
uint32_t max_buf_size,
const void *buffer, /* start of memory region to dump */
uint32_t start_offset, /* start offset into the region */
uint32_t byte_count, /* number of bytes in region to dump */
const char *prefix, /* optional prefix string */
const char *suffix); /* optional suffix string */
static inline uint32_t bcmolt_calc_crc32(uint32_t crc, const void *buf, size_t size)
{
const uint32_t *p = (const uint32_t *)buf;
const uint8_t *p1;
crc = crc ^ ~0U;
for ( ; size >= sizeof(uint32_t); size -= sizeof(uint32_t), ++p)
{
uint32_t w = *p;
/* Convert to BE so that bytes are processed in the same order they appear in memory */
w = BCMOS_ENDIAN_CPU_TO_BIG_U32(w);
crc = bcmolt_calc_crc32_table[(crc ^ w>>24) & 0xFF] ^ (crc >> 8);
crc = bcmolt_calc_crc32_table[(crc ^ w>>16) & 0xFF] ^ (crc >> 8);
crc = bcmolt_calc_crc32_table[(crc ^ w>>8) & 0xFF] ^ (crc >> 8);
crc = bcmolt_calc_crc32_table[(crc ^ w) & 0xFF] ^ (crc >> 8);
}
p1 = (const uint8_t *)p;
while (size--)
crc = bcmolt_calc_crc32_table[(crc ^ *p1++) & 0xFF] ^ (crc >> 8);
return crc ^ ~0U;
}
#define BCMOLT_TIME_STR_MAX_LEN 80
/* Read data of given width from given buffer */
bcmos_errno bcmolt_read_snum(uint8_t byte_width, const void *data, int64_t *n);
#endif /* BCMOLT_UTILS_H */
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#include <sys/un.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include <bcmolt_daemon.h>
#include <bcmolt_utils.h>
#define DAEMON_FILE_NAME_LENGTH 64
static bcmolt_daemon_parms daemon_parms;
static int daemon_pid_file = -1;
/* Get PID file name */
static char *daemon_pid_file_name(const bcmolt_daemon_parms *parms)
{
static char pid_file_name[DAEMON_FILE_NAME_LENGTH];
return bcmolt_daemon_file_name(parms, DAEMON_PID_FILE_SUFFIX, pid_file_name, sizeof(pid_file_name));
}
static bcmos_bool daemon_check_running(const bcmolt_daemon_parms *parms, int *p_pid_file)
{
char str[16];
int pid_file;
const char *pid_file_name = daemon_pid_file_name(parms);
pid_file = open(pid_file_name, O_RDWR | O_CREAT, 0640);
if (pid_file < 0)
{
printf("%s daemon: can't open PID file %s for writing\n", parms->name, pid_file_name);
return BCMOS_TRUE;
}
if (flock(pid_file, LOCK_EX | LOCK_NB))
{
/* Can't lock file */
printf("%s daemon: already running\n", parms->name);
close(pid_file);
return BCMOS_TRUE;
}
if (p_pid_file != NULL)
*p_pid_file = pid_file;
/* Get current PID */
sprintf(str, "%d\n", getpid());
/* Write PID to lockfile */
if (write(pid_file, str, strlen(str)) < 0)
{
printf("%s daemon: write into pidfile %s failed. '%s'\n",
parms->name, pid_file_name, strerror(errno));
}
if (daemon_parms.name == NULL)
{
daemon_parms = *parms;
}
/* pid_file is intentionally left opened. It serves as a lock file
that prevents another application instance from starting
*/
return BCMOS_FALSE;
}
static void _bcmolt_daemon_init_started(void)
{
char done_file_name[DAEMON_FILE_NAME_LENGTH];
bcmolt_daemon_file_name(&daemon_parms, DAEMON_INIT_DONE_FILE_SUFFIX, done_file_name,
sizeof(done_file_name));
unlink(done_file_name);
}
/* Delete all temporary daemon artifacts */
void bcmolt_daemon_terminate(int exit_code)
{
_bcmolt_daemon_init_started();
if (daemon_pid_file >= 0)
close(daemon_pid_file);
unlink(daemon_pid_file_name(&daemon_parms));
if (daemon_parms.is_cli_support)
{
char in_file_name[DAEMON_FILE_NAME_LENGTH];
char out_file_name[DAEMON_FILE_NAME_LENGTH];
close(STDIN_FILENO);
close(STDOUT_FILENO);
bcmolt_daemon_file_name(&daemon_parms, DAEMON_CLI_INPUT_FILE_SUFFIX, in_file_name, sizeof(in_file_name));
bcmolt_daemon_file_name(&daemon_parms, DAEMON_CLI_OUTPUT_FILE_SUFFIX, out_file_name, sizeof(out_file_name));
unlink(in_file_name);
unlink(out_file_name);
}
exit(exit_code);
}
/* Signal handler */
static void daemon_signal_handler(int signal_number)
{
switch (signal_number)
{
case SIGINT:
case SIGTERM:
case SIGKILL:
printf("%s daemon: Caught SIGINT/SIGTERM/SIGKILL signal. Terminating..\n", daemon_parms.name);
if (daemon_parms.terminate_cb)
daemon_parms.terminate_cb();
bcmolt_daemon_terminate(0);
break;
case SIGHUP:
if (daemon_parms.restart_cb)
{
printf("%s daemon: Caught SIGHUP signal. Restarting..\n", daemon_parms.name);
daemon_parms.restart_cb();
break;
}
BCMOLT_FALL_THROUGH;
default:
printf("%s daemon: Caught unexpected signal %d. Signal ignored\n", daemon_parms.name, signal_number);
break;
}
}
/* output handler: in addition to printing it flushes stdout */
static int daemon_print_redirect_cb(void *data, const char *format, va_list ap)
{
int n = vprintf(format, ap);
fflush(stdout);
return n;
}
/* daemonize caller */
bcmos_errno bcmolt_daemon_start(const bcmolt_daemon_parms *parms)
{
struct sigaction act;
pid_t pid = 0;
int fd;
int flags;
int pid_file;
char in_file_name[DAEMON_FILE_NAME_LENGTH];
char out_file_name[DAEMON_FILE_NAME_LENGTH];
if (parms == NULL || parms->name == NULL)
return BCM_ERR_PARM;
/* Check if not running already */
if (daemon_check_running(parms, &pid_file))
{
exit(EXIT_FAILURE);
}
printf("Starting %s daemon in the background\n", parms->descr ? parms->descr : parms->name);
_bcmolt_daemon_init_started();
/* Fork off the parent process */
pid = fork();
/* An error occurred */
if (pid < 0)
{
exit(EXIT_FAILURE);
}
/* Success: Let the parent terminate */
if (pid > 0)
{
exit(EXIT_SUCCESS);
}
/* On success: The child process becomes session leader */
if (setsid() < 0)
{
exit(EXIT_FAILURE);
}
/* Ignore signal sent from child to parent process */
signal(SIGCHLD, SIG_IGN);
/* Set up a HUP signal handler*/
memset (&act, 0, sizeof (act));
act.sa_handler = (__sighandler_t)daemon_signal_handler;
if ((parms->restart_cb != NULL && sigaction(SIGHUP, &act, NULL) < 0) ||
(parms->terminate_cb != NULL &&
(sigaction(SIGINT, &act, NULL) < 0 || sigaction(SIGTERM, &act, NULL) < 0)))
{
perror("sigaction");
close(pid_file);
unlink(daemon_pid_file_name(parms));
return BCM_ERR_INTERNAL;
}
umask(0);
/* Create CLI FIFO files if CLI support is enabled */
if (parms->is_cli_support)
{
bcmolt_daemon_file_name(parms, DAEMON_CLI_INPUT_FILE_SUFFIX, in_file_name, sizeof(in_file_name));
bcmolt_daemon_file_name(parms, DAEMON_CLI_OUTPUT_FILE_SUFFIX, out_file_name, sizeof(out_file_name));
/* Create an input FIFO for CLI */
unlink(in_file_name);
unlink(out_file_name);
if (((mkfifo(in_file_name, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) < 0) &&
(errno != EEXIST)) ||
((mkfifo(out_file_name, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH) < 0) &&
(errno != EEXIST)))
{
close(pid_file);
unlink(daemon_pid_file_name(parms));
printf("%s: couldn't create CLI FIFO. Error %s\n", parms->name, strerror(errno));
return BCM_ERR_IO;
}
}
/* Close all open file descriptors */
for (fd = sysconf(_SC_OPEN_MAX); fd >= 0; fd--)
{
if ((fd != pid_file) && (parms->is_cli_support || fd != STDOUT_FILENO))
close(fd);
}
if (parms->is_cli_support)
{
/* Associate stdin, stdout, stderr with a pipe */
/* stdin */
fd = open(in_file_name, O_RDONLY | O_NONBLOCK);
if (fd == -1)
{
BCMOS_TRACE_ERR("cannot open input file '%s', errno=%d\n", in_file_name, errno);
exit(EXIT_FAILURE);
}
if (fd != STDIN_FILENO)
{
dup2(fd, STDIN_FILENO);
close(fd);
}
/* stdout. must be open as RDWR, because non-blocking open as WRONLY will fail (see fifo(7)) */
fd = open(out_file_name, O_RDWR | O_NONBLOCK);
if (fd == -1)
{
BCMOS_TRACE_ERR("cannot open output file '%s', errno=%d\n", out_file_name, errno);
exit(EXIT_FAILURE);
}
if (fd != STDOUT_FILENO)
{
dup2(fd, STDOUT_FILENO);
close(fd);
}
/* stderr */
dup2(STDOUT_FILENO, STDERR_FILENO);
/* Make STDIN blocking */
flags = fcntl(STDIN_FILENO, F_GETFL, 0);
if (fcntl(STDIN_FILENO, F_SETFL, flags & ~O_NONBLOCK) == -1)
{
BCMOS_TRACE_ERR("fnctl returned error, errno=%d\n", errno);
exit(EXIT_FAILURE);
}
/* Force STDOUT flush following output to CLI FIFO */
bcmos_print_redirect(BCMOS_PRINT_REDIRECT_MODE_REDIRECT, daemon_print_redirect_cb, NULL);
}
daemon_pid_file = pid_file;
return BCM_ERR_OK;
}
/* Indicate that application init is completed */
bcmos_errno bcmolt_daemon_init_completed(void)
{
char done_file_name[DAEMON_FILE_NAME_LENGTH];
int done_file;
bcmolt_daemon_file_name(&daemon_parms, DAEMON_INIT_DONE_FILE_SUFFIX, done_file_name,
sizeof(done_file_name));
done_file = open(done_file_name, O_RDWR|O_CREAT, 0640);
if (done_file < 0)
{
printf("dev_mgmt_daemon: can't open DONE file %s for writing\n", done_file_name);
return BCM_ERR_IO;
}
close(done_file);
return BCM_ERR_OK;
}
/* Check if application is already running */
bcmos_bool bcmolt_daemon_check_lock(const bcmolt_daemon_parms *parms)
{
return daemon_check_running(parms, NULL);
}
<file_sep>## Broadband Forum YANG Modules
### 2019-02-25: [TR-385](https://www.broadband-forum.org/technical/download/TR-385.pdf) ITU-T PON YANG Modules
*Tag: [v3.0.0-TR-385](https://github.com/BroadbandForum/yang/tree/v3.0.0-TR-385)*
TR-385 defines YANG data models for ITU-T Passive Optical Networks (PON) devices as defined in ITU-T G.984.x, ITU-T G.987.x, ITU-T G.989.x, and ITU-T G.9807.x.
(To avoid confusion, the YANG files from the 2017-05-05 WT-385_draft1 release have been removed.)
### 2018-12-03: [TR-383a2](https://www.broadband-forum.org/technical/download/TR-383_Amendment-2.pdf) Common YANG Modules for Access Networks
*Tag: [v2.2.0-TR-383a2](https://github.com/BroadbandForum/yang/tree/v2.2.0-TR-383a2)*
* Add `ethernet-like` abstract interface type
### 2018-10-01: [TR-355a1](https://www.broadband-forum.org/technical/download/TR-355_Amendment-1.pdf) YANG Modules for FTTdp Management
*Tag: [v1.1.0-TR-355a1](https://github.com/BroadbandForum/yang/tree/v1.1.0-TR-355a1)*
* Add support for Reverse Power Feeding
* Update per the latest versions of associated ITU-T specifications
### 2018-07-13: [TR-374](https://www.broadband-forum.org/technical/download/TR-374.pdf) YANG modules for management of G.hn systems in FTTdp architectures
*Tag: [v4.0.0-TR-374](https://github.com/BroadbandForum/yang/tree/v4.0.0-TR-374)*
TR-374 defines YANG data models for the management of ITU-T G.hn technology when applied to FTTdp architectures.
### 2018-07-13: [TR-383a1](https://www.broadband-forum.org/technical/download/TR-383_Amendment-1.pdf) Common YANG Modules for Access Networks
*Tag: [v2.1.0-TR-383a1](https://github.com/BroadbandForum/yang/tree/v2.1.0-TR-383a1)*
* Extend functionality of Layer 2 forwarding and QoS models
* Add new model for Layer 2 multicast management
* Remove models which depended on an early draft of ietf-hardware (these will be published again in a subsequent release based on the revision of ietf-hardware contained in [RFC 8348](https://tools.ietf.org/html/rfc8348))
### 2017-11-27: [TR-355c2](https://www.broadband-forum.org/technical/download/TR-355_Corrigendum-2.pdf) YANG Modules for FTTdp Management
*Tag: [v1.0.2-TR-355c2](https://github.com/BroadbandForum/yang/tree/v1.0.2-TR-355c2)*
Various corrections to existing modules and sub-modules. Some of these corrections are not fully backwards compatible.
### 2017-05-08: [TR-383](https://www.broadband-forum.org/technical/download/TR-383.pdf) Common YANG Modules for Access Networks
*Tag: [v2.0.0-TR-383](https://github.com/BroadbandForum/yang/tree/v2.0.0-TR-383)*
TR-383 defines YANG data models for the management of Broadband Forum specified access network equipment used across many deployment scenarios. Broadband Forum-specified access network equipment comprises Access Nodes and FTTdp DPUs. There is no assumption for BBF YANG modules to apply globally, e.g. to apply to access network equipment other than BBF Access Nodes and FTTdp DPUs, or to apply to core network equipment.
TR-383 YANG data models cover the following common areas (see [TR-383](https://www.broadband-forum.org/technical/download/TR-383.pdf) for a full listing of modules and submodules):
* DHCP
* Equipment
* Ethernet
* Layer 2 forwarding
* Interfaces
* PPPoE
* QoS
* Sub-interfaces
* Subscribers
* Types
Where appropriate, these YANG modules augment IETF YANG modules.
### 2017-05-05: [WT-385_draft1] ITU-T PON YANG Modules
*Tags: [v2.0.0-WT-383-draft1](https://github.com/BroadbandForum/yang/tree/v2.0.0-WT-383-draft1), [v3.0.0-WT-385-draft1](https://github.com/BroadbandForum/yang/tree/v3.0.0-WT-385-draft1)*
Full [WT-385_draft1] release (including documentation) plus partial [WT-383_draft1] (Common YANG Modules for Access Networks) release (only what's needed by WT-385).
WT-385 YANG modules in the [draft/interface](draft/interface) directory:
* [bbf-fiber.yang](draft/interface/bbf-fiber.yang): This is the main module.
* [bbf-fiber-if-type.yang](draft/interface/bbf-fiber-if-type.yang): This module defines xPON interface types, including channelgroup, channelpartition, channelpair and channeltermination.
* [bbf-fiber-types.yang](draft/interface/bbf-fiber-types.yang): This module defines identities and data types used by the xPON YANG Modules.
* [bbf-link-table-body.yang](draft/interface/bbf-link-table-body.yang): This module defines a generic link table where each entry links two IETF interfaces. The link relations are used horizontally between the counterpart interfaces on the OLT and the ONU in Combined-NE mode.
[WT-383_draft1]: https://www.broadband-forum.org/software#WT-383_draft1
[WT-385_draft1]: https://www.broadband-forum.org/software#WT-385_draft1
### 2017-03-13: [TR-355c1](https://www.broadband-forum.org/technical/download/TR-355_Corrigendum-1.pdf) YANG Modules for FTTdp Management
*Tag: [v1.0.1-TR-355c1](https://github.com/BroadbandForum/yang/tree/v1.0.1-TR-355c1)*
Various corrections to existing modules and sub-modules. Some of these corrections are not fully backwards compatible.
### 2016-07-18: [TR-355](https://www.broadband-forum.org/technical/download/TR-355.pdf) YANG Modules for FTTdp Management
*Tag: [v1.0.0-TR-355](https://github.com/BroadbandForum/yang/tree/v1.0.0-TR-355)*
TR-355 YANG modules in the [standard/interface](standard/interface) directory:
* [bbf-fastdsl](standard/interface/bbf-fastdsl.yang): This module contains a collection of YANG definitions for an interface which may support one or more DSL or G.fast technologies.
* [bbf-fast](standard/interface/bbf-fast.yang): This module contains a collection of YANG definitions for managing G.fast lines.
* [bbf-vdsl](standard/interface/bbf-vdsl.yang): This module contains a collection of YANG definitions for managing VDSL and DSL lines.
* [bbf-ghs](standard/interface/bbf-ghs.yang): This module contains a collection of YANG definitions for managing G.handshake (ITU-T G.994.1).
* [bbf-melt](standard/interface/bbf-melt.yang): This module contains a collection of YANG definitions for managing Metallic Line Test (MELT) (ITU-T G.996.2).
* [bbf-selt](standard/interface/bbf-selt.yang): This module contains a collection of YANG definitions for managing Single Ended Line Test (SELT) (ITU-T G.996.2).
TR-355 YANG modules in the [standard/common](standard/common) directory:
* [bbf-yang-types](standard/common/bbf-yang-types.yang): This module contains a collection of YANG definitions for common types used throughout Broadband Forum defined modules.
<file_sep># libnetconf2 - NETCONF agent library
#
include(third_party)
bcm_make_debug_option(NETCONF_TOOLS_FROM_DEVEL BOOL "Take netopeer2, sysrepo, libyang and libnetconf2 from devel" n)
bcm_make_normal_option(NETOPEER2_VERSION_2X BOOL "Use libyang,sysrepo,libnetconf2,netopeer2 v2.x packages" n)
if(NETCONF_TOOLS_FROM_DEVEL)
set(_VERSION "devel")
elseif(NETOPEER2_VERSION_2X)
set(_VERSION "2.0.1")
else()
set(_VERSION "1.1.46")
endif()
bcm_3rdparty_module_name(libnetconf2 ${_VERSION})
if("${LIBNETCONF2_VERSION}" STREQUAL "devel")
bcm_3rdparty_download_wget("https://github.com/CESNET/libnetconf2/archive" "devel.tar.gz" "libnetconf2-devel")
else()
bcm_3rdparty_download_wget("https://github.com/CESNET/libnetconf2/archive" "v${LIBNETCONF2_VERSION}.tar.gz")
endif()
bcm_3rdparty_add_dependencies(libyang libssh openssl libgcrypt)
bcm_3rdparty_add_build_options(-DENABLE_BUILD_TESTS=OFF -DENABLE_VALGRIND_TESTS=OFF)
bcm_3rdparty_add_build_options(-DENABLE_SSH=ON -DENABLE_TLS=ON)
bcm_3rdparty_build_cmake()
bcm_3rdparty_export()
<file_sep># This file contains the macros needed for adding 'make' options. These are translated to CMake options
# on invocation of a build. They are also tracked so they can be parsed for the 'make help' target.
# These must be included before the first options are added.
#====
# Only add the included definitions if this file has not been previously included. We check this by looking
# for the custom target, 'help_params'.
#====
if(TARGET help_params)
return()
endif()
#====
# Define the different option classifications we can have. We use this to loop through settings. If adding
# more option types, you will also need to add additional macros (i.e. bcm_make_<option type>_option) for
# those new types.
#====
set(_OPTION_TYPES NORMAL DEBUG)
#====
# Macro to add a Make/CMake option with a default value and description. There must be one of these for
# each of the entries in _OPTION_TYPES, since we can't iterate to create macros.
#
# @param VAR [in] Variable to set
# @param TYPE [in] Variable type, can be "BOOL, FILEPATH, PATH, STRING"
# @param DESCRIPTION [in] Description string for the variable
# @param VALUE [in] Value(s) to set
#====
macro(bcm_make_normal_option VAR TYPE DESCRIPTION VALUE)
_bcm_make_add_option(NORMAL ${VAR} ${TYPE} ${DESCRIPTION} ${VALUE})
endmacro(bcm_make_normal_option)
macro(bcm_make_debug_option VAR TYPE DESCRIPTION VALUE)
_bcm_make_add_option(DEBUG ${VAR} ${TYPE} ${DESCRIPTION} ${VALUE})
endmacro(bcm_make_debug_option)
#====
# PRIVATE: Macro to set the cache vale and record the type and descripton. The type and description lists in the
# cache provide the information for the 'make help' parameter dump.
#
# @param OPTION_TYPE [in] Type of option this is (DEBUG|NORMAL)
# @param VAR [in] Variable to set
# @param TYPE [in] Variable type, can be "BOOL, FILEPATH, PATH, STRING"
# @param DESCRIPTION [in] Description string for the variable
# @param VALUE [in] Value(s) to set
#====
macro(_bcm_make_add_option OPTION_TYPE VAR TYPE DESCRIPTION VALUE)
# Set the option in the cache
set(${VAR} ${VALUE} CACHE ${TYPE} ${DESCRIPTION})
# Record the information in the cache for the 'make help'
set(BCM_${OPTION_TYPE}_OPTIONS
${BCM_${OPTION_TYPE}_OPTIONS} ${VAR}
CACHE STRING "${OPTION_TYPE} make options list" FORCE)
set(BCM_${OPTION_TYPE}_DESCRIPTIONS
${BCM_${OPTION_TYPE}_DESCRIPTIONS} ${DESCRIPTION}
CACHE STRING "${OPTION_TYPE} make option description list" FORCE)
endmacro(_bcm_make_add_option)
#====
# Iterate over the _OPTION_TYPES to clear the current cache values and create the help targets.
# The help targets provide the parameter dump and are run either at the top of the build tree or
# from the Makefile wrapper.
#====
unset(HELP_PARAMS_TARGET_LIST)
foreach(_OPTION_TYPE ${_OPTION_TYPES})
string(TOLOWER ${_OPTION_TYPE} _OPTION_TYPE_LC)
unset(BCM_${_OPTION_TYPE}_OPTIONS CACHE)
unset(BCM_${_OPTION_TYPE}_DESCRIPTIONS CACHE)
# Create help targets for the 'make' options available
add_custom_target(help_${_OPTION_TYPE_LC}_params
COMMAND python ${CMAKE_CURRENT_SOURCE_DIR}/cmake/scripts/find_options.py
${_OPTION_TYPE_LC} ${CMAKE_CURRENT_BINARY_DIR})
list(APPEND HELP_PARAMS_TARGET_LIST help_${_OPTION_TYPE_LC}_params)
endforeach(_OPTION_TYPE)
#====
# Help target that will execute all the option type helps.
#====
add_custom_target(help_params
DEPENDS ${HELP_PARAMS_TARGET_LIST})
<file_sep>/*
<:copyright-BRCM:2016-2019:Apache:standard
Copyright (c) 2016-2019 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
* :>
*/
#ifndef BCMOLT_CONFIG_H_
#define BCMOLT_CONFIG_H_
/** \defgroup config Configuration Constants
* Configuration constants that must be revised by customer
* @{
*/
/** CPU Endianness. Must be set to BCMOS_ENDIAN_BIG or BCMOS_ENDIAN_LITTLE. */
#ifndef BCM_CPU_ENDIAN
#error BCM_CPU_ENDIAN must be set BCMOS_ENDIAN_BIG or BCMOS_ENDIAN_LITTLE
#endif /* #ifndef BCM_CPU_ENDIAN */
/** Broadcom MAC device type from bcm_mac_device_type.
* If set BCM_MAC_DEVICE_TYPE_UNKNOWN, device type is identified automatically at run time
*/
#define BCM_MAC_DEVICE_TYPE BCM_MAC_DEVICE_TYPE_UNKNOWN
/**
* System topology configuration
*/
/** Max number of line cards controlled by API layer.
* - if application is ON the line card, it controls only this line card and BCM_MAX_LINE_CARDS should be 1
* - If application is remote, it can control multiple line cards. In this case BCM_MAX_LINE_CARDS can be >1
*/
#define BCM_MAX_LINE_CARDS 1
/** Max number of MAC devices per line card */
#define BCM_MAX_DEVS_PER_LINE_CARD 2
/** Max number of MAC devices per OLT
* - Set =BCM_MAX_DEVS_PER_LINE_CARD for Full line card mode
* - Set =1 for Maple backward compatibility mode
* - Set to some other number for PON-level line card slicing
*/
#define BCM_MAX_DEVS_PER_OLT BCM_MAX_DEVS_PER_LINE_CARD
/** Max number of MAC devices globally (on all controlled line cards) */
#define BCM_MAX_DEVS (BCM_MAX_LINE_CARDS * BCM_MAX_DEVS_PER_LINE_CARD)
/** Max number of OLTs per line card
* - Set =1 for full line card mode
* - Set =BCM_MAX_DEVS_PER_LINE_CARD for Maple backward compatibility mode
* - Set to some other number for PON-level line card slicing
*/
#define BCM_MAX_OLTS_PER_LINE_CARD BCM_MAX_DEVS_PER_LINE_CARD
/** Max number of OLTs controlled by API layer.
* An OLT can manage 0 or 1 switch device and 1 to BCM_MAX_DEVS_PER_OLT number of MAC devices.
* - Full line card is mode is a single switch and 1 to BCM_MAX_DEVS_PER_OLT MAC devices.
* - MAC only mode no switch and 1 to BCM_MAX_DEVS_PER_OLT MAC devices
* - Maple backward compatibility mode is no switch and 1 MAC device.
* In this case there is an OLT object per MAC device
*/
#define BCM_MAX_OLTS (BCM_MAX_LINE_CARDS * BCM_MAX_OLTS_PER_LINE_CARD)
/** Max number of PON interfaces per device */
#define BCM_MAX_PONS_PER_DEV 16
/** Max number of PON interfaces per line card */
#define BCM_MAX_PONS_PER_LINE_CARD (BCM_MAX_DEVS_PER_LINE_CARD * BCM_MAX_PONS_PER_DEV)
/** Max number of PON interfaces per OLT */
#define BCM_MAX_PONS_PER_OLT (BCM_MAX_DEVS_PER_OLT * BCM_MAX_PONS_PER_DEV)
/** Max number of applications that can communicate with transport MUX simultaneously */
#define BCM_MAX_CLIENTS 8
/** Max number of NNI interfaces configurable in Switch */
/** @note need to allow config of Inband ports (upto 4 ports typically) after max network NNIs of 16 ports.
* Since for Switch, Inband ports are considered as part of NNI ports (though not network facing),
* the max define should accommodate that.
* Also note, BAL software still allows only 16 NNI network facing ports to be configured.
*/
#define BCM_MAX_NNI_PER_OLT (BCM_MAX_NETWORK_NNI_PER_OLT + BCM_MAX_NIC_NNI_PER_OLT)
/** Max number of network facing NNIs configurable in Switch */
#define BCM_MAX_NETWORK_NNI_PER_OLT 16
/** @note This defines the max physical NIC interfaces that might be available on the OLT. */
#define BCM_MAX_NIC_NNI_PER_OLT 4
/** Max number of Internal NNI interfaces per OLT */
#define BCM_MAX_INNI_PER_OLT 32
/** Max BAL startup time */
#define BCM_BAL_STARTUP_TIMEOUT 80000000 /* 80s */
/**
* Transport layer configuration defaults.
* Usually there is no need to modify any of those constants
*/
/** Transport layer configuration defaults */
/* ToDo: remove BCMTR_MAX_OLTS (currently it is being used by dev agent ut) */
#define BCMTR_MAX_OLTS BCM_MAX_OLTS /**< Max number of OLTs */
#define BCMTR_MSG_TIMEOUT 1000 /**< Max time to wait for response or next message part (ms) */
#define BCMTR_MAX_REQUESTS 64 /**< Max number of outstanding requests per application per OLT */
#define BCMTR_MAX_AUTOS 256 /**< Maximum number of simultaneous multi-part autonomous messages */
#define BCMTR_MAX_FRAGMENTS 1000 /**< Maximum number of fragments per message */
#define BCMTR_MSG_WAIT_MS 5 /**< length of time to wait on conn read */
#define BCMTR_MSG_READY_MS 50 /**< Time to wait for application to peak up response */
#define BCMTR_MAX_MTU_SIZE 1450 /**< max MTU size (must leave >50 bytes of room for L2+UDP+IP header) */
#define BCMTR_RX_THREAD_STACK 0 /**< Rx thread stack size. 0=system default */
#define BCMTR_TIMEOUT_THREAD_STACK 0 /**< Timeout thread stack size. 0=system default */
#define BCMTR_MAX_DEVICES BCM_MAX_DEVS /**< Max number of MAC devices supported by the transport layer */
#define BCMTR_MAX_INSTANCES BCM_MAX_PONS_PER_DEV /**< Max number of message handler instances - typically a number of PON's */
/** UDP transport plugic: default configuration */
#define BCMTR_TR_TYPE BCMTR_TYPE_UDP /**< Default transport type: raw/udp */
#define BCMTR_TR_UDP_HOST_IP 0x7f000001
#define BCMTR_TR_UDP_OLT_IP 0x7f000001
#define BCMTR_TR_UDP_HOST_PORT 0x4000
#define BCMTR_TR_UDP_OLT_PORT 0x4010
/** Debug output configuration */
#define BCM_DBG_MAX_MSG_SIZE 128 /**< Max number of message bytes to include in message dump */
#define BCMTR_BUF_EXTRA_HEADROOM 64 /**< Extra headroom to reserve in system buffer */
#define BCMTR_PCIE_START_TIMEOUT 30000 /**< Application start timeout (ms) */
#define BCMTR_PCIE_CONNECT_TIMEOUT 15000 /**< Connect timeout (ms) */
/** @} */
#define BCMTR_MAX_RXQ_SIZE 256
#endif /* BCMOLT_CONFIG_H_ */
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#include <tr451_polt_vendor.h>
#include <tr451_polt_for_vendor.h>
#include <tr451_polt_vendor_specific.h>
#include <sim_tr451_polt_vendor_internal.h>
#define TR451_POLT_DEFAULT_LISTEN_FROM_ONU_SIM_PORT 50500
static uint8_t inject_buffer[44];
/* Inject OMCI_RX packet */
static bcmos_errno polt_cli_inject_omci_rx(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t nparms)
{
const char *cterm_name = (const char *)parm[0].value.string;
uint16_t onu_id = (uint16_t)parm[1].value.unumber;
sim_tr451_vendor_packet_received_from_onu(cterm_name, onu_id,
inject_buffer,
bcmolt_buf_get_used(&parm[2].value.buffer));
/* Clear buffer for the next iteration */
memset(inject_buffer, 0, sizeof(inject_buffer));
return BCM_ERR_OK;
}
/*Inject OMCI_TX packet to ONU*/
static bcmos_errno polt_cli_inject_omci_tx(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t nparms)
{
bcmos_errno err;
OnuHeader *header = new OnuHeader();
header->set_chnl_term_name(parm[0].value.string);
header->set_onu_id(parm[1].value.unumber);
OmciPacket *grpc_omci_packet = new OmciPacket();
grpc_omci_packet->set_allocated_header(header);
grpc_omci_packet->set_payload(inject_buffer, sizeof(inject_buffer));
err = tr451_vendor_omci_send_to_onu(*grpc_omci_packet);
if (err != BCM_ERR_OK)
{
grpc::Status status = tr451_bcm_errno_grpc_status(err,
"Failed to send OMCI message to ONU %s:%u. Error '%s'",
grpc_omci_packet->header().chnl_term_name().c_str(), grpc_omci_packet->header().onu_id(),
bcmos_strerror(err));
BCM_POLT_LOG(ERROR, "%s:\n", status.error_message().c_str());
return BCM_ERR_IO;
}
BCM_POLT_LOG(DEBUG, "Sent OMCI message to ONU %s:%u. %lu bytes\n",
grpc_omci_packet->header().chnl_term_name().c_str(), grpc_omci_packet->header().onu_id(),
grpc_omci_packet->payload().length());
return BCM_ERR_OK;
}
/* Add ONU */
static bcmos_errno polt_cli_onu_add(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t nparms)
{
const char *cterm_name = (const char *)parm[0].value.string;
uint16_t onu_id = (uint16_t)parm[1].value.unumber;
const char *vendor_id = (const char *)parm[2].value.string;
uint32_t vendor_specific = (uint32_t)parm[3].value.unumber;
xpon_onu_presence_flags flags = (xpon_onu_presence_flags)parm[4].value.unumber;
tr451_polt_onu_serial_number serial_number = {};
strncpy((char *)&serial_number.data[0], vendor_id, sizeof(serial_number));
serial_number.data[4] = (vendor_specific >> 24) & 0xff;
serial_number.data[5] = (vendor_specific >> 16) & 0xff;
serial_number.data[6] = (vendor_specific >> 8) & 0xff;
serial_number.data[7] = vendor_specific & 0xff;
return sim_tr451_vendor_onu_added(cterm_name, onu_id, &serial_number, flags);
}
/* Delete ONU */
static bcmos_errno polt_cli_onu_delete(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t nparms)
{
const char *cterm_name = (const char *)parm[0].value.string;
uint16_t onu_id = (uint16_t)parm[1].value.unumber;
const char *vendor_id = (const char *)parm[2].value.string;
uint32_t vendor_specific = (uint32_t)parm[3].value.unumber;
xpon_onu_presence_flags flags = (xpon_onu_presence_flags)parm[4].value.unumber;
tr451_polt_onu_serial_number serial_number = {};
strncpy((char *)&serial_number.data[0], vendor_id, sizeof(serial_number));
serial_number.data[4] = (vendor_specific >> 24) & 0xff;
serial_number.data[5] = (vendor_specific >> 16) & 0xff;
serial_number.data[6] = (vendor_specific >> 8) & 0xff;
serial_number.data[7] = vendor_specific & 0xff;
return sim_tr451_vendor_onu_removed(cterm_name, onu_id, &serial_number, flags);
}
/* Set Rx handling mode */
static bcmos_errno polt_cli_set_rx_mode(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t nparms)
{
tr451_polt_sim_rx_cfg rx_cfg = {};
rx_cfg.mode = (tr451_polt_sim_rx_mode)parm[0].value.number;
switch (rx_cfg.mode)
{
case TR451_POLT_SIM_RX_MODE_DISCARD:
break;
case TR451_POLT_SIM_RX_MODE_LOOPBACK:
rx_cfg.loopback.skip = (uint32_t)parm[1].value.unumber;
break;
case TR451_POLT_SIM_RX_MODE_ONU_SIM:
rx_cfg.onu_sim.remote_address = (uint32_t)parm[1].value.unumber;
rx_cfg.onu_sim.remote_port = (uint16_t)parm[2].value.unumber;
rx_cfg.onu_sim.local_port = (uint16_t)parm[3].value.unumber;
break;
}
return sim_tr451_vendor_rx_cfg_set(&rx_cfg);
}
bcmos_errno tr451_vendor_cli_init(bcmcli_entry *dir)
{
static bcmcli_enum_val onu_flags_table[] = {
{ .name = "expected", .val=XPON_ONU_PRESENCE_FLAG_V_ANI },
{ .name = "present", .val=XPON_ONU_PRESENCE_FLAG_ONU },
{ .name = "in_o5", .val=XPON_ONU_PRESENCE_FLAG_ONU_IN_O5 },
{ .name = "activation_failed", .val=XPON_ONU_PRESENCE_FLAG_ONU_ACTIVATION_FAILED },
BCMCLI_ENUM_LAST
};
/* Add ONU */
{
static bcmcli_cmd_parm cmd_parms[] = {
BCMCLI_MAKE_PARM("channel_term", "Channel termination name", BCMCLI_PARM_STRING, 0),
BCMCLI_MAKE_PARM("onu_id", "onu_id", BCMCLI_PARM_NUMBER, 0),
BCMCLI_MAKE_PARM("serial_vendor_id", "serial_number: 4 bytes ASCII vendor id", BCMCLI_PARM_STRING, 0),
BCMCLI_MAKE_PARM("serial_vendor_specific", "serial_number: vendor-specific id", BCMCLI_PARM_HEX, 0),
BCMCLI_MAKE_PARM_ENUM_MASK_DEFVAL("flags", "notification flags", onu_flags_table, 0, "expected+present+in_o5"),
{ 0 }
} ;
bcmcli_cmd_add(dir, "onu_add", polt_cli_onu_add, "Add ONU",
BCMCLI_ACCESS_ADMIN, NULL, cmd_parms);
}
/* Delete ONU */
{
static bcmcli_cmd_parm cmd_parms[] = {
BCMCLI_MAKE_PARM("channel_term", "Channel termination name", BCMCLI_PARM_STRING, 0),
BCMCLI_MAKE_PARM("onu_id", "onu_id", BCMCLI_PARM_NUMBER, 0),
BCMCLI_MAKE_PARM("serial_vendor_id", "serial_number: 4 bytes ASCII vendor id", BCMCLI_PARM_STRING, 0),
BCMCLI_MAKE_PARM("serial_vendor_specific", "serial_number: vendor-specific id", BCMCLI_PARM_HEX, 0),
BCMCLI_MAKE_PARM_ENUM_MASK_DEFVAL("flags", "notification flags", onu_flags_table, 0, "expected"),
{ 0 }
} ;
bcmcli_cmd_add(dir, "onu_delete", polt_cli_onu_delete, "Delete ONU",
BCMCLI_ACCESS_ADMIN, NULL, cmd_parms);
}
/* Inject proxy_rx */
{
static bcmcli_cmd_parm inject_parms[] = {
BCMCLI_MAKE_PARM("channel_term", "Channel termination name", BCMCLI_PARM_STRING, 0),
BCMCLI_MAKE_PARM("onu", "ONU", BCMCLI_PARM_NUMBER, 0),
BCMCLI_MAKE_PARM("data", "OMCI packet without MIC", BCMCLI_PARM_BUFFER, 0),
{ 0 } } ;
inject_parms[2].value.buffer.len = sizeof(inject_buffer);
inject_parms[2].value.buffer.start = inject_parms[2].value.buffer.curr = inject_buffer;
bcmcli_cmd_add(dir, "inject", polt_cli_inject_omci_rx,
"Inject OMCI packet received from ONU", BCMCLI_ACCESS_ADMIN, NULL, inject_parms);
}
/* Inject proxy_tx */
{
static bcmcli_cmd_parm inject_parms[] = {
BCMCLI_MAKE_PARM("channel_term", "Channel termination name", BCMCLI_PARM_STRING, 0),
BCMCLI_MAKE_PARM("onu", "ONU", BCMCLI_PARM_NUMBER, 0),
BCMCLI_MAKE_PARM("data", "OMCI packet without MIC", BCMCLI_PARM_BUFFER, 0),
{ 0 } } ;
inject_parms[2].value.buffer.len = sizeof(inject_buffer);
inject_parms[2].value.buffer.start = inject_parms[2].value.buffer.curr = inject_buffer;
bcmcli_cmd_add(dir, "inject_onu", polt_cli_inject_omci_tx,
"Inject OMCI packet received from vOMCI", BCMCLI_ACCESS_ADMIN, NULL, inject_parms);
}
/* Set Rx handling mode */
{
static bcmcli_cmd_parm loopback_parms[] = {
BCMCLI_MAKE_PARM("skip", "Acknowledge 1 packet per skip+1 requests with AR=1", BCMCLI_PARM_NUMBER, 0),
{ 0 } } ;
static bcmcli_cmd_parm onu_sim_parms[] = {
BCMCLI_MAKE_PARM("onu_sim_ip", "ONU simulator IP address", BCMCLI_PARM_IP, 0),
BCMCLI_MAKE_PARM("onu_sim_port", "ONU simulator UDP port", BCMCLI_PARM_NUMBER, 0),
BCMCLI_MAKE_PARM("local_udp_port", "Optional local UDP port", BCMCLI_PARM_NUMBER, BCMCLI_PARM_FLAG_DEFVAL),
{ 0 } } ;
onu_sim_parms[2].value.number = TR451_POLT_DEFAULT_LISTEN_FROM_ONU_SIM_PORT;
static bcmcli_enum_val rx_mode_enum_table[] = {
{ .name = "discard", .val = (long)TR451_POLT_SIM_RX_MODE_DISCARD },
{ .name = "loopback", .val = (long)TR451_POLT_SIM_RX_MODE_LOOPBACK, .parms = loopback_parms },
{ .name = "onu_sim", .val = (long)TR451_POLT_SIM_RX_MODE_ONU_SIM , .parms = onu_sim_parms },
BCMCLI_ENUM_LAST
};
static bcmcli_cmd_parm cmd_parms[] = {
BCMCLI_MAKE_PARM("mode", "RX handling mode", BCMCLI_PARM_ENUM, BCMCLI_PARM_FLAG_SELECTOR),
{ 0 }
} ;
cmd_parms[0].enum_table = rx_mode_enum_table;
bcmcli_cmd_add(dir, "rx_mode", polt_cli_set_rx_mode, "Set Receive handling mode",
BCMCLI_ACCESS_ADMIN, NULL, cmd_parms);
}
return BCM_ERR_OK;
}
<file_sep>/*
<:copyright-BRCM:2016-2019:Apache:standard
Copyright (c) 2016-2019 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
* :>
*/
/*
* bcmos_sysif.h
*
* This internal header file includes OS-specific services
* that are referred in OS-independent OS abstraction implementation
*
*/
#ifndef BCMOS_SYSIF_H_
#define BCMOS_SYSIF_H_
/*
* OS-specific init
*/
/** Initialize system library
* Must be called before any other system function
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_sys_init(void);
/** Clean-up system library
*/
void bcmos_sys_exit(void);
/*
* Timer support
*/
/* OS abstraction must define struct bcmos_sys_timer
*/
typedef struct bcmos_sys_timer bcmos_sys_timer;
/* System timer handler. Implemented in common OS abstraction services */
typedef void (*bcmos_sys_timer_handler)(void *data);
/* Create system timer
* It is expected that only one high-resolution system timer is needed.
* It is used to "kick" timer pool implemented in OS abstraction
* \param[in] timer System timer
* \param[in] handler Timer handler
* \param[in] data Data to be passed to the handler
* \returns 0 if OK or error < 0
*/
bcmos_errno bcmos_sys_timer_create(bcmos_sys_timer *timer, bcmos_sys_timer_handler handler, void *data);
/* Destroy system timer
* \param[in] timer System timer
*/
void bcmos_sys_timer_destroy(bcmos_sys_timer *timer);
/* Start system timer
* \param[in] timer System timer
* \param[in] interval Interval (us)
*/
void bcmos_sys_timer_start(bcmos_sys_timer *timer, uint32_t interval);
/* Stop system timer
* \param[in] timer System timer
*/
void bcmos_sys_timer_stop(bcmos_sys_timer *timer);
#endif /* BCMOS_SYSIF_H_ */
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#ifndef BCMOS_HASH_TABLE_H_
#define BCMOS_HASH_TABLE_H_
#include "bcmos_system.h"
typedef struct ht_block ht_block;
struct ht_block
{
ht_block *next_chain;
};
typedef struct
{
uint16_t obj_len;
uint8_t key_len;
uint32_t data_offset;
uint32_t ht_lookup_tbl_entries;
uint32_t ht_max_data_entries;
bcmos_blk_pool key_data_pool;
ht_block *look_up_entries_tbl;
uint32_t ht_cur_entries;
} hash_table;
typedef struct
{
const hash_table *ht;
uint32_t cur_idx;
ht_block *cur_block;
bcmos_bool removed_at;
bcmos_bool still_valid;
} ht_iterator;
/** Create a hash table
* \param[in] max_data_entries Maximum entries the hash table needs to hold
* \param[in] entry_size Size of each entry in bytes
* \param[in] key_size Size of each key in bytes
* \param[in] pool_name Friendly name to identify the hash table's memory pool
* \return pointer to newly created hash table
*/
hash_table *hash_table_create(uint32_t max_data_entries,
uint16_t entry_size,
uint8_t key_size,
char *pool_name);
/** Removes all entries from a HashTable.
* \param[in] ht Hash table to remove all entries from
*/
void hash_table_clear(hash_table *ht);
/** Gets a pointer to an entry within the hash table (if exists)
* \param[in] ht Hashtable in question
* \param[in] key Key to look for.
* \return Non null if we found a data item associated with KEY.
*/
void *hash_table_get(const hash_table *ht, const uint8_t *key);
/** Returns pointers to the key and value that an iterator is pointing at. Warning: key may not be uint32_t aligned.
* DO NOT DELETE THE ELEMENT THE ITERATOR POINTS AT AND AND TRY TO USE THE ITERATOR SUBSEQUENTLY. If you need to do
* this use ht_iterator_remove_at
* \param[in] hti Iterator
* \param[in] key Pointer to key to fill
* \param[in] obj Pointer to obj to fill.
*/
void ht_iterator_deref(const ht_iterator *hti, uint8_t **key, void **obj);
/** Get an interator for traversing a hashtable.
* \param[in] ht Hashtable to traverse
* \return The iterator.
*/
ht_iterator ht_iterator_get(const hash_table *ht);
/** Get an interator for traversing a hashtable based on an entry's key.
* \param[in] ht Hashtable to traverse
* \param[in] key key of entry to return
* \return The iterator.
*/
ht_iterator ht_iterator_get_by_key(const hash_table *ht, const uint8_t *key);
/** Advances a HashTable iterator to the next location within the HashTable.
* \param[in] it Iterator to advance
* \return TRUE if there was a next element
*/
bcmos_bool ht_iterator_next(ht_iterator *it);
/** Deletes the entry where the iterator points to and advances the iterator returning whether the advance worked or
* not.
* \param[in] ht Writable reference to the hash table (the iterator only has read permission)
* \param[in] it Itreator pointing at entry to delete.
*/
void ht_iterator_remove_at(hash_table *ht, ht_iterator *it);
/** Attempts to associate key with val in the hash table. If key already exists overwrites what was at key with val.
* Otherwise allocates an entry within the hashtable for key and copies val into it.
* \param[in] ht Hashtable to add or modify
* \param[in] key Key to try and associate with val.
* \param[in] val Val to associate
* \return NULL if fail, else pointer to just added block.
*/
void *hash_table_put(hash_table *ht, const uint8_t *key, const void *val);
/** Removes an entry (if exists) from the hash table.
* \param[in] ht HashTable to remove from.
* \param[in] key Key to remove
* \return BCMOS_TRUE if anything was removed, otherwise BCMOS_FALSE.
*/
bcmos_bool hash_table_remove(hash_table *ht, const uint8_t *key);
/** Deletes a hash table entirely, freeing all memory.
* \param[in] ht Hash table to delete
*/
void hash_table_delete(hash_table *ht);
#endif /* Hash.h */
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#include <fstream>
#include <tr451_polt_vendor.h>
#include <tr451_polt_for_vendor.h>
#include <tr451_polt_vendor_specific.h>
#include <sim_tr451_polt_vendor_internal.h>
#define OMCI_MAX_MTU 2048
static tr451_vendor_event_cfg vendor_event_cfg;
static tr451_polt_sim_rx_cfg vendor_rx_cfg;
static uint32_t vendor_rx_skipped;
static int tr451_onu_sim_socket;
static bcmos_bool tr451_onu_sim_rx_task_created;
static bcmos_task tr451_onu_sim_rx_task;
static char tr451_onu_sim_rx_buf[OMCI_MAX_MTU + sizeof(tr451_onu_sim_packet_header)];
static char tr451_onu_sim_tx_buf[OMCI_MAX_MTU + sizeof(tr451_onu_sim_packet_header)];
//
// Helper functions
//
/* Prepare onu_info */
static bcmos_errno tr451_prepare_onu_info(const char *cterm_name, uint16_t onu_id,
const tr451_polt_onu_serial_number *serial_number, tr451_polt_onu_info *onu_info)
{
if (vendor_event_cfg.tr451_onu_state_change_cb == nullptr)
{
BCM_POLT_LOG(ERROR, "No tr451_onu_state_change_cb registration\n");
return BCM_ERR_NOT_SUPPORTED;;
}
memset(onu_info, 0, sizeof(*onu_info));
onu_info->cterm_name = cterm_name;
onu_info->pon_interface_id = POLT_PON_ID_UNDEFINED;
onu_info->onu_id = onu_id;
if (onu_info->onu_id >= TR451_POLT_MAX_ONUS_PER_PON)
{
BCM_POLT_LOG(ERROR, "onu_id out of range\n");
return BCM_ERR_PARM;
}
memcpy(&onu_info->serial_number, serial_number, 8);
return BCM_ERR_OK;
}
/* Report ONU discovered */
bcmos_errno sim_tr451_vendor_onu_added(const char *cterm_name, uint16_t onu_id,
const tr451_polt_onu_serial_number *serial, xpon_onu_presence_flags flags)
{
tr451_polt_onu_info onu_info;
bcmos_errno err;
err = tr451_prepare_onu_info(cterm_name, onu_id, serial, &onu_info);
if (err != BCM_ERR_OK)
return err;
onu_info.presence_flags = flags ? flags : XPON_ONU_PRESENCE_FLAG_ONU;
vendor_event_cfg.tr451_onu_state_change_cb(vendor_event_cfg.user_handle, &onu_info);
if (vendor_event_cfg.tr451_onu_state_change_notify_cb != nullptr)
{
err = vendor_event_cfg.tr451_onu_state_change_notify_cb(vendor_event_cfg.user_handle, &onu_info);
}
return err;
}
/* Report ONU removed */
bcmos_errno sim_tr451_vendor_onu_removed(const char *cterm_name, uint16_t onu_id,
const tr451_polt_onu_serial_number *serial, xpon_onu_presence_flags flags)
{
tr451_polt_onu_info onu_info;
bcmos_errno err;
err = tr451_prepare_onu_info(cterm_name, onu_id, serial, &onu_info);
if (err != BCM_ERR_OK)
return err;
onu_info.presence_flags = flags ? flags : XPON_ONU_PRESENCE_FLAG_V_ANI;
vendor_event_cfg.tr451_onu_state_change_cb(vendor_event_cfg.user_handle, &onu_info);
if (vendor_event_cfg.tr451_onu_state_change_notify_cb != nullptr)
{
err = vendor_event_cfg.tr451_onu_state_change_notify_cb(vendor_event_cfg.user_handle, &onu_info);
}
return err;
}
/* Report packet received from ONU */
bcmos_errno sim_tr451_vendor_packet_received_from_onu(const char *cterm_name, uint16_t onu_id, const uint8_t *data, uint32_t length)
{
if (vendor_event_cfg.tr451_omci_rx_cb == nullptr)
return BCM_ERR_NOT_SUPPORTED;
if (cterm_name == nullptr || data == nullptr || length <= 4)
return BCM_ERR_PARM;
BCM_POLT_LOG(DEBUG, "RX from ONU: cterm=%s onu_id=%u length=%u OMCI_HDR=%02x%02x%02x%02x %02x%02x%02x%02x\n",
cterm_name, onu_id, length,
data[0], data[1], data[2], data[3],
data[4], data[5], data[6], data[7]);
OnuHeader* header = new OnuHeader();
header->set_chnl_term_name(cterm_name);
header->set_onu_id(onu_id);
OmciPacketEntry *grpc_packet = new OmciPacketEntry();
grpc_packet->set_allocated_header(header);
grpc_packet->set_payload(data, length);
vendor_event_cfg.tr451_omci_rx_cb(vendor_event_cfg.user_handle, grpc_packet);
return BCM_ERR_OK;
}
/* Send packet to ONU simulator */
static bcmos_errno tr451_vendor_omci_send_to_onu_sim(const OmciPacket &packet)
{
uint32_t length = packet.payload().length();
if (length > OMCI_MAX_MTU)
{
BCM_POLT_LOG(DEBUG, "TX to ONU: OMCI packet is too long %u. Discarded\n", length);
return BCM_ERR_OVERFLOW;
}
tr451_onu_sim_packet_header *hdr = (tr451_onu_sim_packet_header *)tr451_onu_sim_tx_buf;
strncpy(hdr->cterm_name, packet.header().chnl_term_name().c_str(), sizeof(hdr->cterm_name));
hdr->onu_id = htons(packet.header().onu_id());
memcpy((uint8_t *)(hdr + 1), packet.payload().c_str(), length);
int rc;
rc = send(tr451_onu_sim_socket, tr451_onu_sim_tx_buf, length + sizeof(tr451_onu_sim_packet_header), 0);
if (rc < 0)
{
BCM_POLT_LOG(DEBUG, "TX to ONU: failed to send. Error '%s'\n", strerror(errno));
return BCM_ERR_IO;
}
return BCM_ERR_OK;
}
/*
* External interface
*/
/**
* @brief Initialize TR-451 vendor library
* @returns BCM_ERR_OK(0) or error code <0
*/
bcmos_errno tr451_vendor_init(void)
{
// Set loopback RX handling mode by default
tr451_polt_sim_rx_cfg rx_cfg = {};
rx_cfg.mode = TR451_POLT_SIM_RX_MODE_LOOPBACK;
return sim_tr451_vendor_rx_cfg_set(&rx_cfg);
}
/**
* @brief Terminate TR-451 vendor library
* @returns BCM_ERR_OK(0) or error code <0
*/
bcmos_errno tr451_vendor_exit(void);
/**
* @brief Send packet to ONU
* @note The function can be called for multiple ONUs simultaneously
* from different execution context. It is the responsibility of the
* implementer to make it thread-safe.
* @param[in] &packet: OMCI packet received from vOMCI peer
* @returns BCM_ERR_OK(0) or error code <0
*/
bcmos_errno tr451_vendor_omci_send_to_onu(const OmciPacket &packet)
{
bcmos_errno err = BCM_ERR_OK;
const string *p_payload = &packet.payload();
const uint8_t *data = (const uint8_t *)p_payload->c_str();
BCM_POLT_LOG(DEBUG, "TX to ONU: cterm=%s onu_id=%u length=%lu OMCI_HDR=%02x%02x%02x%02x %02x%02x%02x%02x\n",
packet.header().chnl_term_name().c_str(), packet.header().onu_id(), p_payload->length(),
data[0], data[1], data[2], data[3],
data[4], data[5], data[6], data[7]);
switch(vendor_rx_cfg.mode)
{
case TR451_POLT_SIM_RX_MODE_DISCARD:
break;
case TR451_POLT_SIM_RX_MODE_LOOPBACK:
{
string payload = packet.payload();
uint8_t msg_type = payload[2];
// If AR is not set - just return
if ((msg_type & 0x40) == 0)
break;
if (vendor_rx_skipped < vendor_rx_cfg.loopback.skip)
{
++vendor_rx_skipped;
break;
}
// Toggle AR/AK bit
msg_type &= ~0x40;
msg_type |= 0x20;
payload[2] = msg_type;
for (int i=8; i<48; i++)
payload[i] = 0;
err = sim_tr451_vendor_packet_received_from_onu(
packet.header().chnl_term_name().c_str(),
(uint16_t)packet.header().onu_id(),
(const uint8_t *)payload.c_str(),
payload.length());
vendor_rx_skipped = 0;
}
break;
case TR451_POLT_SIM_RX_MODE_ONU_SIM:
err = tr451_vendor_omci_send_to_onu_sim(packet);
break;
}
return err;
}
/* Receive task handler */
static int _onu_sim_rx_task_handler(long data)
{
bcmos_task *this_task = bcmos_task_current();
tr451_onu_sim_packet_header *hdr = (tr451_onu_sim_packet_header *)tr451_onu_sim_rx_buf;
fd_set read_fds;
struct timeval tv = {};
int rc;
// Poll with 100ms interval
tv.tv_usec = 100000;
while (!this_task->destroy_request)
{
FD_ZERO(&read_fds);
FD_SET(tr451_onu_sim_socket, &read_fds);
rc = select(tr451_onu_sim_socket + 1, &read_fds, NULL, NULL, &tv);
if (!rc)
continue;
if (rc < 0)
break;
/* Check for receive. The function waits for a short while and the times out */
rc = recv(tr451_onu_sim_socket, tr451_onu_sim_rx_buf, sizeof(tr451_onu_sim_rx_buf), 0);
if (rc < sizeof(tr451_onu_sim_packet_header))
break;
sim_tr451_vendor_packet_received_from_onu(hdr->cterm_name, ntohs(hdr->onu_id),
(uint8_t *)(hdr + 1), rc - sizeof(tr451_onu_sim_packet_header));
}
BCM_POLT_LOG(INFO, "ONU-SIM rx task terminated\n");
return 0;
}
/* Set receive handling mode */
bcmos_errno sim_tr451_vendor_rx_cfg_set(const tr451_polt_sim_rx_cfg *cfg)
{
if (cfg->mode == TR451_POLT_SIM_RX_MODE_ONU_SIM)
{
struct sockaddr_in addr = {};
bcmos_errno err;
tr451_onu_sim_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (tr451_onu_sim_socket < 0)
{
BCM_POLT_LOG(ERROR, "Can't create UDP socket\n");
return BCM_ERR_IO;
}
// bind
addr.sin_family = AF_INET;
addr.sin_port = htons(cfg->onu_sim.local_port);
if (bind(tr451_onu_sim_socket, (struct sockaddr *)&addr, sizeof(addr)) == -1)
{
BCM_POLT_LOG(ERROR, "Can't bind ONU-SIM socket to port %u. Error %s\n",
cfg->onu_sim.local_port, strerror(errno));
close(tr451_onu_sim_socket);
return BCM_ERR_IO;
}
// connect
addr.sin_family = AF_INET;
addr.sin_port = htons(cfg->onu_sim.remote_port);
addr.sin_addr.s_addr = htonl(cfg->onu_sim.remote_address);
if (connect(tr451_onu_sim_socket, (struct sockaddr *)&addr, sizeof(addr)) == -1)
{
BCM_POLT_LOG(ERROR, "Can't connect ONU-SIM socket to %d.%d.%d.%d:%u. Error %s\n",
(cfg->onu_sim.remote_address >> 24) & 0xff,
(cfg->onu_sim.remote_address >> 16) & 0xff,
(cfg->onu_sim.remote_address >> 8) & 0xff,
cfg->onu_sim.remote_address & 0xff,
cfg->onu_sim.remote_port, strerror(errno));
close(tr451_onu_sim_socket);
return BCM_ERR_IO;
}
// create RX task
bcmos_task_parm tp = {};
tp.name = "cm_rx",
tp.priority = TASK_PRIORITY_TRANSPORT_RX,
tp.handler = _onu_sim_rx_task_handler,
err = bcmos_task_create(&tr451_onu_sim_rx_task, &tp);
if (err != BCM_ERR_OK)
{
BCM_POLT_LOG(ERROR, "ONU-SIM RX task create failed: %s\n", bcmos_strerror(err));
close(tr451_onu_sim_socket);
return err;
}
tr451_onu_sim_rx_task_created = BCMOS_TRUE;
}
else
{
if (vendor_rx_cfg.mode == TR451_POLT_SIM_RX_MODE_ONU_SIM && tr451_onu_sim_rx_task_created)
{
close(tr451_onu_sim_socket);
bcmos_task_destroy(&tr451_onu_sim_rx_task);
tr451_onu_sim_rx_task_created = BCMOS_FALSE;
}
}
vendor_rx_skipped = 0;
vendor_rx_cfg = *cfg;
return BCM_ERR_OK;
}
/**
* @brief Register to receive OMCI packets
* @note
* @param[in] rx_cb: Receive callback function to be called when OMCI packet is received
* @param[in] *rx_cb_handle: Handle to pass to rx_cb
* @returns BCM_ERR_OK(0) or error code <0
*/
bcmos_errno tr451_vendor_event_register(const tr451_vendor_event_cfg *cb_cfg)
{
if (cb_cfg != nullptr)
{
vendor_event_cfg = *cb_cfg;
}
else
{
memset(&vendor_event_cfg, 0, sizeof(vendor_event_cfg));
}
return BCM_ERR_OK;
}
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#ifndef _BCMOLT_DAEMON_H_
#define _BCMOLT_DAEMON_H_
/**
* @file bcmolt_daemon.h
* @brief Service that enables running application in daemon mode
*/
#include <bcmos_system.h>
#include <pwd.h>
#define DAEMON_PID_FILE_SUFFIX "pid"
#define DAEMON_INIT_DONE_FILE_SUFFIX "init_done"
#define DAEMON_CLI_INPUT_FILE_SUFFIX "cli.input"
#define DAEMON_CLI_OUTPUT_FILE_SUFFIX "cli.output"
/** Daemon parameters */
typedef struct bcmolt_daemon_parms
{
const char *name; /**< Daemon name */
const char *descr; /**< Optional daemon descriptive string */
void (*terminate_cb)(void); /**< Optional terminate callback. Called as part of SIGINT, SIGTERM handling */
void (*restart_cb)(void); /**< Optional restart callback. Called as part of SIGHUP handling */
const char *path; /**< Optional path for daemon files. If NULL, /tmp is used by default */
bcmos_bool is_cli_support; /**< TRUE=create pipes for CLI support */
bcmos_bool is_global; /**< TRUE=only 1 instance is allowed per host. FALSE=allow 1 instance per user */
} bcmolt_daemon_parms;
/**
* @brief Daemonize application
* @param *parms: daemon parameters
* @return error status
*/
bcmos_errno bcmolt_daemon_start(const bcmolt_daemon_parms *parms);
/**
* @brief Indicate that application init is completed
* @return error status
*/
bcmos_errno bcmolt_daemon_init_completed(void);
/**
* @brief Terminate daemon
*/
void bcmolt_daemon_terminate(int exit_code);
/**
* @brief Check if application is already running. If application is NOT running,
* a special lock file is created that prevents another application instance from starting.
* @param *parms: daemon parameters
* @return BCMOS_TRUE if running
*/
bcmos_bool bcmolt_daemon_check_lock(const bcmolt_daemon_parms *parms);
/**
* @brief Get special file name
* @param[IN] *parms:
* @param[IN] *suffix:
* @param[OUT] *file_name:
* @param[IN] name_size:
* @retval file_name
*/
static inline char *bcmolt_daemon_file_name(const bcmolt_daemon_parms *parms, const char *suffix,
char *file_name, uint32_t name_size)
{
const char *path = parms->path ? parms->path : "/tmp";
if (parms->is_global)
snprintf(file_name, name_size, "%s/%s_%s", path, parms->name, suffix);
else
{
struct passwd *pw = getpwuid(geteuid());
snprintf(file_name, name_size, "%s/%s_%s_%s", path, pw ? pw->pw_name : "default", parms->name, suffix);
}
return file_name;
}
#endif
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#ifdef ENABLE_LOG
#include "bcm_dev_log_task.h"
#include "bcm_dev_log_task_internal.h"
#include "bcm_dev_log.h"
static bcmos_timer dev_log_timer;
/* Store timestamp per every rate-limited log ID. */
static uint64_t rate_limit_id2timestamp[DEV_LOG_RATE_LIMIT_ID__NUM_OF];
const char *dev_log_basename(const char *str)
{
const char *slash;
if ((slash = strchr(str, '/')))
{
const char *str0 = str;
str = strchr(slash+1, ' ');
/* If log format string was created by BCM_LOG macro and there is no corruption of some kind
* str above is guaranteed to be != NULL. However, making str!=NULL assumption makes dev_log
* vulnerable to bugs in the caller. In this case the following inexpensive check prevents crash
* in dev_Log and helps in identifying the real culprit.
*/
if (!str)
return str0;
while (str[0] != '/')
str--;
str++;
}
return str;
}
#ifdef TRIGGER_LOGGER_FEATURE
/* check if the message fits the level and the other criteria for a trigger
return 1 if yes, the message will be printed
and returns 0 if the message will not be printed
*/
static bcmos_bool check_trigger(dev_log_id_parm *id, bcm_dev_log_level log_level)
{
/* the level of the message must be exactly the trigger level */
if (id->trigger_log_level != log_level)
return BCMOS_FALSE; /* do not print the message - the level does not fit */
id->trigger.counter++;
if (id->trigger.counter >= id->trigger.start_threshold)
{
if (id->trigger.counter >= id->trigger.stop_threshold)
{
/* trigger finished, check repeat */
if (id->trigger.repeat_threshold)
{
id->trigger.repeat++;
if (id->trigger.repeat < id->trigger.repeat_threshold)
{
/* rewind trigger conditions */
id->trigger.counter = 0;
}
}
}
else /* trigger is active : counter greater than start and less than end */
return BCMOS_TRUE; /* print the message */
}
return BCMOS_FALSE;/* do not print the message - still less than start threshold */
}
/* check if the message fits the level and the criteria for throttle
return 1 if yes, the message will be printed
and returns 0 if the message will not be printed
*/
static bcmos_bool check_throttle(dev_log_id_parm *id, bcm_dev_log_level log_level)
{
/* check if any throttle is defined */
if (id->throttle_log_level != DEV_LOG_LEVEL_NO_LOG)
return BCMOS_TRUE; /* print the message - no trigger is set */
/* the level of the message must be exactly the throttle level */
if (id->throttle_log_level != log_level)
return BCMOS_FALSE; /* do not print the message - the level does not fit */
id->throttle.counter++;
if (id->throttle.counter >= id->throttle.threshold)
{
id->throttle.counter = 0;
return BCMOS_TRUE;
}
return BCMOS_FALSE;/* do not print the message - still less than start threshold */
}
#endif
#if defined(BCM_SUBSYSTEM_HOST)
static bcmos_mutex dev_log_lock;
#endif
void bcm_dev_log_frontend_init(void)
{
#if defined(BCM_SUBSYSTEM_HOST)
bcmos_mutex_create(&dev_log_lock, 0, "dev_log_lock");
#endif
}
static bcmos_timer_rc bcm_dev_log_msg_send_timer_cb(bcmos_timer *timer, long data)
{
bcmos_msg *msg = (bcmos_msg *)data;
bcmos_msg_send(&dev_log.save_queue, msg, BCMOS_MSG_SEND_AUTO_FREE);
return BCMOS_TIMER_OK;
}
uint8_t bcm_dev_log_pool_occupancy_percent_get(void)
{
bcmos_msg_pool_info msg_pool_info;
bcmos_errno error = bcmos_msg_pool_query(&dev_log.pool, &msg_pool_info);
if (error != BCM_ERR_OK)
{
DEV_LOG_ERROR_PRINTF("bcmos_msg_pool_query() returned %s (%d)\n", bcmos_strerror(error), error);
return 0;
}
return (uint8_t)((100 * (msg_pool_info.parm.size - msg_pool_info.stat.free)) / msg_pool_info.parm.size);
}
static bcmos_bool bcm_dev_log_should_drop(
dev_log_id_parm *id,
bcm_dev_log_level log_level,
uint32_t rate_us,
dev_log_rate_limit_id rate_limit_id)
{
/* If the msg pool is sufficiently full, drop all non-error messages */
if (!bcm_dev_log_level_is_error(log_level) &&
bcm_dev_log_pool_occupancy_percent_get() >= DEV_LOG_ERROR_ONLY_THRESHOLD_PERCENT)
{
bcm_dev_log_drop_report();
return BCMOS_TRUE;
}
#ifdef TRIGGER_LOGGER_FEATURE
/* if trigger defined - ignore throttle and printing level */
if (id->trigger_log_level != DEV_LOG_LEVEL_NO_LOG)
return check_trigger(id, log_level);
#endif
/* if trigger is not fullfilled - check other conditions */
if (log_level > id->log_level_print && log_level > id->log_level_save)
return BCMOS_TRUE;
#ifdef TRIGGER_LOGGER_FEATURE
if (!check_throttle(id, log_level))
return BCMOS_TRUE;
#endif
if (rate_us && rate_limit_id != DEV_LOG_RATE_LIMIT_ID_NONE)
{
uint64_t curr_timestamp;
/* Do rate limit. */
curr_timestamp = bcmos_timestamp64();
if (curr_timestamp - rate_limit_id2timestamp[rate_limit_id] < rate_us)
return BCMOS_TRUE; /* Filter out this message. */
rate_limit_id2timestamp[rate_limit_id] = curr_timestamp;
}
return BCMOS_FALSE;
}
#if defined(BCM_SUBSYSTEM_HOST)
/* The following functions might be used on the host side to make sure
that multiple log entries are "together",ie are not interleaved
with other log entries. It might be necessary if application needs to log
a very long string that must be split into multiple log entries.
*/
void bcm_dev_log_lock(void)
{
bcmos_mutex_lock(&dev_log_lock);
}
void bcm_dev_log_unlock(void)
{
bcmos_mutex_unlock(&dev_log_lock);
}
#endif /* #if defined(BCM_SUBSYSTEM_HOST) */
const char * last_format = NULL;
static void _bcm_dev_log_vlog(dev_log_id id,
bcm_dev_log_level log_level,
uint32_t flags,
uint32_t rate_us,
dev_log_rate_limit_id rate_limit_id,
const char *fmt,
va_list args)
{
dev_log_id_parm *parm = (dev_log_id_parm *)id;
dev_log_queue_msg *log_queue_msg;
bcmos_errno error = BCM_ERR_OK;
bcmos_msg *msg;
last_format = fmt;
if (dev_log.state != BCM_DEV_LOG_STATE_ENABLED)
{
if (dev_log.flags & BCM_DEV_LOG_FLAG_DISABLED_WITH_PRINTF)
DEV_LOG_VPRINTF(fmt, args);
return;
}
if (!id || (id == DEV_LOG_INVALID_ID))
{
/* If this ID was not registered - or registered incorrectly */
DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id);
DEV_LOG_VPRINTF(fmt, args); /* This will allow us to debug what line caused the bug. */
return;
}
if ((log_level >= DEV_LOG_LEVEL_NUM_OF) || (log_level == DEV_LOG_LEVEL_NO_LOG))
{
DEV_LOG_ERROR_PRINTF("log_level (%u) is invalid\n", log_level);
DEV_LOG_VPRINTF(fmt, args); /* This will allow us to debug what line caused the bug. */
return;
}
if (parm->log_type == DEV_LOG_ID_TYPE_NONE)
{
return;
}
#if defined(BCM_SUBSYSTEM_HOST) || defined(ASPEN_VLSI_SIM)
/* Always use CALLER_FMT mode on the host to avoid portability issues with
* transferring va_list as an array */
flags |= BCM_LOG_FLAG_CALLER_FMT;
#endif
/* Update log id counters */
parm->counters[log_level]++;
if (bcm_dev_log_should_drop(parm, log_level, rate_us, rate_limit_id))
return;
msg = bcmos_msg_pool_alloc(&dev_log.pool);
if (!msg)
{
bcm_dev_log_drop_report();
return;
}
log_queue_msg = msg->data;
/* Create log message */
log_queue_msg->log_id = parm;
log_queue_msg->time_stamp = dev_log.dev_log_parm.get_time_cb();
log_queue_msg->msg_level = log_level;
log_queue_msg->flags = flags;
#ifndef BCM_SUBSYSTEM_HOST
/* It is not really necessary to compile out non CALLER_FMT case on the host.
* However, keeping unused code will make Coverity unhappy */
if (unlikely(flags & BCM_LOG_FLAG_CALLER_FMT))
{
#endif /* #ifndef BCM_SUBSYSTEM_HOST */
vsnprintf(log_queue_msg->u.str, MAX_DEV_LOG_STRING_SIZE, (flags & BCM_LOG_FLAG_FILENAME_IN_FMT) ? dev_log_basename(fmt) : fmt, args);
#ifndef BCM_SUBSYSTEM_HOST
}
else
{
uint32_t i;
uint32_t offset;
log_queue_msg->u.fmt_args.fmt = fmt;
offset = ((long)log_queue_msg->u.fmt_args.args % 8 == 0) ? 0 : 1; /* start on an 8-byte boundary */
for (i = 0; i < DEV_LOG_MAX_ARGS; i++)
{
log_queue_msg->u.fmt_args.args[i + offset] = va_arg(args, void *);
}
}
#endif /* #ifndef BCM_SUBSYSTEM_HOST */
if (bcmos_sem_post_is_allowed())
{
#ifdef BCM_SUBSYSTEM_HOST
bcm_dev_log_lock();
#endif
error = bcmos_msg_send(&dev_log.save_queue, msg, BCMOS_MSG_SEND_AUTO_FREE);
#ifdef BCM_SUBSYSTEM_HOST
bcm_dev_log_unlock();
#endif
}
else
{
bcmos_timer_parm timer_params =
{
.name = "dev_log_timer",
.handler = bcm_dev_log_msg_send_timer_cb,
};
if (!(dev_log_timer.flags & BCMOS_TIMER_FLAG_VALID))
bcmos_timer_create(&dev_log_timer, &timer_params);
/* Limitation: We don't send more than 1 logger message even if _bcm_dev_log_vlog() was called multiple timers in IRQs disabled mode because we have a single timer. */
if (!bcmos_timer_is_running(&dev_log_timer))
{
bcmos_timer_handler_set(&dev_log_timer, bcm_dev_log_msg_send_timer_cb, (long)msg);
bcmos_timer_start(&dev_log_timer, 0);
}
}
if (error != BCM_ERR_OK)
{
parm->lost_msg_cnt++;
}
}
void bcm_dev_log_vlog(dev_log_id id,
bcm_dev_log_level log_level,
uint32_t flags,
const char *fmt,
va_list args)
{
_bcm_dev_log_vlog(id, log_level, flags, 0, DEV_LOG_RATE_LIMIT_ID_NONE, fmt, args);
}
/* IMPORTANT!!!
* The function bcm_dev_log_log() must have even number of arguments before the '...' (see comments on header file).
*/
void bcm_dev_log_log(dev_log_id id,
bcm_dev_log_level log_level,
uint32_t flags,
const char *fmt,
...)
{
va_list args;
va_start(args, fmt);
bcm_dev_log_vlog(id, log_level, flags, fmt, args);
va_end(args);
}
void bcm_dev_log_log_ratelimit(dev_log_id id,
bcm_dev_log_level log_level,
uint32_t flags,
uint32_t rate_us,
dev_log_rate_limit_id rate_limit_id,
const char *fmt,
...)
{
va_list args;
va_start(args, fmt);
_bcm_dev_log_vlog(id, log_level, flags, rate_us, rate_limit_id, fmt, args);
va_end(args);
}
#ifdef BCMOS_TRACE_IN_DEV_LOG
static dev_log_id bcmos_trace_dev_log_id[] =
{
[BCMOS_TRACE_LEVEL_NONE] = DEV_LOG_INVALID_ID,
[BCMOS_TRACE_LEVEL_ERROR] = DEV_LOG_INVALID_ID,
[BCMOS_TRACE_LEVEL_INFO] = DEV_LOG_INVALID_ID,
[BCMOS_TRACE_LEVEL_VERBOSE] = DEV_LOG_INVALID_ID,
[BCMOS_TRACE_LEVEL_DEBUG] = DEV_LOG_INVALID_ID
};
static bcm_dev_log_level bcmos_trace_dev_log_level[] =
{
[BCMOS_TRACE_LEVEL_ERROR] = DEV_LOG_LEVEL_ERROR,
[BCMOS_TRACE_LEVEL_INFO] = DEV_LOG_LEVEL_INFO,
[BCMOS_TRACE_LEVEL_VERBOSE] = DEV_LOG_LEVEL_INFO,
[BCMOS_TRACE_LEVEL_DEBUG] = DEV_LOG_LEVEL_DEBUG
};
#endif
/********************************************************************************************/
/* */
/* Name: bcm_dev_log_os_trace_init */
/* */
/* Abstract: Direct bcmos_trace() output to log */
/* Arguments: NONE */
/* */
/* Return Value: */
/* bcmos_errno - Success code (BCM_ERR_OK) or Error code (see bcmos_errno.h) */
/* */
/********************************************************************************************/
bcmos_errno bcm_dev_log_os_trace_init(void)
{
#ifdef BCMOS_TRACE_IN_DEV_LOG
bcmos_trace_dev_log_id[BCMOS_TRACE_LEVEL_ERROR] = bcm_dev_log_id_register("trace_error",
DEV_LOG_LEVEL_ERROR, DEV_LOG_ID_TYPE_BOTH);
bcmos_trace_dev_log_id[BCMOS_TRACE_LEVEL_INFO] = bcm_dev_log_id_register("trace_info",
DEV_LOG_LEVEL_INFO, DEV_LOG_ID_TYPE_BOTH);
bcmos_trace_dev_log_id[BCMOS_TRACE_LEVEL_VERBOSE] = bcmos_trace_dev_log_id[BCMOS_TRACE_LEVEL_INFO];
bcmos_trace_dev_log_id[BCMOS_TRACE_LEVEL_DEBUG] = bcm_dev_log_id_register("trace_debug",
DEV_LOG_LEVEL_DEBUG, DEV_LOG_ID_TYPE_BOTH);
if (bcmos_trace_dev_log_id[BCMOS_TRACE_LEVEL_ERROR] == DEV_LOG_INVALID_ID ||
bcmos_trace_dev_log_id[BCMOS_TRACE_LEVEL_INFO] == DEV_LOG_INVALID_ID ||
bcmos_trace_dev_log_id[BCMOS_TRACE_LEVEL_DEBUG] == DEV_LOG_INVALID_ID)
{
return BCM_ERR_NORES;
}
return BCM_ERR_OK;
#else /* #ifdef BCMOS_TRACE_IN_DEV_LOG */
return BCM_ERR_NOT_SUPPORTED;
#endif
}
#ifdef BCMOS_TRACE_IN_DEV_LOG
/* Direct OS trace to dev_log */
void bcmos_trace(bcmos_trace_level level, const char *format, ...)
{
va_list args;
va_start(args, format);
if (bcmos_trace_dev_log_id[level] == DEV_LOG_INVALID_ID)
{
/* The OS trace hasn't been initialized yet, so just use system printf. */
bcmos_vprintf(format, args);
}
else
{
if (dev_log.state == BCM_DEV_LOG_STATE_ENABLED)
{
if (level == BCMOS_TRACE_LEVEL_ERROR)
bcm_dev_log_vlog(bcmos_trace_dev_log_id[level], bcmos_trace_dev_log_level[level], BCM_LOG_FLAG_CALLER_FMT, format, args);
else
bcm_dev_log_vlog(bcmos_trace_dev_log_id[level], bcmos_trace_dev_log_level[level], 0, format, args);
}
}
va_end(args);
}
#endif
static const char *double2two_int_leading_zeros_arr[] =
{
"",
"0",
"00",
"000",
"0000",
"00000",
"000000",
"0000000",
"00000000",
"000000000",
"0000000000",
"00000000000",
"000000000000",
"0000000000000",
"00000000000000",
"000000000000000",
};
void dev_log_double2two_int_conv(double double_val, uint8_t precision, double2two_int_t *result)
{
ulong_t i;
double fraction;
result->int_val = double_val;
result->leading_zeros = "";
result->fraction = 0;
fraction = (double_val - (double)result->int_val);
if (!fraction)
return; /* Corner case: the given value is 0. */
/* Calculate the number of leading zeros (in i) and point to the corresponding leading zero string. */
for (i = 0; i < MIN(16, precision); i++)
{
if (fraction * pow(10, i) > 0.1)
{
result->leading_zeros = double2two_int_leading_zeros_arr[i];
break;
}
}
if (precision <= i)
return; /* We "wasted" all the precision on the leading zeros. */
result->fraction = fraction * pow(10, precision);
}
char *dev_log_double2str_conv(double double_val, uint8_t precision, char *str)
{
double2two_int_t result;
dev_log_double2two_int_conv(double_val, precision, &result);
sprintf(str, "%-lu.%s%-lu", result.int_val, result.leading_zeros, result.fraction);
return str;
}
#ifdef __KERNEL__
EXPORT_SYMBOL(bcm_dev_log_id_register);
EXPORT_SYMBOL(bcm_dev_log_id_unregister);
EXPORT_SYMBOL(bcm_dev_log_log);
EXPORT_SYMBOL(bcmos_trace);
#endif
#endif /* ENABLE_LOG */
<file_sep># This file contains CMake macros for downloading and building third-party packages
# The macros available to the Aspen module CMakeLists.txt files are:
#
# - bcm_3rdparty_module_name(<name>, <version>) - Set the 3rd party module name and associated variables.
# This macro must be the 1st called
# - bcm_3rdparty_download_wget(<domain> <archive>) - download using wget and unpack 3rd party package.
# - bcm_3rdparty_build_cmake([targets]) - build using cmake+make.
# If [targets] is not specified, "install" is used by default"
# - bcm_3rdparty_build_automake([targets]) - build using configure+make.
# If [targets] is not specified, "install" is used by default"
# - bcm_3rdparty_add_build_options(options) - add build options.
# - bcm_3rdparty_add_cflags(options) - add cflags.
# - bcm_3rdparty_add_cxxflags(options) - add cxxflags.
# - bcm_3rdparty_add_ldflags(options) - add ldflags.
# - bcm_3rdparty_add_dependencies(deps) - add dependencies
# - bcm_3rdparty_export(ldflags) - export module
# This is the last macro to be called when building 3rd party package
#
#======
# Macro to set 3rd party package name
#
# @param MODULE_NAME [in] Target name to add property to.
# @param VERSION [in] Package version.
#======
macro(bcm_3rdparty_module_name MODULE_NAME VERSION)
bcm_module_name(${MODULE_NAME})
string(TOUPPER ${MODULE_NAME} _MOD_NAME_UPPER)
bcm_make_normal_option(${_MOD_NAME_UPPER}_VERSION STRING "${MODULE_NAME} version" "${VERSION}")
if(${_MOD_NAME_UPPER}_VERSION)
set(_VERSION ${${_MOD_NAME_UPPER}_VERSION})
else()
set(_VERSION ${VERSION})
endif()
set(_${_MOD_NAME_UPPER}_TARGET ${MODULE_NAME}_${${_MOD_NAME_UPPER}_VERSION})
set(_${_MOD_NAME_UPPER}_INSTALL_TOP ${CMAKE_BINARY_DIR}/fs)
set(_${_MOD_NAME_UPPER}_LOADED_FILE ${CMAKE_CURRENT_BINARY_DIR}/.${MODULE_NAME}_${_VERSION}_loaded)
set(_${_MOD_NAME_UPPER}_INSTALLED_FILE ${CMAKE_CURRENT_BINARY_DIR}/.${MODULE_NAME}_${_VERSION}_installed)
unset(_VERSION)
endmacro(bcm_3rdparty_module_name)
#======
# Macro to download 3rd party package using wget
#
# @param DOMAIN [in] Domain where to download
# @param ARCHIVE [in] Package file name
# [@param SRC_DIR] [in] Package directory name after unpacking
#======
macro(bcm_3rdparty_download_wget DOMAIN ARCHIVE)
# Absolute path of where the package is going to be unpacked
if(NOT "${ARGN}" STREQUAL "")
set(_${_MOD_NAME_UPPER}_SRC_DIR ${CMAKE_CURRENT_BINARY_DIR}/${ARGN})
else()
set(_${_MOD_NAME_UPPER}_SRC_DIR ${CMAKE_CURRENT_BINARY_DIR}/${_MOD_NAME}-${${_MOD_NAME_UPPER}_VERSION})
endif()
# Identify "unpack" command
get_filename_component(_ARCHIVE_EXT ${ARCHIVE} EXT)
if("${_ARCHIVE_EXT}" MATCHES ".*.tar.gz")
set(_UNPACK_COMMAND tar -xzf)
elseif("${_ARCHIVE_EXT}" MATCHES ".*.tar.bz")
set(_UNPACK_COMMAND tar -xjf)
elseif("${_ARCHIVE_EXT}" MATCHES ".*.tar.xz")
set(_UNPACK_COMMAND tar -xJf)
elseif("${_ARCHIVE_EXT}" MATCHES ".*.zip")
set(_UNPACK_COMMAND unzip)
else()
message(FATAL_ERROR "Don't know how to unpack archive ${ARCHIVE}")
endif()
# Check if patch file exists
set(_PATCH_FILE ${CMAKE_CURRENT_SOURCE_DIR}/${_MOD_NAME}_${${_MOD_NAME_UPPER}_VERSION}.patch)
if(EXISTS ${_PATCH_FILE})
set(_CMD_PATCH COMMAND patch -p0 -i ${_PATCH_FILE} && echo ${_MOD_NAME} patched)
endif()
# Pull archive from public repository only if needed
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${ARCHIVE})
set(_PULL_ARCHIVE_COMMAND COMMAND cp -f ${CMAKE_CURRENT_SOURCE_DIR}/${ARCHIVE} .)
else()
set(_PULL_ARCHIVE_COMMAND COMMAND wget --no-check-certificate ${DOMAIN}/${ARCHIVE})
endif()
add_custom_command(OUTPUT ${_${_MOD_NAME_UPPER}_LOADED_FILE}
COMMAND echo "Loading ${ARCHIVE} from ${DOMAIN}.."
COMMAND rm -rf ${_${_MOD_NAME_UPPER}_SRC_DIR} ${DOMAIN}/${ARCHIVE}*
${_PULL_ARCHIVE_COMMAND}
COMMAND ${_UNPACK_COMMAND} ${ARCHIVE}
COMMAND rm -f ${ARCHIVE}
COMMAND mkdir -p ${_${_MOD_NAME_UPPER}_SRC_DIR}/build
COMMAND touch ${_${_MOD_NAME_UPPER}_LOADED_FILE}
COMMAND echo "${ARCHIVE} loaded and unpacked in ${_${_MOD_NAME_UPPER}_SRC_DIR}"
${_CMD_PATCH}
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
add_custom_target(_${_MOD_NAME_UPPER}_LOADED DEPENDS ${_${_MOD_NAME_UPPER}_LOADED_FILE})
unset(_ARCHIVE_EXT)
unset(_UNPACK_COMMAND)
unset(_PATCH_FILE)
unset(_CMD_PATCH)
endmacro(bcm_3rdparty_download_wget)
#======
# Macro to add build options
#
# @param ARGN [in] options
#======
macro(bcm_3rdparty_add_build_options)
list(APPEND _${_MOD_NAME_UPPER}_BUILD_OPTS ${ARGN})
endmacro(bcm_3rdparty_add_build_options)
#======
# Macro to add cflags
#
# @param ARGN [in] options
#======
macro(bcm_3rdparty_add_cflags)
list(APPEND _${_MOD_NAME_UPPER}_CFLAGS ${ARGN})
endmacro(bcm_3rdparty_add_cflags)
#======
# Macro to add cxxflags
#
# @param ARGN [in] options
#======
macro(bcm_3rdparty_add_cxxflags)
list(APPEND _${_MOD_NAME_UPPER}_CXXFLAGS ${ARGN})
endmacro(bcm_3rdparty_add_cxxflags)
#======
# Macro to add ldflags
#
# @param ARGN [in] options
#======
macro(bcm_3rdparty_add_ldflags)
list(APPEND _${_MOD_NAME_UPPER}_LDFLAGS ${ARGN})
endmacro(bcm_3rdparty_add_ldflags)
#======
# Macro to add dependencies
#
# @param ARGN [in] dependencies
#======
macro(bcm_3rdparty_add_dependencies)
bcm_module_dependencies(PUBLIC ${ARGN})
endmacro(bcm_3rdparty_add_dependencies)
#======
# Macro to add environment variables
#
# @param ARGN [in] environment variables in format var=value
#======
macro(bcm_3rdparty_add_env_variables)
list(APPEND _${_MOD_NAME_UPPER}_BUILD_ENV ${ARGN})
endmacro(bcm_3rdparty_add_env_variables)
#======
# Macro to build 3rd party package using cmake+make
#
# @param ARGN [in] Make targets
#======
macro(bcm_3rdparty_build_cmake)
string(REPLACE " " ";" _BCM_ARCH_FLAGS_LIST "${BCM_ARCHITECTURE_FLAGS}")
set(_CFLAGS_OPTS -I"${BUILD_TOP}"/fs/include ${_BCM_ARCH_FLAGS_LIST} ${_${_MOD_NAME_UPPER}_CFLAGS})
set(_CXXFLAGS_OPTS -I"${BUILD_TOP}"/fs/include ${_BCM_ARCH_FLAGS_LIST} ${_${_MOD_NAME_UPPER}_CXXFLAGS})
set(_LDFLAGS_OPTS -L"${BUILD_TOP}"/fs/lib ${LINK_FLAGS} ${_${_MOD_NAME_UPPER}_LDFLAGS})
set(_TARGETS ${ARGN})
if(NOT _TARGETS)
set(_TARGETS install)
endif()
set(_LD_LIBRARY_PATH "LD_LIBRARY_PATH=${CMAKE_BINARY_DIR}/fs/lib")
if(NOT BCM_CONFIG_HOST MATCHES "x86")
set(_LD_LIBRARY_PATH "${_LD_LIBRARY_PATH}:${CMAKE_BINARY_DIR}/../host-sim/fs/lib")
endif()
add_custom_command(OUTPUT ${_${_MOD_NAME_UPPER}_INSTALLED_FILE}
COMMAND echo "Building ${_MOD_NAME}-${${_MOD_NAME_UPPER}_VERSION}.."
COMMAND PKG_CONFIG_PATH=${CMAKE_BINARY_DIR}/fs/lib/pkgconfig ${_${_MOD_NAME_UPPER}_BUILD_ENV} ${CMAKE_COMMAND} ..
-DCMAKE_INSTALL_PREFIX=${_${_MOD_NAME_UPPER}_INSTALL_TOP}
-DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}
-DCMAKE_AR=${CMAKE_AR} -DCMAKE_LINKER=${CMAKE_LINKER}
-DCMAKE_C_FLAGS="${_CFLAGS_OPTS}" -DCMAKE_CXX_FLAGS="${_CXXFLAGS_OPTS}"
-DCMAKE_EXE_LINKER_FLAGS="${_LDFLAGS_OPTS}"
-DCMAKE_VERBOSE_MAKEFILE:BOOL=${CMAKE_VERBOSE_MAKEFILE}
${_${_MOD_NAME_UPPER}_BUILD_OPTS}
COMMAND ${_LD_LIBRARY_PATH} ${_${_MOD_NAME_UPPER}_BUILD_ENV} ${BCM_MAKE_PROGRAM} ${_BCM_COMMON_MAKE_FLAGS} MAKEOVERRIDES= ${_TARGETS}
COMMAND rm -f ${CMAKE_CURRENT_BINARY_DIR}/.${_MOD_NAME}_*_installed
COMMAND touch ${_${_MOD_NAME_UPPER}_INSTALLED_FILE}
DEPENDS ${_MOD_PUBLIC_DEPS} ${_${_MOD_NAME_UPPER}_LOADED_FILE}
WORKING_DIRECTORY ${_${_MOD_NAME_UPPER}_SRC_DIR}/build)
unset(_BCM_ARCH_FLAGS_LIST)
unset(_CFLAGS_OPTS)
unset(_CXXFLAGS_OPTS)
unset(_LDFLAGS_OPTS)
unset(_TARGETS)
endmacro(bcm_3rdparty_build_cmake)
#======
# Macro to build 3rd party package using automake tools+make
#
# @param ARGN [in] Make targets
#======
macro(bcm_3rdparty_build_automake)
string(REPLACE " " ";" _BCM_ARCH_FLAGS_LIST "${BCM_ARCHITECTURE_FLAGS}")
set(_CFLAGS_OPTS -I"${BUILD_TOP}"/fs/include ${_BCM_ARCH_FLAGS_LIST} ${_${_MOD_NAME_UPPER}_CFLAGS})
set(_CXXFLAGS_OPTS -I"${BUILD_TOP}"/fs/include ${_BCM_ARCH_FLAGS_LIST} ${_${_MOD_NAME_UPPER}_CXXFLAGS})
set(_LDFLAGS_OPTS -L"${BUILD_TOP}"/fs/lib ${LINK_FLAGS} ${_${_MOD_NAME_UPPER}_LDFLAGS})
if(NOT DEFINED BCM_CONFIG_HOST)
message(FATAL_ERROR "Need to add support for board ${BOARD}")
endif()
if(DEFINED ${_MOD_NAME_UPPER}_CONFIG_HOST)
set(_CONFIG_HOST ${${_MOD_NAME_UPPER}_CONFIG_HOST})
else()
set(_CONFIG_HOST ${BCM_CONFIG_HOST})
endif()
set(_TARGETS ${ARGN})
if(NOT _TARGETS)
set(_TARGETS install)
endif()
if(NOT ${_MOD_NAME_UPPER}-DO_NOT_RECONF)
set(_RECONF_CMD COMMAND aclocal && libtoolize && autoheader && automake --add-missing && autoconf)
endif()
add_custom_command(OUTPUT ${_${_MOD_NAME_UPPER}_INSTALLED_FILE}
COMMAND echo "Building ${_MOD_NAME}-${${_MOD_NAME_UPPER}_VERSION}.."
${_RECONF_CMD}
COMMAND ./configure --prefix=${_${_MOD_NAME_UPPER}_INSTALL_TOP} --host=${_CONFIG_HOST}
CC=${CMAKE_C_COMPILER} CXX=${CMAKE_CXX_COMPILER}
CFLAGS="${_CFLAGS_OPTS}" CXXFLAGS="${_CXXFLAGS_OPTS}"
LDFLAGS="${_LDFLAGS_OPTS}" ${_${_MOD_NAME_UPPER}_BUILD_OPTS}
COMMAND ${BCM_MAKE_PROGRAM} ${_BCM_COMMON_MAKE_FLAGS} MAKEOVERRIDES= ${_TARGETS}
COMMAND rm -f ${CMAKE_CURRENT_BINARY_DIR}/.${_MOD_NAME}_*_installed
COMMAND touch ${_${_MOD_NAME_UPPER}_INSTALLED_FILE}
DEPENDS ${_MOD_PUBLIC_DEPS} ${_${_MOD_NAME_UPPER}_LOADED_FILE}
WORKING_DIRECTORY ${_${_MOD_NAME_UPPER}_SRC_DIR})
unset(_BCM_ARCH_FLAGS_LIST)
unset(_CFLAGS_OPTS)
unset(_CXXFLAGS_OPTS)
unset(_LDFLAGS_OPTS)
unset(_TARGETS)
unset(_CONFIG_HOST)
unset(_RECONF_CMD)
endmacro(bcm_3rdparty_build_automake)
#======
# Macro to build 3rd dummy party package
#
# @param ARGN [in] Make targets
#======
macro(bcm_3rdparty_build_dummy)
set(_DEPENDENCIES ${_MOD_PUBLIC_DEPS})
if(TARGET _${_MOD_NAME_UPPER}_LOADED)
set(_DEPENDENCIES ${_DEPENDENCIES} _${_MOD_NAME_UPPER}_LOADED)
endif()
add_custom_command(OUTPUT ${_${_MOD_NAME_UPPER}_INSTALLED_FILE}
COMMAND echo "Building ${_MOD_NAME}-${${_MOD_NAME_UPPER}_VERSION}.."
COMMAND touch ${_${_MOD_NAME_UPPER}_INSTALLED_FILE}
DEPENDS ${_DEPENDENCIES}
WORKING_DIRECTORY ${_${_MOD_NAME_UPPER}_SRC_DIR})
endmacro(bcm_3rdparty_build_dummy)
#======
# Macro to export 3rd party package
#
# @param ARG0 [in] List of libraries (';'-delimited, without -l)
# @param ARG1-N [in] Link options
#======
macro(bcm_3rdparty_export)
if(NOT _${_MOD_NAME_UPPER}_TYPE)
set(_${_MOD_NAME_UPPER}_TYPE SHARED_LIBRARY)
endif()
unset(_LIBS)
unset(_LFLAGS)
if("${_${_MOD_NAME_UPPER}_TYPE}" MATCHES ".*_LIBRARY")
if(NOT "${ARGV}" STREQUAL "")
set(_ARG_LIST ${ARGV})
list(GET _ARG_LIST 0 _LIBS)
# The 1st parameter might be an empty string. In this case remove it
if(NOT _LIBS)
unset(_LIBS)
endif()
list(REMOVE_AT _ARG_LIST 0)
foreach(_OPT ${_ARG_LIST})
list(APPEND _LFLAGS ${_OPT})
endforeach(_OPT)
else()
# Derive library name from module name
if("${_MOD_NAME}" MATCHES "lib.*")
string(SUBSTRING ${_MOD_NAME} 3 -1 _LIBS)
else()
set(_LIBS ${_MOD_NAME})
endif()
endif()
endif()
add_custom_target(${_${_MOD_NAME_UPPER}_TARGET} DEPENDS ${_${_MOD_NAME_UPPER}_INSTALLED_FILE})
add_library(${_MOD_NAME} INTERFACE)
add_dependencies(${_MOD_NAME} ${_${_MOD_NAME_UPPER}_TARGET})
if(_LIBS)
target_include_directories(${_MOD_NAME} INTERFACE ${BUILD_TOP}/fs/include)
if("${_${_MOD_NAME_UPPER}_CFLAGS}")
target_compile_options(${_MOD_NAME} INTERFACE ${_${_MOD_NAME_UPPER}_CFLAGS})
endif()
target_link_libraries(${_MOD_NAME} INTERFACE ${_LIBS})
# For some reason target_link_libraries is not reliable. Adding libraries explicitly
set(_LOPTS -L${BUILD_TOP}/fs/lib -Wl,-rpath=${BUILD_TOP}/fs/lib ${_LFLAGS})
foreach(_LIB ${_LIBS})
list(APPEND _LOPTS -l${_LIB})
endforeach(_LIB)
set_target_properties(${_MOD_NAME} PROPERTIES INTERFACE_SYSTEM_LIBRARIES "${_LOPTS}")
endif()
if(_MOD_PUBLIC_DEPS)
add_dependencies(${_${_MOD_NAME_UPPER}_TARGET} ${_MOD_PUBLIC_DEPS})
endif()
set_target_properties(${_${_MOD_NAME_UPPER}_TARGET} PROPERTIES IMPORT_TYPE ${_${_MOD_NAME_UPPER}_TYPE})
# Unset all variables
unset(_CFLAGS)
unset(_LFLAGS)
unset(_LIBRARY_TYPE)
unset(_LIBS)
unset(_DEPS)
unset(_${_MOD_NAME}_LIBRARY_TYPE)
unset(_${_MOD_NAME}_LFLAGS)
unset(${_MOD_NAME_UPPER}_VERSION)
unset(_${_MOD_NAME_UPPER}_TARGET)
unset(_${_MOD_NAME_UPPER}_INSTALL_TOP)
unset(_${_MOD_NAME_UPPER}_LOADED_FILE)
unset(_${_MOD_NAME_UPPER}_INSTALLED_FILE)
unset(${_MOD_NAME_UPPER})
_bcm_module_globals_clear()
endmacro(bcm_3rdparty_export)
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#include "bcmolt_buf.h"
#include "bcmos_system.h"
/** Initalize a bcmolt_buf stream
*
* \param buf
* \param size
* \param start
* \param endian Endianness of numbers in the resulting stream
*/
void bcmolt_buf_init(bcmolt_buf *buf, uint32_t size, uint8_t *start)
{
buf->len = size;
buf->curr = start;
buf->start = start;
memset(&buf->io, 0, sizeof(buf->io));
}
/** Initalize a bcmolt_buf file IO stream
*
* \param buf bcmolt_buf instance
* \param size Total length of the buffer stream in bytes
* \param io IO callbacks
*/
void bcmolt_buf_init_io(bcmolt_buf *buf, uint32_t size, const bcmolt_buf_io *io)
{
BUG_ON(io->read==NULL || io->write==NULL);
buf->io = *io;
buf->len = size;
buf->curr = buf->start = NULL;
}
/** Set the length of a bcmolt_buf instance
*
* \param buf bcmolt_buf instance
* \param size Total length of the buffer stream in bytes
*/
void bcmolt_buf_set_length(bcmolt_buf *buf, uint32_t size)
{
buf->len = size;
}
/** Read from the buffer
*
* \param buf bcmolt_buf instance
* \param to Where to read to
* \param len Number of bytes to copy
*
* \return BCMOS_TRUE if successfully copied
*/
bcmos_bool bcmolt_buf_read(bcmolt_buf *buf, void *to, size_t len)
{
if ((buf->start + buf->len) >= (buf->curr + len))
{
if (buf->io.read != NULL)
{
int io_result = buf->io.read(buf->io.handle, (unsigned long)buf->curr, to, len);
if (io_result != len)
return BCMOS_FALSE;
}
else
{
memcpy(to, buf->curr, len);
}
buf->curr += len;
return BCMOS_TRUE;
}
return BCMOS_FALSE;
}
/** Transfer bytes from one buf to another
*
* \param *from Source buffer
* \param *to Destination buffer
* \param bytes Number of bytes to transfer
* \return BCMOS_TRUE if successfully transferred
*/
bcmos_bool bcmolt_buf_transfer_bytes(bcmolt_buf *from, bcmolt_buf *to, uint32_t bytes)
{
uint8_t tmp[256];
uint32_t toRead;
while (bytes != 0)
{
toRead = bytes > sizeof(tmp) ? sizeof(tmp) : bytes;
if (!bcmolt_buf_read(from, tmp, toRead) || !bcmolt_buf_write(to, tmp, toRead))
{
return BCMOS_FALSE;
}
bytes -= toRead;
}
return BCMOS_TRUE;
}
/** Write to the buffer
*
* \param buf bcmolt_buf instance
* \param from Source, to copy from
* \param len Number of bytes to copy
*
* \return BCMOS_TRUE if successfully copied
*/
bcmos_bool bcmolt_buf_write(bcmolt_buf *buf, const void *from, size_t len)
{
if ((buf->start + buf->len) >= (buf->curr + len))
{
if (buf->io.write != NULL)
{
int io_result = buf->io.write(buf->io.handle, (unsigned long)buf->curr, from, len);
if (io_result != len)
return BCMOS_FALSE;
}
else
{
memcpy(buf->curr, from, len);
}
buf->curr += len;
return BCMOS_TRUE;
}
else
{
return BCMOS_FALSE;
}
}
/** Move the current pointer to a given position in the buffer
*
* \param pos Byte position in the buffer to move the current pointer to
*
* \param *buf Input buffer
* \return BCMOS_FALSE if len takes us past the end of buffer
*/
bcmos_bool bcmolt_buf_set_pos(bcmolt_buf *buf, uint32_t pos)
{
if (pos <= buf->len)
{
buf->curr = buf->start + pos;
return BCMOS_TRUE;
}
return BCMOS_FALSE;
}
/** Move the current pointer ahead by given number of bytes
*
* \param buf bcmolt_buf instance
* \param len Number of bytes to skip
*
* \return BCMOS_FALSE if len takes us past the end of buffer
*/
bcmos_bool bcmolt_buf_skip(bcmolt_buf *buf, uint32_t len)
{
if ((buf->start + buf->len) >= (buf->curr + len))
{
buf->curr += len;
return BCMOS_TRUE;
}
return BCMOS_FALSE;
}
/** Move the current pointer back by given number of bytes
*
* \param buf bcmolt_buf instance
* \param len Number of bytes to go back
*
* \return BCMOS_FALSE if len takes us past the start of buffer
*/
bcmos_bool bcmolt_buf_rewind(bcmolt_buf *buf, uint32_t len)
{
if (buf->curr >= (buf->start + len))
{
buf->curr -= len;
return BCMOS_TRUE;
}
return BCMOS_FALSE;
}
/** Reads a boolean from a buffer
*
* \param *buf
* \param *val
*/
bcmos_bool bcmolt_buf_read_bool(bcmolt_buf *buf, bcmos_bool *val)
{
/* this function isn't inlined like the rest because it's too complex to inline cleanly */
uint8_t tmp;
if (bcmolt_buf_read_u8(buf, &tmp))
{
*val = (tmp != 0);
return BCMOS_TRUE;
}
else
{
return BCMOS_FALSE;
}
}
#ifdef __KERNEL__
EXPORT_SYMBOL(bcmolt_buf_init);
EXPORT_SYMBOL(bcmolt_buf_read);
EXPORT_SYMBOL(bcmolt_buf_transfer_bytes);
EXPORT_SYMBOL(bcmolt_buf_write);
EXPORT_SYMBOL(bcmolt_buf_set_pos);
EXPORT_SYMBOL(bcmolt_buf_skip);
EXPORT_SYMBOL(bcmolt_buf_rewind);
EXPORT_SYMBOL(bcmolt_buf_read_bool);
MODULE_LICENSE("Dual BSD/GPL");
#endif
<file_sep># CMCC vOMCI : API definition
if(TR451_VOMCI_POLT)
bcm_module_name(tr451_sbi)
bcm_module_dependencies(PUBLIC grpc protobuf)
bcm_module_header_paths(PUBLIC .)
file(GLOB _ALL_PROTOS ${CMAKE_CURRENT_SOURCE_DIR}/*.proto)
unset(_ALL_PB_CC)
foreach(_PROTOFILE ${_ALL_PROTOS})
string(REPLACE "${CMAKE_CURRENT_SOURCE_DIR}/" "" _PROTOFILE ${_PROTOFILE})
string(REPLACE ".proto" ".pb.cc" _PROTOFILE ${_PROTOFILE})
list(APPEND _ALL_PB_CC ${_PROTOFILE})
endforeach(_PROTOFILE)
bcm_module_cflags(PUBLIC -Wno-redundant-decls -Wno-switch-default
-Wno-cast-qual -Wno-shadow -Wno-deprecated-declarations -Wno-unused-variable)
bcm_module_cflags(PUBLIC -std=c++11)
bcm_module_protoc_srcs(
${_ALL_PB_CC}
tr451_vomci_sbi_service.grpc.pb.cc
)
# Generate C++ files from .proto
bcm_protoc_generate()
# Build library
bcm_create_lib_target()
endif()
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#include "bcmolt_utils.h"
/* HexPrint a single line */
#define BYTES_IN_LINE 16
#define b2a(c) (isprint(c)?c:'.')
static void _hexprint1(bcmos_msg_print_cb print_cb, void *context, uint16_t o, const uint8_t *p_data, uint16_t count, const char *indent)
{
int i;
if (indent)
print_cb(context, "%s", indent);
print_cb(context, "%04x: ", o);
for (i=0; i<count; i++)
{
print_cb(context, "%02x", p_data[i]);
if (!((i+1)%4))
print_cb(context, " ");
}
for (; i<BYTES_IN_LINE; i++)
{
if (!((i+1)%4))
print_cb(context, " ");
else
print_cb(context, " ");
}
for (i=0; i<count; i++)
print_cb(context, "%c", b2a(p_data[i]));
print_cb(context, "\n");
}
static void _default_print_cb(void *context, const char *format, ...)
{
va_list args;
va_start(args, format);
bcmos_vprintf(format, args);
va_end(args);
}
void bcmos_hexdump(bcmos_msg_print_cb print_cb, void *context, const void *buffer, uint32_t offset, uint32_t count, const char *indent)
{
const uint8_t *p_data = buffer;
uint16_t n;
if (print_cb == NULL)
print_cb = _default_print_cb;
while (count)
{
n = (count > BYTES_IN_LINE) ? BYTES_IN_LINE : count;
_hexprint1(print_cb, context, offset, p_data, n, indent);
count -= n;
p_data += n;
offset += n;
}
}
void bcmos_hexdump_one_line(const char *funcname,
uint32_t lineno,
bcmos_msg_print_cb print_cb,
void *context,
char *out_buf,
uint32_t max_buf_size,
const void *buffer,
uint32_t start_offset,
uint32_t byte_count,
const char *prefix,
const char *suffix)
{
const uint8_t *p_data = buffer;
uint32_t data_offset = start_offset;
size_t out_buf_offset = 0;
uint32_t tmp_num_chars = 0;
memset(out_buf, 0, max_buf_size);
if (prefix)
{
tmp_num_chars = snprintf(out_buf + out_buf_offset, /* out_buf start offset */
max_buf_size - out_buf_offset, /* remaining space in out_buf */
"\n%40s:%-5u %s", funcname, lineno, prefix);
}
else
{
tmp_num_chars = snprintf(out_buf + out_buf_offset, /* out_buf start offset */
max_buf_size - out_buf_offset, /* remaining space in out_buf */
"\n");
}
out_buf_offset += tmp_num_chars;
while ((data_offset < (start_offset + byte_count)) && (out_buf_offset < max_buf_size))
{
tmp_num_chars = snprintf(out_buf + out_buf_offset, /* out_buf start offset */
max_buf_size - out_buf_offset, /* remaining space in out_buf */
"%02x ",
p_data[data_offset++]); /* byte to dump */
BUG_UNLESS(3 == tmp_num_chars);
out_buf_offset += tmp_num_chars;
}
if (tmp_num_chars < max_buf_size)
{
if (suffix)
{
tmp_num_chars = snprintf(out_buf + out_buf_offset, /* out_buf start offset */
max_buf_size - out_buf_offset, /* remaining space in out_buf */
"%s", suffix);
}
else
{
tmp_num_chars = snprintf(out_buf + out_buf_offset, /* out_buf start offset */
max_buf_size - out_buf_offset, /* remaining space in out_buf */
"\n");
}
out_buf_offset += tmp_num_chars;
BUG_UNLESS(out_buf_offset < max_buf_size);
}
print_cb(context, "%s", out_buf);
}
bcmos_errno bcmolt_read_snum(uint8_t byte_width, const void *data, int64_t *n)
{
switch (byte_width)
{
case 1:
{
int8_t n1 = *(const int8_t *)data;
*n = n1;
break;
}
case 2:
{
int16_t n2 = *(const int16_t *)data;
*n = n2;
break;
}
case 4:
{
int32_t n4 = *(const int32_t *)data;
*n = n4;
break;
}
case 8:
{
memcpy(n, data, sizeof(*n));
break;
}
default:
return BCM_ERR_NOT_SUPPORTED;
}
return BCM_ERR_OK;
}
<file_sep># TR-451 ONU Management
# pOLT daemon application
#
if(TR451_VOMCI_POLT)
bcm_module_name(tr451_polt_daemon)
bcm_module_dependencies(PUBLIC tr451_polt daemon)
bcm_module_header_paths(PRIVATE .)
bcm_module_srcs(bcm_tr451_polt_main.c)
bcm_create_app_target(fs)
install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/start_tr451_polt.sh DESTINATION fs
PERMISSIONS OWNER_READ OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE)
endif()
<file_sep>bcm_module_name(os)
bcm_module_header_paths(PUBLIC ${OS} .)
bcm_module_dependencies(PUBLIC ${SUBSYSTEM}_config)
bcm_make_debug_option(OS_HEAP_DEBUG BOOL "Enable heap debugging" n)
bcm_make_debug_option(OS_BLK_POOL_DEBUG BOOL "Enable block pool debugging" n)
bcm_make_debug_option(OS_TIMER_DEBUG BOOL "Enable timer debugging" n)
bcm_make_debug_option(OS_MEM_CHECK BOOL "Enable dynamic memory block boundary check" n)
if("${OS}" STREQUAL "threadx")
bcm_module_dependencies(PUBLIC threadx bsp)
bcm_module_definitions(PUBLIC -DBCMOS_TRACE_IN_DEV_LOG)
bcm_module_definitions(PUBLIC -DBCMOS_HEALTH_CHECK_ENABLED)
elseif("${OS}" STREQUAL "posix")
bcm_module_definitions(PUBLIC -DBCMOS_MSG_QUEUE_DOMAIN_SOCKET
-DBCMOS_MSG_QUEUE_UDP_SOCKET)
bcm_module_system_libraries(pthread rt m)
elseif("${OS}" STREQUAL "cfe")
bcm_module_dependencies(PRIVATE sys)
bcm_module_header_paths(PUBLIC ${SOURCE_TOP}/embedded/platform/${PLATFORM}/cfe/cfe/include)
bcm_module_header_paths(PUBLIC ${SOURCE_TOP}/embedded/platform/${PLATFORM}/cfe/cfe/arch/arm/common/include)
endif()
if(${BUF_IN_DMA_MEM})
bcm_module_definitions(PUBLIC -DBCMOS_BUF_IN_DMA_MEM
-DBCMOS_BUF_DATA_UNIT_SIZE=1024)
endif()
if("${OS}" STREQUAL "threadx" AND "${PLATFORM}" STREQUAL "aspen")
bcm_make_debug_option(BUF_POOL_SIZE STRING "bcmos_buf system buffer pool size. 0=use heap" 1024)
elseif("${OS}" STREQUAL "threadx")
bcm_make_debug_option(BUF_POOL_SIZE STRING "bcmos_buf system buffer pool size. 0=use heap" 512)
elseif("${SUBSYSTEM}" STREQUAL "embedded") # x86 simulation in embedded side
bcm_make_debug_option(BUF_POOL_SIZE STRING "bcmos_buf system buffer pool size. 0=use heap" 1024)
else()
bcm_make_debug_option(BUF_POOL_SIZE STRING "bcmos_buf system buffer pool size. 0=use heap" 0)
endif()
if(DEFINED BUF_POOL_SIZE AND NOT "${BUF_POOL_SIZE}" STREQUAL "0")
if(NOT DEFINED BUF_POOL_BUF_SIZE)
set(BUF_POOL_BUF_SIZE 4224)
endif()
if(NOT DEFINED BIG_BUF_POOL_SIZE)
set(BIG_BUF_POOL_SIZE 16)
endif()
if(NOT DEFINED BIG_BUF_POOL_BUF_SIZE)
set(BIG_BUF_POOL_BUF_SIZE 65536)
endif()
bcm_module_definitions(PUBLIC -DBCMOS_BUF_POOL_SIZE=${BUF_POOL_SIZE}
-DBCMOS_BUF_POOL_BUF_SIZE=${BUF_POOL_BUF_SIZE}
-DBCMOS_BIG_BUF_POOL_SIZE=${BIG_BUF_POOL_SIZE}
-DBCMOS_BIG_BUF_POOL_BUF_SIZE=${BIG_BUF_POOL_BUF_SIZE})
endif()
if(${OS_HEAP_DEBUG})
bcm_module_definitions(PUBLIC -DBCMOS_HEAP_DEBUG)
endif()
if(${OS_TIMER_DEBUG})
bcm_module_definitions(PUBLIC -DBCMOS_TIMER_DEBUG)
endif()
if(${OS_BLK_POOL_DEBUG})
bcm_module_definitions(PUBLIC -DBCMOS_BLK_POOL_DEBUG)
endif()
bcm_module_srcs(bcmos_common.c bcmos_errno.c bcmos_hash_table.c ${OS}/bcmos_system.c)
if(${COVERITY})
bcm_module_srcs(bcmos_rw_lock_coverity.c)
else()
bcm_module_srcs(bcmos_rw_lock.c)
endif()
if(${OS_MEM_CHECK})
bcm_module_definitions(PUBLIC -DBCMOS_MEM_CHECK)
endif()
if(${ASPEN_PCIE_VLSI_SIM})
bcm_module_dependencies(PUBLIC pcie_dma_vlsi_sim_utils)
endif()
bcm_create_lib_target()
# Add additional subdirectories for this module
if(CLI AND EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/os_cli)
bcm_add_subdirectory(os_cli)
endif()
if("${OS_KERNEL}" STREQUAL "linux")
bcm_add_subdirectory(linux)
endif()
# Add files to the GitHub part of the release tree.
bcm_github_install(./*
RELEASE github/os_abstraction
EXCLUDE_FROM_RELEASE threadx vxworks55 cfe ipc_test linux os_cli unitest)
<file_sep>if(TR451_VOMCI_POLT)
# TR-451 pOLT vendor interface: Simulation
bcm_module_name(tr451_polt_vendor)
bcm_module_header_paths(PUBLIC . ..)
bcm_module_dependencies(PUBLIC os dev_log cli)
bcm_module_dependencies(PRIVATE tr451_sbi grpc tr451_polt)
bcm_module_srcs(sim_tr451_polt_vendor.cc sim_tr451_polt_vendor_cli.cc)
bcm_create_lib_target()
endif()
<file_sep>#!/bin/bash
# Parameters:
# - tool name
# - tool parameters
#set -x
fs_bin_dir=`dirname $0`
tool_name=$1
tool_dir=`dirname $1`
mkdir -p $fs_bin_dir/../sysrepo
pushd $fs_bin_dir/../sysrepo
sysrepo_dir=`pwd`
popd
lib_dir=$tool_dir/../lib
export LD_LIBRARY_PATH=$lib_dir:$LD_LIBRARY_PATH
export SYSREPO_REPOSITORY_PATH=$sysrepo_dir
export LIBYANG_EXTENSIONS_PLUGINS_DIR=$lib_dir/libyang/extensions
export LIBYANG_USER_TYPES_PLUGINS_DIR=$lib_dir/libyang/user_types
shift
$tool_name $*
<file_sep>#!/bin/bash
# Parameters:
# - tool parameters
#set -x
fs_bin_dir=`dirname $0`
tool_name=$fs_bin_dir/netopeer2-server
pushd $fs_bin_dir/../sysrepo
sysrepo_dir=`pwd`
popd
lib_dir=$fs_bin_dir/../lib
export LD_LIBRARY_PATH=$lib_dir:$LD_LIBRARY_PATH
export SYSREPO_REPOSITORY_PATH=$sysrepo_dir
export LIBYANG_EXTENSIONS_PLUGINS_DIR=$lib_dir/libyang/extensions
export LIBYANG_USER_TYPES_PLUGINS_DIR=$lib_dir/libyang/user_types
if [ "$1" = "gdb" ]; then
GDB="gdb --args"
shift
fi
# busibox version of 'ps' doesn't support '-ef' operand
if ls -l `which ps` | grep busybox > /dev/null; then
PS="ps"
else
PS="ps -ef"
fi
# cleanup
if $PS | grep netopeer2\-server | grep -v grep > /dev/null; then
echo netopeer2-server is already running
exit -1
fi
if [ "`whoami`" = "root" ]; then
chown -R root:root $sysrepo_dir/*
fi
# Create sysrepo shared directory if doesn't exist
if test ! -d /dev/shm; then
mkdir /dev/shm
fi
if ! $PS | grep bcmolt_netconf_server | grep -v grep > /dev/null; then
echo Cleaning up stale state
unset SHM_PREFIX
if [ "$SYSREPO_SHM_PREFIX" != "" ]; then
SHM_PREFIX=${SYSREPO_SHM_PREFIX}
else
SHM_PREFIX=sr
fi
rm -fr /dev/shm/${SHM_PREFIX}_* /dev/shm/${SHM_PREFIX}sub_* $sysrepo_dir/sr_evpipe* /tmp/netopeer2-server.pid
fi
$GDB $tool_name $*
<file_sep># Top level makefile for generating the build tree. The makefile is a wrapper to the CMake call
# to simplify the interface. See the 'make help' for more information on what can be done here.
#
# The build artifacts will be under the 'build' directory.
#
# Artifacts (e.g. executables, images, kernel modules, etc. Will be added to the build tree
# in the designated install path. For consistency with Maple, by default the install path will
# be the directory 'fs' (e.g. /build/embedded-aspen/fs.
#
#====
# Top level definitions used before CMake
#====
TOP_DIR := $(shell pwd)
BUILD_TOP_DIR ?= ./build
BOARD ?= sim
V ?= n
ifneq (,$(wildcard ./netconf_server))
NETCONF_PRESENT := y
NETCONF_SERVER ?= y
NETCONF_SERVER_OPT := -DNETCONF_SERVER:BOOL=$(NETCONF_SERVER)
endif
ifneq (,$(wildcard ./onu_mgmt/tr451_vomci_polt)$(wildcard ./tr451_vomci_polt))
TR451_VOMCI_POLT ?= y
TR451_VOMCI_POLT_OPT := -DTR451_VOMCI_POLT:BOOL=$(TR451_VOMCI_POLT)
endif
OPEN_SOURCE := y
ifeq ("$V", "n")
SILENT := @
CMAKE_VERBOSE := OFF
BCM_MAKE_OPTIONS := --no-print-directory
else
CMAKE_VERBOSE := ON
endif
#====
# Build artifact directory paths
#====
HOST_ARTIFACTS := $(BUILD_TOP_DIR)
HOST_CACHE_MD5SUM := $(shell md5sum $(HOST_ARTIFACTS)/CMakeCache.txt 2>/dev/null)
#====
# Variables used in the 'clean' rules. The lower case part is to support meta rule resolution
#====
ALL_clean_ARTIFACTS := $(wildcard $(BUILD_TOP_DIR)/Makefile)
ALL_clean_cache_ARTIFACTS := $(wildcard $(BUILD_TOP_DIR)/CMakeCache.txt)
#====
# Determine the flags we pass to CMake that are common for host or embedded. The definitions set
# here can be viewed in the <artifact tree>/CMakeCache.txt file. All variables that are overridden
# on the command line (e.g. "UT=y") are passed through to CMake transparently. Additionally, CMake
# has a bool for enabling or disabling verbose info from the Makefiles. If the V variable is set,
# the verbose will be enabled. If not set the verbose will be disabled.
#====
BCM_CMAKE_USER_VARS = $(patsubst %,-D%,$(filter-out BUILD_TOP_DIR=%,$(filter-out V=%,$(MAKEOVERRIDES))))
MAKE_PID = $(shell echo $$PPID)
JOB_FLAG := $(filter -j%, $(subst -j, -j, $(shell ps T | grep "^\s*$(MAKE_PID).*$(MAKE)")))
BCM_CMAKE_OPTIONS = $(BCM_CMAKE_USER_VARS) \
$(NETCONF_SERVER_OPT) \
$(TR451_VOMCI_POLT_OPT) \
-DOPEN_SOURCE=$(OPEN_SOURCE) \
-DBOARD:STRING=$(BOARD) \
-DCMAKE_VERBOSE_MAKEFILE:BOOL=$(CMAKE_VERBOSE)
#====
# Definitions of commands used in the build rules. Currently: cmake generation, docker use check and
# clean.
#====
BCM_CMAKE_CMD = cd $(BUILD_DIR) && \
cmake -DCMAKE_TOOLCHAIN_FILE=cmake/modules/$(TOOLCHAIN).cmake \
$(BCM_CMAKE_OPTIONS) \
-DSUBSYSTEM:STRING=$(SUBSYSTEM) $(TOP_DIR)
BCM_CLEAN_CMD = test "$(ALL_$@_ARTIFACTS)" != "" && \
for this_dir in $(ALL_$@_ARTIFACTS); do \
if test $(BCM_CLEAN_CACHE) -eq 1; then \
echo -n "Cleaning file $$this_dir...."; \
rm -f $$this_dir; \
else \
echo -n "Cleaning directory $$(dirname $$this_dir)...."; \
(cd $$(dirname $$this_dir) && rm -f CMakeCache.txt && $(MAKE) $(BCM_MAKE_OPTIONS) clean);\
fi; \
echo "done"; \
done || echo "Nothing to be done for '$@'"
ifneq ("$NETCONF_PRESENT", "y")
INSTALL_INCLUDE_TARGET = github_install_include
endif
#====
# Default build rule
#====
all: host
PHONY += all
#====
# Rules for generating the CMake build trees. For each subsystem it is possible the CMake command line
# may be called twice. This is to support a modularization use case where we want to place cache options
# (bcm_make_<type>_option() macros) with the module that is associated (e.g. CLI=y|n in the
# cli/CMakeLists.txt file).
#
# To support the modularity we want, we would need to run the CMake command line twice before doing the build.
# Since this has a slight impact on the build time, we will only do this if any CMakeLists.txt files have
# changed in the tree and the CMakeCache.txt file is now out of date. If no CMakeLists.txt file changes,
# we only run the CMake command line once per invocation.
#====
cmake-host: BUILD_DIR := $(HOST_ARTIFACTS)
cmake-host: TOOLCHAIN := $(BOARD)
cmake-host:
$(SILENT)mkdir -p $(BUILD_DIR)
$(SILENT)$(BCM_DOCKER_CHECK)
$(SILENT)$(BCM_CMAKE_CMD)
$(SILENT)if test "$$(md5sum $(HOST_ARTIFACTS)/CMakeCache.txt)" != "$(HOST_CACHE_MD5SUM)"; then \
$(BCM_CMAKE_CMD); \
fi
PHONY += cmake-host
#====
# Rules for just generating the build artifact tree. The CMake generation is done only, no make is done
# afterwards. This can be used if you don't want to build an entire 'embedded' or 'host'. For example, you
# might just want to build unit tests in one subsystem.
#====
buildtree: cmake-host
PHONY += buildtree
#====
# Rules for the subsystem builds. These will update the artifact tree with CMake and then run a make
# in that tree. The 'make install' is used so the results will be in the 'fs' directory at the top
# of the artifact tree.
#====
host: cmake-host
$(SILENT)cd $(HOST_ARTIFACTS) && $(MAKE) $(BCM_MAKE_OPTIONS) install $(INSTALL_INCLUDE_TARGET)
PHONY += host
#====
# Clean rules for build and artifact trees. The 'clean', 'clean_host', 'clean_embedded' are a 'make clean'
# in the artifact tree. The 'make clean' target that is run was generated by CMake and will just clean
# the build artifacts. The CMake generated tree will remain. To clean the CMake tree, use the 'make clean_all'
# which just removes the whole 'build' directory.
#====
clean: BCM_CLEAN_CACHE = 0
clean:
$(SILENT)$(BCM_CLEAN_CMD)
PHONY += clean
clean_cache: BCM_CLEAN_CACHE = 1
clean_cache:
$(SILENT)$(BCM_CLEAN_CMD)
PHONY += clean_cache
clean_all:
@echo -n "Removing the build directory...."
$(SILENT)rm -rf $(BUILD_TOP_DIR)
@echo "done"
PHONY += clean_all
#====
# Make help targets
#====
.NOTPARALLEL:
help_targets:
@echo
@echo "Make Targets:"
@echo " help - Help for all targets, including target types"
@echo " all - Build the source for the host board (default target)"
@echo " buildtree - Just run the CMake configuration, no build"
@echo " clean - Do a 'make clean' in the host and embedded build trees, includes CMake cache"
@echo " clean_cache - Remove the CMake cache for the host and embedded build trees"
@echo " clean_all - Remove all the build artifacts"
PHONY += help_targets
help_params:
@echo
@echo "Make Parameters Available for Host"
@echo " BOARD - Host board type [current='$(BOARD)']"
@echo " KERNELDIR - Top of the kernel source directory [current='$(KERNELDIR)']"
@echo " KERNEL_OUTDIR - Top of the kernel build directory (default KERNELDIR) [current='$(KERNEL_OUTDIR)']"
@echo " BUILD_TOP_DIR - Where to place the build artifacts [current='$(BUILD_TOP_DIR)']"
@test -s $(HOST_ARTIFACTS)/CMakeCache.txt && (cd $(HOST_ARTIFACTS) && $(MAKE) -s help_normal_params) || \
echo "(Run 'make buildtree' to see the full set of options)"
@echo
@echo "Make Debug Parameters Available for Host"
@echo " V - Turn on or off make verbosity, =y to turn on [current='$(if $(V),y,n)']"
PHONY += help_params
help: help_targets help_params
PHONY += help
<file_sep># pcre - Perl Regular Expression parser
#
include(third_party)
bcm_3rdparty_module_name(pcre "8.43")
bcm_3rdparty_download_wget("https://ftp.pcre.org/pub/pcre" "pcre-${PCRE_VERSION}.tar.gz")
bcm_3rdparty_add_dependencies(zlib)
bcm_3rdparty_add_build_options(-DBUILD_SHARED_LIBS=true -DPCRE_SUPPORT_UNICODE_PROPERTIES=true -DPCRE_SUPPORT_UTF=true)
bcm_3rdparty_build_cmake()
bcm_3rdparty_export()
<file_sep>/*
* <:copyright-BRCM:2016-2020:Apache:standard
*
* Copyright (c) 2016-2020 Broadcom. All Rights Reserved
*
* The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* :>
*
*****************************************************************************/
/*
* bbf-vomci.h
*/
#ifndef _BBF_VOMCI_H_
#define _BBF_VOMCI_H_
#include <bcmos_system.h>
#include <libyang/libyang.h>
#include <sysrepo.h>
#define BBF_POLT_VOMCI_MODULE_NAME "bbf-olt-vomci"
#define BBF_NF_ENDPOINT_FILTER_MODULE_NAME "bbf-nf-endpoint-filter"
#define BBF_POLT_VOMCI_SERVER_PATH "/bbf-olt-vomci:remote-network-function/nf-server"
#define BBF_POLT_VOMCI_CLIENT_PATH "/bbf-olt-vomci:remote-network-function/nf-client"
#define BBF_POLT_VOMCI_FILTER_PATH "/bbf-olt-vomci:remote-network-function/nf-endpoint-filter"
#define BBF_POLT_VOMCI_SERVER_LISTEN_ENDPOINTS_PATH BBF_POLT_VOMCI_SERVER_PATH "/listen/listen-endpoint"
#define BBF_POLT_VOMCI_SERVER_REMOTE_ENDPOINTS_PATH BBF_POLT_VOMCI_SERVER_LISTEN_ENDPOINTS_PATH "/remote-endpoints"
#define BBF_POLT_VOMCI_CLIENT_REMOTE_ENDPOINTS_PATH BBF_POLT_VOMCI_CLIENT_PATH "/nf-initiate/remote-endpoints"
bcmos_errno bbf_polt_vomci_module_init(sr_session_ctx_t *srs, struct ly_ctx *ly_ctx);
bcmos_errno bbf_polt_vomci_module_start(sr_session_ctx_t *srs, struct ly_ctx *ly_ctx);
void bbf_polt_vomci_module_exit(sr_session_ctx_t *srs, struct ly_ctx *ly_ctx);
#endif /* _BBF_XPON_H_ */
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
/*******************************************************************
* bcmcli.h
*
* CLI engine
*
*******************************************************************/
#ifndef BCMCLI_H
#define BCMCLI_H
#include <bcmos_system.h>
#include <bcmcli_session.h>
#include <bcmolt_buf.h>
#ifndef BCM_OPEN_SOURCE
#include <bcmolt_type_metadata.h>
#else
typedef long bcmolt_enum_number;
#define BCMOLT_PARM_NO_VALUE_STR "_"
#define BCMOLT_ARRAY_EMPTY_STR "-"
#define BCMOLT_MAX_METADATA_NAME_LENGTH 80
#define BCMOLT_ENUM_MASK_DEL_STR "+"
#endif
/** \defgroup bcm_cli Broadcom CLI Engine
* Broadcom CLI engine is used for all configuration and status monitoring.\n
* It doesn't have built-in scripting capabilities (logical expressions, loops),
* but can be used in combination with any available scripting language.\n
* Broadcom CLI supports the following features:\n
* - parameter number and type validation (simplifies command handlers development)
* - parameter value range checking
* - mandatory and optional parameters
* - positional and named parameters
* - parameters with default values
* - enum parameters can have arbitrary values
* - automatic command help generation
* - automatic or user-defined command shortcuts
* - command handlers return completion status to enable scripting
* - multiple sessions
* - session access rights
* - extendible. Supports user-defined parameter types
* - relatively low stack usage
* @{
*/
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
#define BCMCLI_MAX_SEARCH_SUBSTR_LENGTH BCMOLT_MAX_METADATA_NAME_LENGTH
#define BCMCLI_ARRAY_EMPTY BCMOLT_ARRAY_EMPTY_STR
#define BCMCLI_PARM_NO_VALUE BCMOLT_PARM_NO_VALUE_STR
#define BCMCLI_ENUM_MASK_DEL_STR BCMOLT_ENUM_MASK_DEL_STR
/** Monitor entry handle
*/
typedef struct bcmcli_entry bcmcli_entry;
/* if BCMCLI_PARM_USERIO flag is set:
low_val: t_userscanf_f function
high_val: t_userprintf_f function
*/
/** Function parameter structure */
typedef struct bcmcli_cmd_parm bcmcli_cmd_parm;
/** Parameter type */
typedef enum
{
BCMCLI_PARM_NONE,
BCMCLI_PARM_DECIMAL, /**< Decimal number */
BCMCLI_PARM_DECIMAL64, /**< Signed 64-bit decimal */
BCMCLI_PARM_UDECIMAL, /**< Unsigned decimal number */
BCMCLI_PARM_UDECIMAL64, /**< Unsigned 64-bit decimal number */
BCMCLI_PARM_HEX, /**< Hexadecimal number */
BCMCLI_PARM_HEX64, /**< 64-bit hexadecimal number */
BCMCLI_PARM_NUMBER, /**< Decimal number or hex number prefixed by 0x */
BCMCLI_PARM_NUMBER64, /**< 64bit decimal number or hex number prefixed by 0x */
BCMCLI_PARM_UNUMBER, /**< Unsigned decimal number or hex number prefixed by 0x */
BCMCLI_PARM_UNUMBER64, /**< Unsigned 64bit decimal number or hex number prefixed by 0x */
BCMCLI_PARM_FLOAT, /**< IEEE 32-bit floating-point number */
BCMCLI_PARM_DOUBLE, /**< IEEE 64-bit floating point number */
BCMCLI_PARM_STRING, /**< String */
BCMCLI_PARM_ENUM, /**< Enumeration */
BCMCLI_PARM_ENUM_MASK, /**< Bitmask created from enumeration values */
BCMCLI_PARM_IP, /**< IP address n.n.n.n */
BCMCLI_PARM_IPV6, /**< IPv6 address */
BCMCLI_PARM_MAC, /**< MAC address xx:xx:xx:xx:xx:xx */
BCMCLI_PARM_BUFFER, /**< Byte array */
BCMCLI_PARM_STRUCT, /**< Structure */
BCMCLI_PARM_USERDEF /**< User-defined parameter. User must provide scan_cb */
} bcmcli_parm_type;
/** Enum attribute value.
*
* Enum values is an array of bcmcli_enum_val terminated by element with name==NULL.
* This is an extension of the generic enum value 'bcmolt_enum_val' with additional parameters.
*/
typedef struct bcmcli_enum_val
{
const char *name; /**< Enum symbolic name */
bcmolt_enum_number val; /**< Enum internal value */
bcmcli_cmd_parm *parms; /**< Extension parameter table for enum-selector */
} bcmcli_enum_val;
#define BCMCLI_ENUM_LAST { NULL, 0, NULL } /**< Last entry in enum table */
/** Boolean values (true/false, yes/no, on/off)
*
*/
extern bcmcli_enum_val bcmcli_enum_bool_table[];
/* Monitor data types */
typedef long bcmcli_number; /**< Type underlying BCMCLI_PARM_NUMBER, BCMCLI_PARM_DECIMAL */
typedef long bcmcli_unumber; /**< Type underlying BCMCLI_PARM_HEX, BCMCLI_PARM_UDECIMAL */
typedef long bcmcli_number64; /**< Type underlying BCMCLI_PARM_NUMBER64, BCMCLI_PARM_DECIMAL64 */
typedef long bcmcli_unumber64; /**< Type underlying BCMCLI_PARM_HEX64, BCMCLI_PARM_UDECIMAL64 */
/** Parameter value */
typedef struct bcmcli_parm_value
{
union
{
long number; /**< Signed number */
unsigned long unumber; /**< Unsigned number */
long long number64; /**< Signed 64-bit number */
unsigned long long unumber64; /**< Unsigned 64-bit number */
const char *string; /**< 0-terminated string */
double d; /**< Double-precision floating point number */
bcmos_mac_address mac; /**< MAC address */
bcmos_ipv6_address ipv6; /**< IPv6 address */
bcmolt_buf buffer; /**< Buffer: used for BCMCLI_PARM_BUFFER */
bcmolt_enum_number enum_val; /**< Enum value (number) */
bcmcli_cmd_parm *fields; /**< Structure fields */
};
bcmos_bool is_set;
} bcmcli_parm_value;
/** User-defined scan function.
* The function is used for parsing user-defined parameter types
* Returns: 0-ok, <=error
*
*/
typedef bcmos_errno (*bcmcli_scan_cb)(bcmcli_session *session, const bcmcli_cmd_parm *parm,
bcmcli_parm_value *value, const char *string_val);
/** User-defined print value function.
* The function is used for printing values of user-defined parameter types
*
*/
typedef void (*bcmcli_print_cb)(bcmcli_session *session, const bcmcli_cmd_parm *parm,
const bcmcli_parm_value *value);
/** Function parameter structure */
struct bcmcli_cmd_parm
{
const char *name; /**< Parameter name. Shouldn't be allocated on stack! */
const char *description; /**< Parameter description. Shouldn't be allocated on stack! */
bcmcli_parm_type type; /**< Parameter type */
uint8_t flags; /**< Combination of BCMCLI_PARM_xx flags */
#define BCMCLI_PARM_FLAG_NONE 0x00 /**< For use instead of magic number 0 when no flags apply */
#define BCMCLI_PARM_FLAG_OPTIONAL 0x01 /**< Parameter is optional */
#define BCMCLI_PARM_FLAG_DEFVAL 0x02 /**< Default value is set */
#define BCMCLI_PARM_FLAG_RANGE 0x04 /**< Range is set */
#define BCMCLI_PARM_FLAG_EOL 0x08 /**< String from the current parser position till EOL */
#define BCMCLI_PARM_FLAG_SELECTOR 0x10 /**< Parameter selects other parameters */
#define BCMCLI_PARM_FLAG_OMIT_VAL 0x20 /**< Allow only the name of the parameter to be specified (without =value) */
#define BCMCLI_PARM_FLAG_ASSIGNED 0x40 /**< Internal flag: parameter is assigned */
bcmcli_number low_val; /**< Low val for range checking */
bcmcli_number hi_val; /**< Hi val for range checking */
bcmcli_parm_value value; /**< Value */
bcmcli_enum_val *enum_table; /**< Table containing { enum_name, enum_value } pairs */
bcmcli_scan_cb scan_cb; /**< User-defined scan function for BCMCLI_PARM_USERDEF parameter type */
bcmcli_print_cb print_cb; /**< User-defined print function for BCMCLI_PARM_USERDEF parameter type */
uint32_t max_array_size; /**< Max array size for array-parameter */
uint32_t array_size; /**< Actual array size for array-parameter */
bcmcli_parm_value *values; /**< Array values */
void *user_data; /**< User data - passed transparently to command handler */
};
/** Command parameter list terminator */
#define BCMCLI_PARM_LIST_TERMINATOR { .name=NULL, .description=NULL, .type=BCMCLI_PARM_NONE }
/** Helper macro: make simple parameter
* \param[in] _name Parameter name
* \param[in] _descr Parameter description
* \param[in] _type Parameter type
* \param[in] _flags Parameter flags
*/
#define BCMCLI_MAKE_PARM(_name, _descr, _type, _flags) \
{ .name=(_name), .description=(_descr), .type=(_type), .flags=(_flags) }
/** Helper macro: make simple parameter
* \param[in] _name Parameter name
* \param[in] _descr Parameter description
* \param[in] _type Parameter type
* \param[in] _flags Parameter flags
* \param[in] _size Max array size
* \param[in] _values Array values buffer
*/
#define BCMCLI_MAKE_PARM_ARRAY(_name, _descr, _type, _flags, _size, _values) \
{ .name=(_name), .description=(_descr), .type=(_type), .flags=(_flags),\
.max_array_size=(_size), .values=(_values) }
/** Helper macro: make simple parameter for arrays of enums
* \param[in] _name Parameter name
* \param[in] _descr Parameter description
* \param[in] _type Parameter type
* \param[in] _flags Parameter flags
* \param[in] _size Max array size
* \param[in] _values Array values buffer
* \param[in] _enum_table An array of enums that may be in the array
*/
#define BCMCLI_MAKE_PARM_ENUM_ARRAY(_name, _descr, _type, _flags, _size, _values, _enum_table) \
{ .name=(_name), .description=(_descr), .type=(_type), .flags=(_flags),\
.max_array_size=(_size), .values=(_values), .enum_table=(_enum_table) }
/** Helper macro: make range parameter
* \param[in] _name Parameter name
* \param[in] _descr Parameter description
* \param[in] _type Parameter type
* \param[in] _flags Parameter flags
* \param[in] _min Min value
* \param[in] _max Max value
*/
#define BCMCLI_MAKE_PARM_RANGE(_name, _descr, _type, _flags, _min, _max) \
{ .name=(_name), .description=(_descr), .type=(_type), .flags=(_flags) | BCMCLI_PARM_FLAG_RANGE, \
.low_val=(_min), .hi_val=(_max) }
/** Helper macro: make range parameter for arrays with range
* \param[in] _name Parameter name
* \param[in] _descr Parameter description
* \param[in] _type Parameter type
* \param[in] _flags Parameter flags
* \param[in] _size Max array size
* \param[in] _values Array values buffer
* \param[in] _min Min value
* \param[in] _max Max value
*/
#define BCMCLI_MAKE_PARM_ARRAY_RANGE(_name, _descr, _type, _flags, _size, _values, _min, _max) \
{ .name=(_name), .description=(_descr), .type=(_type), .flags=(_flags) | BCMCLI_PARM_FLAG_RANGE,\
.max_array_size=(_size), .values=(_values), .low_val=(_min), .hi_val=(_max) }
/** Helper macro: make parameter with default value
* \param[in] _name Parameter name
* \param[in] _descr Parameter description
* \param[in] _type Parameter type
* \param[in] _flags Parameter flags
* \param[in] _dft Default value
*/
#define BCMCLI_MAKE_PARM_DEFVAL(_name, _descr, _type, _flags, _dft) \
{ .name=(_name), .description=(_descr), .type=(_type), .flags=(_flags) | BCMCLI_PARM_FLAG_DEFVAL, \
.value = {{_dft}} }
/** Helper macro: make range parameter with default value
* \param[in] _name Parameter name
* \param[in] _descr Parameter description
* \param[in] _type Parameter type
* \param[in] _flags Parameter flags
* \param[in] _min Min value
* \param[in] _max Max value
* \param[in] _dft Default value
*/
#define BCMCLI_MAKE_PARM_RANGE_DEFVAL(_name, _descr, _type, _flags, _min, _max, _dft) \
{ .name=(_name), .description=(_descr), .type=(_type), \
.flags=(_flags) | BCMCLI_PARM_FLAG_RANGE | BCMCLI_PARM_FLAG_DEFVAL, \
.low_val=(_min), .hi_val=(_max), .value = {{_dft}} }
/** Helper macro: make enum parameter
* \param[in] _name Parameter name
* \param[in] _descr Parameter description
* \param[in] _values Enum values table
* \param[in] _flags Parameter flags
*/
#define BCMCLI_MAKE_PARM_ENUM(_name, _descr, _values, _flags) \
{ .name=(_name), .description=(_descr), .type=BCMCLI_PARM_ENUM, .flags=(_flags), .enum_table=(_values)}
/** Helper macro: make enum parameter with default value
* \param[in] _name Parameter name
* \param[in] _descr Parameter description
* \param[in] _values Enum values table
* \param[in] _flags Parameter flags
* \param[in] _dft Default value
*/
#define BCMCLI_MAKE_PARM_ENUM_DEFVAL(_name, _descr, _values, _flags, _dft) \
{ .name=(_name), .description=(_descr), .type=BCMCLI_PARM_ENUM, .flags=(_flags) | BCMCLI_PARM_FLAG_DEFVAL,\
.low_val=0, .hi_val=0, .value={{.string=_dft}}, .enum_table=(_values) }
/** Helper macro: make enum mask parameter
* \param[in] _name Parameter name
* \param[in] _descr Parameter description
* \param[in] _values Enum values table
* \param[in] _flags Parameter flags
*/
#define BCMCLI_MAKE_PARM_ENUM_MASK(_name, _descr, _values, _flags) \
{ .name=(_name), .description=(_descr), .type=BCMCLI_PARM_ENUM_MASK, .flags=(_flags), \
.low_val=0, .hi_val=0, .value={}, .enum_table=(_values) }
/** Helper macro: make enum_mask parameter with default value
* \param[in] _name Parameter name
* \param[in] _descr Parameter description
* \param[in] _values Enum values table
* \param[in] _flags Parameter flags
* \param[in] _dft Default value
*/
#define BCMCLI_MAKE_PARM_ENUM_MASK_DEFVAL(_name, _descr, _values, _flags, _dft) \
{ .name=(_name), .description=(_descr), .type=BCMCLI_PARM_ENUM_MASK, .flags=(_flags) | BCMCLI_PARM_FLAG_DEFVAL,\
.low_val=0, .hi_val=0, .value={{.string=_dft}}, .enum_table=(_values) }
/** Helper macro: make enum-selector parameter
* \param[in] _name Parameter name
* \param[in] _descr Parameter description
* \param[in] _values Selector values table
* \param[in] _flags Parameter flags
*/
#define BCMCLI_MAKE_PARM_SELECTOR(_name, _descr, _values, _flags) \
{ .name=(_name), .description=(_descr), .type=BCMCLI_PARM_ENUM, .flags=(_flags) | BCMCLI_PARM_FLAG_SELECTOR,\
.low_val=0, .hi_val=0, .value={}, .enum_table=(_values) }
/** Helper macro: make buffer parameter
* \param[in] _name Parameter name
* \param[in] _descr Parameter description
* \param[in] _flags Parameter flags
* \param[in] _buf Memory buffer associated with the parameter
* \param[in] _size Buffer size
*/
#define BCMCLI_MAKE_PARM_BUFFER(_name, _descr, _flags, _buf, _size) \
{ .name=(_name), .description=(_descr), .type=BCMCLI_PARM_BUFFER, \
.flags=(_flags), .value = {{.buffer = {.start = _buf, .curr = _buf, .len = _size}}} }
/** Helper macro: make struct parameter
* \param[in] _name Parameter name
* \param[in] _descr Parameter description
* \param[in] _flags Parameter flags
* \param[in] _fields Structure fields
*/
#define BCMCLI_MAKE_PARM_STRUCT(_name, _descr, _flags, _fields) \
{ .name=(_name), .description=(_descr), .type=BCMCLI_PARM_STRUCT, \
.flags=(_flags), .value.fields = _fields }
/** Register command without parameters helper */
#define BCMCLI_MAKE_CMD_NOPARM(dir, cmd, help, cb) \
{\
bcmos_errno bcmcli_cmd_add_err = bcmcli_cmd_add(dir, cmd, cb, help, BCMCLI_ACCESS_ADMIN, NULL, NULL);\
BUG_ON(BCM_ERR_OK != bcmcli_cmd_add_err);\
}
/** Register command helper */
#define BCMCLI_MAKE_CMD(dir, cmd, help, cb, parms...) \
{ \
static bcmcli_cmd_parm cmd_parms[]={ \
parms, \
BCMCLI_PARM_LIST_TERMINATOR \
}; \
bcmos_errno bcmcli_cmd_add_err = bcmcli_cmd_add(dir, cmd, cb, help, BCMCLI_ACCESS_ADMIN, NULL, cmd_parms); \
BUG_ON(BCM_ERR_OK != bcmcli_cmd_add_err);\
}
/** Optional custom directory handlers */
typedef void (*bcmcli_dir_enter_leave_cb)(bcmcli_session *session, bcmcli_entry *dir, int is_enter);
/** Optional command or directory help callback
* \param[in] session Session handle
* \param[in] h Command or directory handle
* \param[in] parms Parameter(s) - the rest of the command string.
* Can be used for example to get help on individual parameters
*/
typedef void (*bcmcli_help_cb)(bcmcli_session *session, bcmcli_entry *h, const char *parms);
/** Extra parameters of monitor directory.
* See \ref bcmcli_dir_add
*
*/
typedef struct bcmcli_dir_extra_parm
{
void *user_priv; /**< private data passed to enter_leave_cb */
bcmcli_dir_enter_leave_cb enter_leave_cb; /**< callback function to be called when session enters/leavs the directory */
bcmcli_help_cb help_cb; /**< Help function called to print directory help instead of the automatic help */
} bcmcli_dir_extra_parm;
/** Extra parameters of monitor command.
* See \ref bcmcli_cmd_add
*
*/
typedef struct bcmcli_cmd_extra_parm
{
bcmcli_help_cb help_cb; /**< Optional help callback. Can be used for more sophisticated help, e.g., help for specific parameters */
uint32_t flags; /**< Command flags */
void (*free_parms)(bcmcli_cmd_parm *parms); /* Optional user-defined free */
} bcmcli_cmd_extra_parm;
/** Monitor command handler prototype */
typedef bcmos_errno (*bcmcli_cmd_cb)(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms);
/** CLI command logging mode */
typedef enum
{
BCMCLI_LOG_NONE, /**< Disable logging */
BCMCLI_LOG_CLI, /**< Log commands as is and rc as CLI comment*/
BCMCLI_LOG_C_COMMENT /**< Log as C comments */
} bcmcli_log_mode;
/** Add subdirectory to the parent directory
*
* \param[in] parent Parent directory handle. NULL=root
* \param[in] name Directory name
* \param[in] help Help string
* \param[in] access_right Access rights
* \param[in] extras Optional directory descriptor. Mustn't be allocated on the stack.
* \return new directory handle or NULL in case of failure
*/
bcmcli_entry *bcmcli_dir_add(bcmcli_entry *parent, const char *name,
const char *help, bcmcli_access_right access_right,
const bcmcli_dir_extra_parm *extras);
/** Scan directory tree and look for directory named "name".
*
* \param[in] parent Directory sub-tree root. NULL=root
* \param[in] name Name of directory to be found
* \return directory handle if found or NULL if not found
*/
bcmcli_entry *bcmcli_dir_find(bcmcli_entry *parent, const char *name);
/** Scan directory tree and look for command named "name".
*
* \param[in] parent Directory sub-tree root. NULL=root
* \param[in] name Name of command to be found
* \return command handle if found or NULL if not found
*/
bcmcli_entry *bcmcli_cmd_find(bcmcli_entry *parent, const char *name);
/** Get token name
* \param[in] token Directory or command token
* \return directory token name
*/
const char *bcmcli_token_name(bcmcli_entry *token);
/** Find the CLI parameter with the specified name (case insensitive).
* \param[in] session CLI session
* \param[in] name Parameter name
* \return The CLI parameter that was found, or NULL if not found
*/
bcmcli_cmd_parm *bcmcli_find_named_parm(bcmcli_session *session, const char *name);
/** Query parameter value status.
* The function can be used for scalar and array parameters
* \param[in] session CLI session
* \param[in] parm Parameter from the array passed to the CLI command handler
* or returned by bcmcli_find_named_parm()
* \param[in] value_index value_index - for array parameters
* \return BCMOS_TRUE if the parameter value is set, BCMOS_FALSE otherwise
*/
bcmos_bool bcmcli_parm_value_is_set(bcmcli_session *session, const bcmcli_cmd_parm *parm, uint32_t value_index);
/** Add CLI command
*
* \param[in] dir Handle of directory to add command to. NULL=root
* \param[in] name Command name
* \param[in] cmd_cb Command handler
* \param[in] help Help string
* \param[in] access_right Access rights
* \param[in] extras Optional extras
* \param[in] parms Optional parameters array. Must not be allocated on the stack!
* If parms!=NULL, the last parameter in the array must have name==NULL.
* \return
* 0 =OK\n
* <0 =error code
*/
bcmos_errno bcmcli_cmd_add(bcmcli_entry *dir, const char *name, bcmcli_cmd_cb cmd_cb,
const char *help, bcmcli_access_right access_right,
const bcmcli_cmd_extra_parm *extras, bcmcli_cmd_parm parms[]);
/** Destroy token (command or directory)
* \param[in] token Directory or command token. NULL=root
*/
void bcmcli_token_destroy(bcmcli_entry *token);
/** Parse and execute input string.
* input_string can contain multiple commands delimited by ';'
*
* \param[in] session Session handle
* \param[in] input_string String to be parsed
* \return
* =0 - OK \n
* -EINVAL - parsing error\n
* other - return code - as returned from command handler.
* It is recommended to return -EINTR to interrupt monitor loop.
*/
bcmos_errno bcmcli_parse(bcmcli_session *session, char *input_string);
/** Read input and parse iteratively until EOF or bcmcli_is_stopped()
*
* \param[in] session Session handle
* \return
* =0 - OK \n
*/
bcmos_errno bcmcli_driver(bcmcli_session *session);
/** Stop monitor driver.
* The function stops \ref bcmcli_driver
* \param[in] session Session handle
*/
void bcmcli_stop(bcmcli_session *session);
/** Returns 1 if monitor session is stopped
* \param[in] session Session handle
* \returns 1 if monitor session stopped by bcmcli_stop()\n
* 0 otherwise
*/
bcmos_bool bcmcli_is_stopped(bcmcli_session *session);
/** Get current directory for the session,
* \param[in] session Session handle
* \return The current directory handle
*/
bcmcli_entry *bcmcli_dir_get(bcmcli_session *session);
/** Set current directory for the session.
* \param[in] session Session handle
* \param[in] dir Directory that should become current
* \return
* =0 - OK
* <0 - error
*/
bcmos_errno bcmcli_dir_set(bcmcli_session *session, bcmcli_entry *dir);
/** Get command that is being executed.
* The function is intended for use from command handler.
* \param[in] session Session handle
* \return The current command handle
*/
bcmcli_entry *bcmcli_cmd_get(bcmcli_session *session);
/* Get CLI entry info
* \param[in] session
* \param[in] entry
* \param[out] is_dir
* \param[out] name
* \param[out] descr
* \param[out] parent
*/
void bcmcli_entry_info_get(bcmcli_session *session, const bcmcli_entry *entry,
bcmos_bool *is_dir, const char **name, const char **descr, const bcmcli_entry **parent);
/** Get parameter number given its name.
* The function is intended for use by command handlers
* \param[in] session Session handle
* \param[in] parm_name Parameter name
* \return
* >=0 - parameter number\n
* <0 - parameter with this name doesn't exist
*/
int bcmcli_parm_number(bcmcli_session *session, const char *parm_name);
/** Get parameter by name
* The function is intended for use by command handlers
* \param[in] session Session handle
* \param[in] parm_name Parameter name
* \return
* parameter pointer or NULL if not found
*/
bcmcli_cmd_parm *bcmcli_parm_get(bcmcli_session *session, const char *parm_name);
/** Check if parameter is set
* The function is intended for use by command handlers
* \param[in] session Session handle
* \param[in] parm Parameter name
* \return
* TRUE if parameter is set, FALSE otherwise
*/
static inline bcmos_bool bcmcli_parm_is_set(bcmcli_session *session, const bcmcli_cmd_parm *parm)
{
bcmos_bool parm_is_set = BCMOS_FALSE;
if (parm)
{
parm_is_set = (parm->flags & BCMCLI_PARM_FLAG_ASSIGNED) ? BCMOS_TRUE : BCMOS_FALSE;
}
return parm_is_set;
}
/** Check if parameter is set
* \param[in] session Session handle
* \param[in] parm_number Parameter number
* \return
* 0 if parameter is set\n
* BCM_ERR_NOENT if parameter is not set
* BCM_ERR_PARM if parm_number is invalid
*/
bcmos_errno bcmcli_parm_check(bcmcli_session *session, int parm_number);
/** Get enum's string value given its internal value
* \param[in] table Enum table
* \param[in] value Internal value
* \return
* enum string value or NULL if internal value is invalid
*/
static inline const char *bcmcli_enum_stringval(const bcmcli_enum_val table[], long value)
{
while(table->name)
{
if (table->val==value)
return table->name;
++table;
}
return NULL;
}
/** Get enum's parameter string value given its internal value
* \param[in] session Session handle
* \param[in] parm Parameter
* \return
* enum string value or NULL if parameter is not enum or
* internal value is invalid
*/
const char *bcmcli_enum_parm_stringval(bcmcli_session *session, const bcmcli_cmd_parm *parm);
/** Print CLI parameter value
* \param[in] session Session handle
* \param[in] parm Parameter
*/
void bcmcli_parm_print(bcmcli_session *session, const bcmcli_cmd_parm *parm);
/* Redefine bcmcli_session_print --> bcmcli_print */
#define bcmcli_print bcmcli_session_print
/** Enable / disable CLI command logging
* \param[in] mode Logging flags
* \param[in] session Log session. Must be set if mode != BCMCLI_CMD_LOG_NONE
* \return 0=OK or error <0
*/
bcmos_errno bcmcli_log_set(bcmcli_log_mode mode, bcmcli_session *session);
/** Write string to CLI log.
* The function is ignored if CLI logging is not enabled using bcmcli_log_set()
* \param[in] format printf-like format followed by arguments
*/
void bcmcli_log(const char *format, ...);
#ifdef __cplusplus
}
#endif
/** @} end bcm_cli group */
#endif /* #ifndef BCM_CLI_H */
<file_sep># grpc - Google RPC
#
include(third_party)
bcm_3rdparty_module_name(grpc "1.26.0")
bcm_3rdparty_add_dependencies(protobuf zlib openssl cares)
bcm_3rdparty_download_wget("https://github.com/grpc/grpc/archive" "v${GRPC_VERSION}.tar.gz")
bcm_3rdparty_add_build_options(-DgRPC_CARES_PROVIDER=package -DgRPC_PROTOBUF_PROVIDER=package)
bcm_3rdparty_add_build_options(-DgRPC_ZLIB_PROVIDER=package -DgRPC_SSL_PROVIDER=package)
bcm_3rdparty_add_build_options(-DZLIB_LIBRARIES=z)
bcm_3rdparty_add_build_options(-DgRPC_BUILD_TESTS=OFF)
bcm_3rdparty_add_build_options(-DgRPC_BUILD_GRPC_RUBY_PLUGIN=OFF -DgRPC_BUILD_GRPC_PHP_PLUGIN=OFF)
bcm_3rdparty_add_build_options(-DgRPC_BUILD_GRPC_NODE_PLUGIN=OFF -DgRPC_BUILD_GRPC_CSHARP_PLUGIN=OFF)
bcm_3rdparty_add_build_options(-DgRPC_BUILD_GRPC_OBJECTIVE_C_PLUGIN=OFF)
if(NOT BCM_CONFIG_HOST MATCHES "x86")
bcm_3rdparty_add_build_options(-DgRPC_BUILD_CODEGEN=OFF)
bcm_3rdparty_add_build_options(-DProtobuf_PROTOC_EXECUTABLE=${CMAKE_BINARY_DIR}/../host-sim/fs/bin/protoc)
else()
set(_GRPC_REFLECTION -lgrpc++_reflection)
endif()
bcm_3rdparty_add_cflags(-std=c++11)
bcm_3rdparty_build_cmake()
bcm_3rdparty_export(rt -lgrpc++ -lgrpc -Wl,--no-as-needed ${_GRPC_REFLECTION} -Wl,--as-needed -laddress_sorting -lcares -lssl -lz -lgpr -lupb -lcrypto)
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
/*
* bcmos_system.h
* Maple System Services
* posix port: simulation
*/
#ifndef BCMOS_SYSTEM_H_
#define BCMOS_SYSTEM_H_
#if (!defined(__cplusplus) && !defined(_GNU_SOURCE))
#define _GNU_SOURCE
#endif
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <stdio.h>
#include <assert.h>
#include <stdint.h>
#include <ctype.h>
#include <stddef.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h>
#include <semaphore.h>
#include <signal.h>
#include <execinfo.h>
#include <limits.h>
#include <stdarg.h>
#include <sys/select.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <math.h>
#include <inttypes.h>
/* posix port has only been tested in linux user space */
#define LINUX_USER_SPACE
/* Re-define GNU typeof as ISO __typeof__ */
#define typeof __typeof__
void _bcmos_backtrace(void);
#define BUG_ON_PRINT(condition, fmt, args...) \
do \
{ \
if (condition) \
{ \
BCMOS_TRACE_ERR(fmt, ##args); \
BCMOS_TRACE_ERR("Condition: " #condition); \
abort(); \
} \
} while (0)
#define BUG_ON(condition) BUG_ON_PRINT((condition), "BUG in %s %d!\n", __FUNCTION__, __LINE__)
#define BUG() BUG_ON(1)
#define BUG_UNLESS(condition) BUG_ON(!(condition))
/* If 'err' is not BCM_ERR_OK, there is a bug in the software - halt and print the specified message */
#define BUG_ON_ERROR(err, fmt, args...) \
BUG_ON_PRINT((err) != BCM_ERR_OK, \
"%s:%d: err=%s (%d): " fmt, \
__FUNCTION__, __LINE__, bcmos_strerror(err), (err), ##args)
/* Specify here which system functions are inlined */
#define BCMOS_FASTLOCK_INLINE
/* #define BCMOS_SEM_WAIT_INLINE */
#define BCMOS_SEM_POST_INLINE
#define BCMOS_TRACE_PRINTF
/* #define BCMOS_BYTE_POOL_ALLOC_FREE_INLINE */
/* #define BCMOS_MALLOC_FREE_INLINE */
/* #define BCMOS_CALLOC_INLINE */
/* #define BCMOS_DMA_ALLOC_FREE_INLINE */
#define BCMOS_VIRT_TO_PHYS_INLINE
#define BCMOS_CACHE_INLINE
/* Supports file IO */
#define BCMOS_FILE_IO_OS_SPECIFIC
#include "bcmos_common.h"
/* posix-specific stuff */
/*
* Synchronization
*/
/** \addtogroup system_mutex
* @{
*/
/** Mutex control block */
struct bcmos_mutex
{
pthread_mutex_t m; /**< pthread mutex */
pthread_mutexattr_t attr; /**< pthread mutex attribute */
};
/** @} system_mutex */
/** \addtogroup system_fastlock
* @{
*/
/** Fast lock control block */
struct bcmos_fastlock
{
bcmos_mutex m;
};
/** Fastlock initializer. Can be used instead of calling bcmos_fastlock_init() */
#define BCMOS_FASTLOCK_INITIALIZER { { PTHREAD_MUTEX_INITIALIZER } }
/* Init fastlock */
static inline void bcmos_fastlock_init(bcmos_fastlock *lock, uint32_t flags)
{
bcmos_mutex_create(&lock->m, 0, NULL);
}
/* Take fast lock */
static inline long bcmos_fastlock_lock(bcmos_fastlock *lock)
{
bcmos_mutex_lock(&lock->m);
return 0;
}
/* Release fast lock */
static inline void bcmos_fastlock_unlock(bcmos_fastlock *lock, long flags)
{
bcmos_mutex_unlock(&lock->m);
}
/** @} system_fastlock */
/** \addtogroup system_sem
* @{
*/
/** Semaphore control block */
struct bcmos_sem
{
sem_t s; /**< pthread semaphore */
};
/* Increment semaphore counter */
static inline void bcmos_sem_post(bcmos_sem *sem)
{
sem_post(&sem->s);
}
/** @} system_sem */
/** \addtogroup system_timer
* @{
*/
/** System timer */
struct bcmos_sys_timer
{
timer_t t; /**< librt timer */
bcmos_sys_timer_handler handler; /**< Timer handler */
bcmos_bool destroyed; /**< BCMOS_TRUE if the timer has been destroyed */
void *data; /**< Parameter to be passed to the handler */
};
/** @} system_timer */
/** \addtogroup system_task
* @{
*/
/* Default stack size (bytes).
* PTHREAD_STACK_MIN will be added to this value when creating threads (to account for OS overheads). */
#define BCMOS_DEFAULT_STACK_SIZE (80 * 1024)
/** OS-specific task control block extension */
typedef struct bcmos_sys_task
{
pthread_t t; /**< posix pthread */
} bcmos_sys_task;
/** @} system_task */
/** \addtogroup byte_pool
* @{
*/
/** Memory pool control block */
struct bcmos_byte_pool
{
bcmos_byte_pool_parm parm; /**< Pool parameters */
uint32_t allocated; /**< Number of bytes allocated */
#ifdef BCMOS_MEM_CHECK
uint32_t magic; /**< magic number */
#define BCMOS_BYTE_POOL_VALID (('b'<<24) | ('y' << 16) | ('p' << 8) | 'o')
#define BCMOS_BYTE_POOL_DELETED (('b'<<24) | ('y' << 16) | ('p' << 8) | '~')
#endif
};
/** @} */
/* Print */
#define bcmos_sys_vprintf(fmt, args) vprintf(fmt, args)
/* A few macros to enable linux kernel space compilation */
#define EXPORT_SYMBOL(_sym)
/*
* The following low-level functions are mostly for simulation
*/
/*
* DMA-able memory allocation
*/
#define BCMOS_DMA_ADDR_T_DEFINED
typedef unsigned long dma_addr_t;
/* Convert virtual address to physical address */
static inline unsigned long bcmos_virt_to_phys(volatile void *va)
{
return (unsigned long)(va);
}
/* Invalidate address area in data cache. Dirty cache lines content is discarded. */
static inline void bcmos_dcache_inv(void *start, uint32_t size)
{
}
/* Flush address area in data cache. Dirty cache lines are committed to memory. */
static inline void bcmos_dcache_flush(void *start, uint32_t size)
{
}
/* write barrier */
static inline void bcmos_barrier(void)
{
}
/* Write 32 bit word to address across PCIs bus */
void bcm_pci_write32(volatile uint32_t *address, uint32_t value);
/* Read 32 bit word across PCIE bus */
uint32_t bcm_pci_read32(const volatile uint32_t *address);
/* Check in-irq status */
static inline bcmos_bool is_irq_mode(void)
{
return BCMOS_FALSE;
}
/* Check if interrupts are disabled */
static inline bcmos_bool is_irq_disabled(void)
{
return BCMOS_FALSE;
}
/* High-precision sleep is not available in POSIX, so fall back to default sleep. */
static inline void bcmos_precision_usleep(uint32_t timeout)
{
bcmos_usleep(timeout);
}
#ifdef SIMULATION_BUILD
#define BCMOS_IRQ_SINGLE 0
#define BCMOS_IRQ_SHARED 1
#define BCMOS_IRQ_EDGE_TRIGGERED 2
/* Fire interrupt if enabled */
void bcmos_int_fire(int irq);
#endif
/*
* Internal (to OS abstraction) functions for messaging over domain and UDP sockets
*/
#ifdef BCMOS_MSG_QUEUE_DOMAIN_SOCKET
bcmos_errno bcmos_sys_msg_queue_domain_socket_open(bcmos_msg_queue *queue);
#endif
#ifdef BCMOS_MSG_QUEUE_UDP_SOCKET
bcmos_errno bcmos_sys_msg_queue_udp_socket_open(bcmos_msg_queue *queue);
#endif
/* 2nd part of OS-independent declarations */
#include "bcmos_common2.h"
#endif /* BCMOS_SYSTEM_H_ */
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#include <bcm_tr451_polt_internal.h>
// Task that handles transmission of OMCI packets received from ONUs to vOMCI
static int _client_tx_task_handler(long data)
{
bcmos_task *self = bcmos_task_current();
BcmPoltClient *owner = (BcmPoltClient *)data;
while (!self->destroy_request)
{
VomciConnection *connection = owner->connection();
bcmos_errno err;
if (connection == nullptr)
continue; // Paranoya
err = connection->WaitForPacketFromOnu();
if (err != BCM_ERR_OK && err != BCM_ERR_TIMEOUT)
break;
OmciPacketEntry *omci_packet = connection->PopPacketFromOnuFromTxQueue();
if (omci_packet == nullptr)
continue;
// Convert to gRPC and transmit
if (owner->OmciTxToVomci(omci_packet) == BCM_ERR_OK)
{
++connection->stats.packets_onu_to_vomci_sent;
}
else
{
++connection->stats.packets_onu_to_vomci_disc;
}
}
self->destroyed = BCMOS_TRUE;
return 0;
}
BcmPoltClient::BcmPoltClient(const tr451_client_endpoint *ep):
GrpcProcessor(GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_CLIENT, ep->name),
endpoint_(ep->name, ep->local_name)
{
connection_ = nullptr;
listen_context_ = nullptr;
const tr451_endpoint *entry;
STAILQ_FOREACH(entry, &ep->entry_list, next)
{
endpoint_.AddEntry(entry);
}
}
BcmPoltClient::~BcmPoltClient()
{
Stop();
BCM_POLT_LOG(INFO, "client '%s': Destroyed\n", endpoint_.name());
}
void BcmPoltClient::CancelListenForVomciTx()
{
if (listen_context_ != nullptr)
{
listen_context_->TryCancel();
while (listen_context_ != nullptr)
{
bcmos_usleep(10000);
}
}
}
// Stop client
void BcmPoltClient::Stop()
{
if (!stopping)
{
stopping = true;
CancelListenForVomciTx();
Disconnected();
GrpcProcessor::Stop();
BCM_POLT_LOG(INFO, "client %s: Stopped\n", endpoint_.name());
}
}
bcmos_errno BcmPoltClient::Connect(const Endpoint *entry)
{
bool ready = false;
// Create a channel to the server
string host_port = entry->host_name() + string(":") + std::to_string(entry->port());
while(!ready)
{
// See if authentication is required
string my_key, my_cert, peer_cert;
bool use_auth = false;
grpc::SslCredentialsOptions sslOpts;
grpc::ChannelArguments channelArgs;
if (bcm_tr451_auth_data(my_key, my_cert, peer_cert))
{
sslOpts.pem_root_certs = peer_cert;
sslOpts.pem_private_key = my_key;
sslOpts.pem_cert_chain = my_cert;
channelArgs.SetSslTargetNameOverride(entry->name());
use_auth = true;
}
BCM_POLT_LOG(INFO, "client %s.%s: establishing %s connection with the server at %s:%u\n",
endpoint_.name(), entry->name(),
use_auth ? "ssl" : "unsecured",
entry->host_name(), entry->port());
channel_ = grpc::CreateCustomChannel(host_port,
use_auth ? grpc::SslCredentials(sslOpts) : grpc::InsecureChannelCredentials(), channelArgs);
if (channel_ == nullptr || channel_->GetState(true) == GRPC_CHANNEL_SHUTDOWN)
{
BCM_POLT_LOG(ERROR, "client %s.%s: couldn't connect with the server at %s:%u.\n",
endpoint_.name(), entry->name(), entry->host_name(), entry->port());
bcmos_usleep(1*1000000);
continue;
}
ready = true;
}
return BCM_ERR_OK;
}
// Send Hello
bcmos_errno BcmPoltClient::Hello(const Endpoint *entry)
{
hello_stub_ = ::tr451_vomci_sbi_service::v1::VomciHelloSbi::NewStub(channel_);
ClientContext context;
HelloVomciRequest hello_request;
HelloVomciResponse hello_response;
Status status;
::tr451_vomci_sbi_message::v1::Hello *olt = new ::tr451_vomci_sbi_message::v1::Hello();
olt->set_endpoint_name(endpoint_.name_for_hello());
hello_request.set_allocated_local_endpoint_hello(olt);
status = hello_stub_->HelloVomci(&context, hello_request, &hello_response);
if (!status.ok())
{
BCM_POLT_LOG(INFO, "client %s.%s: 'hello' exchange with server at %s:%u failed. Re-connecting..\n",
endpoint_.name(), entry->name(), entry->host_name(), entry->port());
return BCM_ERR_IO;
}
const char *vomci_name = nullptr;
if (hello_response.has_remote_endpoint_hello())
vomci_name = hello_response.remote_endpoint_hello().endpoint_name().c_str();
if (vomci_name == nullptr || !*vomci_name)
vomci_name = endpoint_.name();
BCM_POLT_LOG(INFO, "client %s.%s: 'hello' exchange with the server at %s:%u completed: connected to vomci %s\n",
endpoint_.name(), entry->name(), entry->host_name(), entry->port(), vomci_name);
if (connection_ != nullptr)
delete connection_;
connection_ = new VomciConnection(this, entry->name(), endpoint_.name_for_hello(), vomci_name);
connection_->setConnected(true);
return BCM_ERR_OK;
}
// Listen for OMCI messages from vOMCI
void BcmPoltClient::ListenForVomciTx()
{
CancelListenForVomciTx(); // cancel old call if any
listen_context_ = new ClientContext();
Empty request;
std::unique_ptr< ::grpc::ClientReaderInterface<VomciMessage>> reader(
message_stub_->ListenForVomciRx(listen_context_, request));
VomciMessage tx_msg;
while (connection_ != nullptr && reader->Read(&tx_msg))
{
if (!tx_msg.has_omci_packet_msg())
{
BCM_POLT_LOG(INFO, "%s: Received message is not a packet. Ignored\n", endpoint_.name());
continue;
}
OmciTxToOnu(tx_msg.omci_packet_msg(), connection_ ? connection_->peer() : nullptr);
}
reader->Finish();
// There appears to be a race-condition bug in grpc library.
// It sometimes crashes when attempty to destroy mutex that another grpc task still waiting on
// sleep a little here
bcmos_usleep(10000);
delete listen_context_;
listen_context_ = nullptr;
}
void BcmPoltClient::Disconnected()
{
// Diosconnected. Delete stale connection
if (connection_ != nullptr)
{
bcmos_task_destroy(&tx_task_);
delete connection_;
connection_ = nullptr;
}
}
bcmos_errno BcmPoltClient::Start()
{
bcmos_errno err = BCM_ERR_OK;
if (endpoint_.entry(nullptr) == nullptr)
{
BCM_POLT_LOG(INFO, "client %s: no remote entries\n", endpoint_.name());
return BCM_ERR_PARM;
}
// Iterate over endpoint entries until connected
do
{
// Connect with the server and send 'hello'
const Endpoint *entry = NULL;
do
{
entry = endpoint_.entry(entry);
if (entry == NULL)
continue;
err = Connect(entry);
// Connected. Now send Hello
err = err ? err : Hello(entry);
if (err != BCM_ERR_OK)
{
bcmos_usleep(1*1000000);
continue;
}
} while (err != BCM_ERR_OK && !stopping);
if (stopping)
break;
// Create stub interface for message exchange
message_stub_ = ::tr451_vomci_sbi_service::v1::VomciMessageSbi::NewStub(channel_);
// Create TX task
bcmos_errno err;
bcmos_task_parm tp = {};
tp.name = endpoint_.name();
tp.priority = TASK_PRIORITY_TRANSPORT_PROXY;
tp.handler = _client_tx_task_handler;
tp.data = (long)this;
err = bcmos_task_create(&tx_task_, &tp);
if (err != BCM_ERR_OK)
{
BCM_POLT_LOG(ERROR, "client %s: can't create TX task. Terminated.\n",
endpoint_.name());
return err;
}
// Now send ListenForOmciRx() request. It will block
ListenForVomciTx();
Disconnected();
} while (!stopping);
return BCM_ERR_OK;
}
// Forward message received from ONU to vOMCI
bcmos_errno BcmPoltClient::OmciTxToVomci(OmciPacket *grpc_omci_packet)
{
ClientContext context;
::google::protobuf::Empty response;
Status status;
VomciMessage msg;
msg.set_allocated_omci_packet_msg(grpc_omci_packet);
status = message_stub_->VomciTx(&context, msg, &response);
return status.ok() ? BCM_ERR_OK: BCM_ERR_IO;
}
bcmos_errno bcm_tr451_polt_grpc_client_init(void)
{
return BCM_ERR_OK;
}
bcmos_errno bcm_tr451_polt_grpc_client_create(const tr451_client_endpoint *endpoint)
{
GrpcProcessor *old_client = bcm_grpc_processor_get_by_name(endpoint->name,
GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_CLIENT);
if (old_client != nullptr)
{
BCM_POLT_LOG(ERROR, "client %s already exists\n", endpoint->name);
return BCM_ERR_ALREADY;
}
bcmos_errno err = BCM_ERR_OK;
// Validation
const tr451_endpoint *entry;
if (STAILQ_EMPTY(&endpoint->entry_list))
{
BCM_POLT_LOG(ERROR, "client %s: no entries\n", endpoint->name);
return BCM_ERR_PARM;
}
STAILQ_FOREACH(entry, &endpoint->entry_list, next)
{
if (entry->host_name == nullptr)
{
BCM_POLT_LOG(ERROR, "client %s.%s: host_name is required for client connection\n",
endpoint->name, entry->name);
return BCM_ERR_PARM;
}
if (!entry->port)
{
BCM_POLT_LOG(ERROR, "client %s.%s: port is required for client connection\n",
endpoint->name, entry->name);
return BCM_ERR_PARM;
}
BCM_POLT_LOG(INFO, "Creating client %s: name_for_hello=%s entry %s %s:%u\n",
endpoint->name,
endpoint->local_name ? endpoint->local_name : endpoint->name,
entry->name,
entry->host_name ? entry->host_name : "any", entry->port);
}
// Create and start client
BcmPoltClient *client = new BcmPoltClient(endpoint);
if (bcm_grpc_processor_is_enabled(GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_CLIENT))
{
err = client->CreateTaskAndStart();
}
return err;
}
bcmos_errno bcm_tr451_polt_grpc_client_start(const char *name)
{
GrpcProcessor *entry = bcm_grpc_processor_get_by_name(name,
GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_CLIENT);
if (entry == nullptr)
return BCM_ERR_NOENT;
return entry->CreateTaskAndStart();
}
bcmos_errno bcm_tr451_polt_grpc_client_stop(const char *name)
{
GrpcProcessor *entry = bcm_grpc_processor_get_by_name(name,
GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_CLIENT);
if (entry == nullptr)
return BCM_ERR_NOENT;
BcmPoltClient *client = dynamic_cast<BcmPoltClient *>(entry);
client->Stop();
return BCM_ERR_OK;
}
bcmos_errno bcm_tr451_polt_grpc_client_delete(const char *name)
{
GrpcProcessor *entry = bcm_grpc_processor_get_by_name(name,
GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_CLIENT);
if (entry == nullptr)
return BCM_ERR_NOENT;
BcmPoltClient *client = dynamic_cast<BcmPoltClient *>(entry);
delete client;
return BCM_ERR_OK;
}
// Get client by name
BcmPoltClient *bcm_polt_client_get_by_name(const char *name)
{
GrpcProcessor *entry = bcm_grpc_processor_get_by_name(name,
GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_CLIENT);
return dynamic_cast<BcmPoltClient *>(entry);
}
bcmos_errno bcm_tr451_polt_grpc_client_enable_disable(bcmos_bool enable)
{
return bcm_grpc_processor_enable_disable((bool)enable,
GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_CLIENT);
}
<file_sep># This file is included first in the top level CMakeLists.txt file to provide common definitions for all
# builds. There should be no platform/board/compiler specific settings in this file.
#====
# Common definitions
#====
set(SUBSYSTEM host)
#====
# Skip the install of symbols in the 'fs' directory for the release
#====
set(BCM_INSTALL_STRIP_SYMBOLS n CACHE BOOL "Do not install stripped symbols" FORCE)
#====
# Add a subdirectory within the Aspen system. This is a wrapper on the CMake add_subdirectory that collects
# information on which directories have been added.
#
# @param DIR [in] Directory to add. Can be relative or absolute
# @param OPTIONAL [in] Optional argument indicating it is OK if the directory is not there
#====
macro(bcm_add_subdirectory DIR)
bcm_find_absolute_path(_BCM_ABSOLUTE_DIR ${DIR})
if(IS_DIRECTORY ${_BCM_ABSOLUTE_DIR})
add_subdirectory(${DIR})
else()
# See if the directory is 'optional' or 'exclude_from_release'; otherwise, fatal error
set(_MY_ARGN ${ARGN})
list(FIND _MY_ARGN OPTIONAL _OPTIONAL_INDEX)
list(FIND _MY_ARGN EXCLUDE_FROM_RELEASE _EXCLUDE_INDEX)
if((${_OPTIONAL_INDEX} LESS 0) AND (${_EXCLUDE_INDEX} LESS 0))
bcm_message(FATAL_ERROR "ERROR: Sub-directory, '${DIR}', does not exist")
endif()
endif()
endmacro(bcm_add_subdirectory)
#====
# This is the release directory so we ignore any calls to bcm_release_install
#====
function(bcm_release_install)
endfunction(bcm_release_install)
function(bcm_github_install)
endfunction(bcm_github_install)
#====
# Common compile definitions for all builds
#====
bcm_create_global_compile_definition(BCM_SUBSYSTEM ${SUBSYSTEM})
#====
# CMake checks for unused variables from the command-line. Add intentionally unused variables here.
#====
set(IGNORED_CLI_ARGS ${CMAKE_TOOLCHAIN_FILE})
if(NOT OPEN_SOURCE)
#====
# If the kernel directory exists, create a dummy target for the module dependencies
#====
if(IS_DIRECTORY ${KERNEL_OUTDIR})
add_custom_target(kernel)
set_target_properties(kernel PROPERTIES KERNEL_OUTDIR ${KERNEL_OUTDIR})
elseif(NOT SIMULATION_BUILD)
bcm_message(FATAL_ERROR "ERROR: Kernel objects directory not found: KERNEL_OUTDIR=${KERNEL_OUTDIR}")
endif()
endif()
#====
# If the main board is not set explicitly, it defaults to BOARD
#====
if(NOT MAIN_BOARD)
set(MAIN_BOARD ${BOARD})
endif()
#====
# Define the BCM_MAKE_PROGRAM which we use as '$(MAKE)' so our generated makefiles will use $(MAKE) for
# subtending make calls. This will ensure the original parameters are used in the subtending makes. We
# use this variable instead of the CMAKE_MAKE_PROGRAM.
#====
set(BCM_MAKE_PROGRAM "$(MAKE)")
<file_sep># c-ares - A C library for asynchronous DNS requests
#
include(third_party)
bcm_3rdparty_module_name(cares "1_15_0")
#bcm_3rdparty_add_dependencies(protobuf zlib openssl)
bcm_3rdparty_download_wget("https://github.com/c-ares/c-ares/archive" "cares-${CARES_VERSION}.tar.gz" "c-ares-cares-${CARES_VERSION}")
bcm_3rdparty_build_cmake()
bcm_3rdparty_export()
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
/*******************************************************************
* bcmcli_session.c
*
* CLI engine - session management
*
*******************************************************************/
#include <bcmos_system.h>
#include <bcmolt_utils.h>
#define BCMCLI_INTERNAL
#include <bcmcli_session.h>
static bcmos_fastlock session_lock;
static bcmcli_session *session_list;
static int session_module_initialized;
/*
* Internal functions
*/
static void _bcmcli_session_update_prompt(bcmcli_session *session)
{
if (!session)
return;
if (session->parms.get_prompt)
{
session->parms.get_prompt(session, session->prompt_buf, BCMCLI_MAX_PROMPT_LEN);
session->prompt_buf[BCMCLI_MAX_PROMPT_LEN - 1] = '\0';
}
else
{
session->prompt_buf[0] = '\0';
}
}
static char *_bcmcli_session_gets(bcmcli_session *session, char *buffer, uint32_t size)
{
const char *line = NULL;
_bcmcli_session_update_prompt(session);
#ifdef CONFIG_LIBEDIT
if (session && session->el && session->history)
{
int line_len;
line = (el_gets(session->el, &line_len));
if (!line)
return NULL;
if (line_len > size)
{
bcmos_printf("%s: buffer is too short %u - got %d. Truncated\n",
__FUNCTION__, size, line_len);
}
strncpy(buffer, line, size);
if (*line && *line != '\n' && *line != '#')
history(session->history, &session->histevent, H_ENTER, line);
}
else
#endif
#ifdef CONFIG_LINENOISE
if (session && session->ln_session)
{
char *ln_line = linenoise(session->ln_session, session->prompt_buf, buffer, size);
if (ln_line)
{
if (strlen(ln_line))
{
linenoiseHistoryAdd(session->ln_session, ln_line); /* Add to the history. */
}
else
{
strncpy(buffer, "\n", size-1);
}
buffer[size-1] = 0;
line = buffer;
}
}
else
#endif
{
bcmcli_session_print(session, "%s", session->prompt_buf);
if (session && session->parms.gets)
line = session->parms.gets(session, buffer, size);
else
line = fgets(buffer, size, stdin);
}
return line ? buffer : NULL;
}
#ifdef CONFIG_LIBEDIT
static char *_bcmcli_editline_prompt(EditLine *e)
{
bcmcli_session *session = NULL;
el_get(e, EL_CLIENTDATA, &session);
BUG_ON(session == NULL || session->magic != BCMCLI_SESSION_MAGIC);
_bcmcli_session_update_prompt(session);
return session->prompt_buf;
}
static int _bcmcli_editline_cfn(EditLine *el, char *c)
{
bcmcli_session *session = NULL;
char insert_buf[80];
int c1;
bcmos_errno rc;
el_get(el, EL_CLIENTDATA, &session);
BUG_ON(session == NULL || session->magic != BCMCLI_SESSION_MAGIC);
c1 = session->parms.get_char(session);
/* ToDo: handle \t parameter extension */
while (c1 > 0 && c1 == '\t')
{
const LineInfo *li = el_line(el);
if (li->cursor - li->buffer > sizeof(session->tab_complete_buf))
return -1;
memcpy(session->tab_complete_buf, li->buffer, li->cursor - li->buffer);
session->tab_complete_buf[li->cursor - li->buffer] = 0;
rc = bcmcli_extend(session, session->tab_complete_buf, insert_buf, sizeof(insert_buf));
if (rc)
{
c1 = session->parms.get_char(session);
continue;
}
el_insertstr(el, insert_buf);
printf("\r");
el_set(el, EL_REFRESH, NULL);
c1 = session->parms.get_char(session);
}
if (c1 < 0)
return -1;
*c = c1;
return 1;
}
#endif
/* linenoise line editing library: completion support */
#ifdef CONFIG_LINENOISE
static int _bcmcli_linenoise_read_char(long fd_in, char *c)
{
bcmcli_session *session = (bcmcli_session *)fd_in;
int c1;
c1 = session->parms.get_char(session);
if (c1 < 0)
{
return -1;
}
*c = c1;
return 1;
}
static int _bcmcli_linenoise_write(long fd_out, const char *buf, size_t len)
{
bcmcli_session *session = (bcmcli_session *)fd_out;
/* Use a shortcut for len==1 - which is char-by-char input.
bcmos_printf("%*s", buf, 1) misbehaves on vxw platform,
possibly because it is too slow.
*/
if (len == 1 && !session->parms.write)
{
bcmos_putchar(buf[0]);
return 1;
}
return bcmcli_session_write(session, buf, len);
}
static int _bcmcli_linenoise_tab(linenoiseSession *ln_session, char *buf, size_t buf_size, int *p_pos, const char **help)
{
bcmcli_session *session = NULL;
int pos = *p_pos;
char insert_buf[80]="";
int len;
session = linenoiseSessionData(ln_session);
BUG_ON(session == NULL || session->magic != BCMCLI_SESSION_MAGIC);
bcmolt_strncpy(session->tab_complete_buf, buf, sizeof(session->tab_complete_buf));
bcmolt_string_init(&session->tab_complete_help_string, session->tab_complete_help_buf, sizeof(session->tab_complete_help_buf));
session->tab_complete_mode = BCMOS_TRUE;
bcmcli_extend(session, session->tab_complete_buf, insert_buf, sizeof(insert_buf));
session->tab_complete_mode = BCMOS_FALSE;
len = strlen(buf);
if (pos >=0 && pos < len)
{
bcmolt_strncpy(session->tab_complete_buf, buf, pos + 1);
bcmolt_strncat(session->tab_complete_buf, insert_buf, sizeof(session->tab_complete_buf));
bcmolt_strncat(session->tab_complete_buf, &buf[pos], sizeof(session->tab_complete_buf));
pos += strlen(insert_buf);
}
else
{
bcmolt_strncpy(session->tab_complete_buf, buf, sizeof(session->tab_complete_buf));
bcmolt_strncat(session->tab_complete_buf, insert_buf, sizeof(session->tab_complete_buf));
pos = strlen(session->tab_complete_buf);
}
*p_pos = pos;
bcmolt_strncpy(buf, session->tab_complete_buf, buf_size);
*help = bcmolt_string_get(&session->tab_complete_help_string);
return 1;
}
#endif
/* Default getc function */
static int _bcmcli_session_get_char(bcmcli_session *session)
{
return bcmos_getchar();
}
/** Initialize session management module
* \return
* 0 =OK\n
* <0 =error code
*/
static void bcmcli_session_module_init(void)
{
bcmos_fastlock_init(&session_lock, 0);
session_module_initialized = 1;
}
/** Open management session */
bcmos_errno bcmcli_session_open_user(const bcmcli_session_parm *parm, bcmcli_session **p_session)
{
bcmcli_session *session;
bcmcli_session **p_last_next;
const char *name;
char *name_clone;
uint32_t stack_size;
long flags;
if (!p_session || !parm)
return BCM_ERR_PARM;
#ifndef CONFIG_EDITLINE
if (parm->line_edit_mode == BCMCLI_LINE_EDIT_ENABLE)
{
bcmos_trace(BCMOS_TRACE_LEVEL_ERROR, "Line editing feature is not compiled in. define CONFIG_EDITLINE\n");
return BCM_ERR_NOT_SUPPORTED;
}
#endif
if (!session_module_initialized)
bcmcli_session_module_init();
name = parm->name;
if (!name)
name = "*unnamed*";
stack_size = (parm->stack_size > BCMCLI_SESSION_MIN_STACK_SIZE) ? parm->stack_size : BCMCLI_SESSION_MIN_STACK_SIZE;
session=bcmos_calloc(sizeof(bcmcli_session) + strlen(name) + 1 + parm->extra_size + stack_size);
if (!session)
return BCM_ERR_NOMEM;
session->parms = *parm;
session->stack.start = (char *)session + sizeof(bcmcli_session) + parm->extra_size;
session->stack.size = stack_size;
name_clone = session->stack.start + session->stack.size;
strcpy(name_clone, name);
session->parms.name = name_clone;
if (!session->parms.get_char)
session->parms.get_char = _bcmcli_session_get_char;
#ifdef CONFIG_LIBEDIT
if (!parm->gets && (parm->line_edit_mode == BCMCLI_LINE_EDIT_ENABLE ||
parm->line_edit_mode == BCMCLI_LINE_EDIT_DEFAULT))
{
/* Initialize editline library */
session->el = el_init(session->parms.name, stdin, stdout, stderr);
session->history = history_init();
if (session->el && session->history)
{
el_set(session->el, EL_EDITOR, "emacs");
el_set(session->el, EL_PROMPT, &_bcmcli_editline_prompt);
el_set(session->el, EL_TERMINAL, "xterm");
el_set(session->el, EL_GETCFN, _bcmcli_editline_cfn);
el_set(session->el, EL_CLIENTDATA, session);
history(session->history, &session->histevent, H_SETSIZE, 800);
el_set(session->el, EL_HIST, history, session->history);
}
else
{
bcmos_trace(BCMOS_TRACE_LEVEL_ERROR, "Can't initialize editline library\n");
bcmos_free(session);
return BCM_ERR_INTERNAL;
}
}
#endif
#ifdef CONFIG_LINENOISE
/* Set the completion callback. This will be called every time the
* user uses the <tab> key. */
if (!parm->gets && (parm->line_edit_mode == BCMCLI_LINE_EDIT_ENABLE ||
parm->line_edit_mode == BCMCLI_LINE_EDIT_DEFAULT))
{
linenoiseSessionIO io={.fd_in=(long)session, .fd_out=(long)session,
.read_char=_bcmcli_linenoise_read_char,
.write=_bcmcli_linenoise_write
};
if (linenoiseSessionOpen(&io, session, &session->ln_session))
{
bcmos_trace(BCMOS_TRACE_LEVEL_ERROR, "Can't create linenoise session\n");
bcmos_free(session);
return BCM_ERR_INTERNAL;
}
linenoiseSetCompletionCallback(session->ln_session, _bcmcli_linenoise_tab);
}
#endif
bcmos_mutex_create(&session->write_lock, 0, "cli_session");
session->magic = BCMCLI_SESSION_MAGIC;
flags = bcmos_fastlock_lock(&session_lock);
p_last_next = &session_list;
while(*p_last_next)
p_last_next = &((*p_last_next)->next);
*p_last_next = session;
bcmos_fastlock_unlock(&session_lock, flags);
*p_session = session;
return BCM_ERR_OK;
}
static int bcmcli_session_string_write(bcmcli_session *session, const char *buf, uint32_t size)
{
bcmolt_string *str = bcmcli_session_user_priv(session);
return bcmolt_string_copy(str, buf, size);
}
bcmos_errno bcmcli_session_open_string(bcmcli_session **session, bcmolt_string *str)
{
bcmcli_session_parm sp = { .user_priv = str, .write = bcmcli_session_string_write };
return bcmcli_session_open_user(&sp, session);
}
/** Close management session.
* \param[in] session Session handle
*/
void bcmcli_session_close(bcmcli_session *session)
{
long flags;
BUG_ON(session->magic != BCMCLI_SESSION_MAGIC);
flags = bcmos_fastlock_lock(&session_lock);
if (session==session_list)
session_list = session->next;
else
{
bcmcli_session *prev = session_list;
while (prev && prev->next != session)
prev = prev->next;
if (!prev)
{
bcmos_fastlock_unlock(&session_lock, flags);
bcmos_trace(BCMOS_TRACE_LEVEL_ERROR, "%s: can't find session\n", __FUNCTION__);
return;
}
prev->next = session->next;
}
bcmos_fastlock_unlock(&session_lock, flags);
#ifdef CONFIG_LIBEDIT
if (session->history)
history_end(session->history);
if (session->el)
el_end(session->el);
#endif
#ifdef CONFIG_LINENOISE
if (session->ln_session)
linenoiseSessionClose(session->ln_session);
#endif
bcmos_mutex_destroy(&session->write_lock);
session->magic = BCMCLI_SESSION_MAGIC_DEL;
bcmos_free(session);
}
/** Configure RAW input mode
*
* \param[in] session Session handle
* \param[in] is_raw TRUE=enable raw mode, FALSE=disable raw mode
* \return
* =0 - OK \n
* BCM_ERR_NOT_SUPPORTED - raw mode is not supported\n
*/
bcmos_errno bcmcli_session_raw_mode_set(bcmcli_session *session, bcmos_bool is_raw)
{
#ifdef CONFIG_LINENOISE
int rc;
if (session->parms.gets)
return BCM_ERR_NOT_SUPPORTED;
rc = linenoiseSetRaw(session->ln_session, is_raw);
return (rc == 0) ? BCM_ERR_OK : BCM_ERR_NOT_SUPPORTED;
#else
return BCM_ERR_NOT_SUPPORTED;
#endif
}
/** Default write callback function
* write to stdout
*/
static int _bcmcli_session_write(bcmcli_session *session, const char *buf, uint32_t size)
{
return bcmos_printf("%.*s", size, buf);
}
/** Write function.
* Write buffer to the current session.
* \param[in] session Session handle. NULL=use stdout
* \param[in] buffer output buffer
* \param[in] size number of bytes to be written
* \return
* >=0 - number of bytes written\n
* <0 - output error
*/
int bcmcli_session_write(bcmcli_session *session, const char *buf, uint32_t size)
{
int (*write_cb)(bcmcli_session *session, const char *buf, uint32_t size);
if (session && session->parms.write)
{
BUG_ON(session->magic != BCMCLI_SESSION_MAGIC);
write_cb = session->parms.write;
}
else
write_cb = _bcmcli_session_write;
return write_cb(session, buf, size);
}
/** Read line
* \param[in] session Session handle. NULL=use default
* \param[in,out] buf input buffer
* \param[in] size buf size
* \return
* buf if successful
* NULL if EOF or error
*/
char *bcmcli_session_gets(bcmcli_session *session, char *buf, uint32_t size)
{
return _bcmcli_session_gets(session, buf, size);
}
/** Acquire session write lock.
* This function is useful to print block of data uninterruptible
* in multi-thread context
*/
void bcmcli_session_lock(bcmcli_session *session)
{
if (session == NULL)
return;
bcmos_mutex_lock(&session->write_lock);
}
/** Release session write lock.
*/
void bcmcli_session_unlock(bcmcli_session *session)
{
if (session == NULL)
return;
bcmos_mutex_unlock(&session->write_lock);
}
/** Print function.
* Prints in the context of current session.
* \param[in] session Session handle. NULL=use stdout
* \param[in] format print format - as in printf
* \param[in] ap parameters list. Undefined after the call
*/
void bcmcli_session_vprint(bcmcli_session *session, const char *format, va_list ap)
{
bcmcli_session_lock(session);
if (session && (session->parms.write != NULL || session->tab_complete_mode))
{
BUG_ON(session->magic != BCMCLI_SESSION_MAGIC);
vsnprintf(session->outbuf, sizeof(session->outbuf), format, ap);
session->outbuf[sizeof(session->outbuf) - 1] = 0;
if (session->tab_complete_mode)
bcmolt_string_append(&session->tab_complete_help_string, "%s", session->outbuf);
else
bcmcli_session_write(session, session->outbuf, strlen(session->outbuf));
}
else
{
bcmos_vprintf(format, ap);
}
bcmcli_session_unlock(session);
}
/** Print function.
* Prints in the context of current session.
* \param[in] session Session handle. NULL=use stdout
* \param[in] format print format - as in printf
*/
void bcmcli_session_print(bcmcli_session *session, const char *format, ...)
{
va_list ap;
va_start(ap, format);
bcmcli_session_vprint(session, format, ap);
va_end(ap);
}
/** Get user_priv provoded in session partameters when it was registered
* \param[in] session Session handle. NULL=use stdin
* \return usr_priv value
*/
void *bcmcli_session_user_priv(bcmcli_session *session)
{
if (!session)
return NULL;
BUG_ON(session->magic != BCMCLI_SESSION_MAGIC);
return session->parms.user_priv;
}
/** Get extra data associated with the session
* \param[in] session Session handle. NULL=default session
* \return extra_data pointer or NULL if there is no extra data
*/
void *bcmcli_session_data(bcmcli_session *session)
{
if (!session)
return NULL;
BUG_ON(!(session->magic == BCMCLI_SESSION_MAGIC || session->magic == BCMCLI_SESSION_MAGIC_DEL));
if (session->parms.extra_size <= 0)
return NULL;
return (char *)session + sizeof(*session);
}
/** Get session namedata
* \param[in] session Session handle. NULL=default session
* \return session name
*/
const char *bcmcli_session_name(bcmcli_session *session)
{
if (!session)
return NULL;
BUG_ON(session->magic != BCMCLI_SESSION_MAGIC);
return session->parms.name;
}
/** Get session access righte
* \param[in] session Session handle. NULL=default debug session
* \return session access right
*/
bcmcli_access_right bcmcli_session_access_right(bcmcli_session *session)
{
if (!session)
return BCMCLI_ACCESS_DEBUG;
BUG_ON(session->magic != BCMCLI_SESSION_MAGIC);
return session->parms.access_right;
}
/** Print buffer in hexadecimal format
* \param[in] session Session handle. NULL=use stdout
* \param[in] buffer Buffer address
* \param[in] offset Start offset in the buffer
* \param[in] count Number of bytes to dump
* \param[in] indent Optional indentation string
*/
void bcmcli_session_hexdump(bcmcli_session *session, const void *buffer, uint32_t offset, uint32_t count, const char *indent)
{
bcmos_hexdump((bcmos_msg_print_cb)bcmcli_session_print, session, buffer, offset, count, indent);
}
/** Allocate memory from session stack
*
* \param[in] session Session handle
* \param[in] size Size of memory block to be allocated
* \return address of memory block or NULL
*/
void *bcmcli_session_stack_calloc(bcmcli_session *session, uint32_t size)
{
void *ptr;
size = BCMOS_ROUND_UP(size, sizeof(void *));
if (session->stack.allocated + size > session->stack.size)
return NULL;
ptr = &session->stack.start[session->stack.allocated];
session->stack.allocated += size;
memset(ptr, 0, size);
return ptr;
}
/** Reset session stack
*
* \param[in] session Session handle
*/
void bcmcli_session_stack_reset(bcmcli_session *session)
{
session->stack.allocated = 0;
}
/*
* Exports
*/
EXPORT_SYMBOL(bcmcli_session_open);
EXPORT_SYMBOL(bcmcli_session_close);
EXPORT_SYMBOL(bcmcli_session_write);
EXPORT_SYMBOL(bcmcli_session_vprint);
EXPORT_SYMBOL(bcmcli_session_print);
EXPORT_SYMBOL(bcmcli_session_access_right);
EXPORT_SYMBOL(bcmcli_session_data);
EXPORT_SYMBOL(bcmcli_session_name);
EXPORT_SYMBOL(bcmcli_session_hexdump);
<file_sep># CMake file that has the general GCC configurations. This can be used by both host builds
# and simulation builds.
include(option_macros)
#====
# Set Target related globals
#====
set(OS posix)
set(TOOLCHAIN gcc)
#====
# Make sure the PLATFORM variable represents a good value. It could have '-sim' in the name indicating simulation
# We want the actual platform within CMake.
#====
if("${PLATFORM}" MATCHES "-sim")
string(REPLACE "-sim" "" _PLATFORM_NAME ${PLATFORM})
set(PLATFORM ${_PLATFORM_NAME} CACHE STRING "Embedded platform type" FORCE)
endif()
#====
# Check the compiler with a library instead of executable. The executable CMake tries
# to build and run does not work on all versions of our build servers. Building to
# a library is sufficient to check the compiler and is how it is done in cross-compile.
#====
set(CMAKE_TRY_COMPILE_TARGET_TYPE STATIC_LIBRARY)
#====
# Define the GCC_COMMON_CFLAGS that are common across host cross-compile and simulation
#====
set(GCC_COMMON_CFLAGS -std=c99 -MMD -MP -Werror -Wall -gdwarf-3 -fPIC)
set(GCC_COMMON_CXXFLAGS -MMD -MP -Werror -Wall -gdwarf-3 -fPIC)
add_definitions(-D_XOPEN_SOURCE=600)
if(OPEN_SOURCE)
add_definitions(-DBCM_OPEN_SOURCE)
endif()
if(OPEN_SOURCE_SIM)
add_definitions(-DBCM_OPEN_SOURCE_SIM)
endif()
#====
# Define additional flags for more detailed error checking. These are included in build_macros.cmake
# unless the DISABLE_EXTRA_WARNINGS flag is set in the calling CMakeLists.txt file.
#====
set(BCM_EXTRA_WARNINGS -Wextra -Wcast-align -Wcast-qual -Wchar-subscripts)
set(BCM_EXTRA_WARNINGS ${BCM_EXTRA_WARNINGS} -Wpointer-arith -Wredundant-decls)
set(BCM_EXTRA_WARNINGS ${BCM_EXTRA_WARNINGS} -Wparentheses -Wswitch -Wswitch-default -Wunused -Wuninitialized)
set(BCM_EXTRA_WARNINGS ${BCM_EXTRA_WARNINGS} -Wunused-but-set-variable -Wno-unused-parameter)
set(BCM_EXTRA_WARNINGS ${BCM_EXTRA_WARNINGS} -Wno-sign-compare -Wshadow -Wno-inline)
set(BCM_EXTRA_WARNINGS ${BCM_EXTRA_WARNINGS} -Wno-strict-aliasing -Wno-missing-field-initializers)
set(BCM_EXTRA_C_WARNINGS ${BCM_EXTRA_WARNINGS} -Wbad-function-cast -Wmissing-prototypes -Wnested-externs)
set(BCM_EXTRA_C_WARNINGS ${BCM_EXTRA_C_WARNINGS} -Wstrict-prototypes)
set(BCM_EXTRA_CXX_WARNINGS ${BCM_EXTRA_WARNINGS})
#====
# Set the linker command to use grouping for libraries. This will allow circular dependencies to get resolved.
# The system libraries are added to the end from the cache variable. We have already removed duplicates on the
# system libraries, but need to remove the ';' and add a '-l'. In order for this to work, the list of system
# libraries must be available now, which means they have to be in the cache. We rely on the double call to
# CMake from the Makefile wrapper when there is no cache yet and when CMake files change. This assures that
# the cache variable is set at time of building.
#====
# First set the default linker commands
set(CMAKE_C_LINK_EXECUTABLE "<CMAKE_C_COMPILER> <FLAGS> <CMAKE_C_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> -Wl,--start-group <LINK_LIBRARIES> -Wl,--end-group -Wl,--export-dynamic")
set(CMAKE_CXX_LINK_EXECUTABLE "<CMAKE_CXX_COMPILER> <FLAGS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> -Wl,--start-group <LINK_LIBRARIES> -Wl,--end-group -Wl,--export-dynamic")
set(CMAKE_C_CREATE_SHARED_LIBRARY "<CMAKE_C_COMPILER> <CMAKE_SHARED_LIBRARY_C_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_C_FLAGS> <SONAME_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> -Wl,--start-group <LINK_LIBRARIES> -Wl,--end-group")
set(CMAKE_CXX_CREATE_SHARED_LIBRARY "<CMAKE_CXX_COMPILER> <CMAKE_SHARED_LIBRARY_CXX_FLAGS> <LANGUAGE_COMPILE_FLAGS> <LINK_FLAGS> <CMAKE_SHARED_LIBRARY_CREATE_CXX_FLAGS> <SONAME_FLAG><TARGET_SONAME> -o <TARGET> <OBJECTS> -Wl,--start-group <LINK_LIBRARIES> -Wl,--end-group")
#====
# Now add a macro that will take the given library list and add it to the end of the link command. Note that
# a directory creating an executable or shared library that has system libs and then includes another directory
# that does the same can cause repeated system libs on the link command, if not careful. For this reason we
# temporarily turn the link command into a list so we can remove duplicates, then turn it back to a string.
#
# @param SYS_LIBS [in] System libraries to add at the end of the link
# @param TARGET_TYPE [in] Target type for determining the link commands
#====
macro(bcm_add_system_libraries_to_link SYS_LIBS TARGET_TYPE)
if(DEFINED ${SYS_LIBS})
# Here we consider whether there is a '-' at the head of the list entry indicating we already
# have it in the right form. If no '-', then we prepend a '-l'. This allows special cases like
# '-pthread' vs. 'pthread' to be used.
unset(_MY_SYS_LIBS)
foreach(_SYS_LIB ${${SYS_LIBS}})
string(FIND ${_SYS_LIB} "-" _DASH_LOCATION)
if(${_DASH_LOCATION} LESS 0)
list(APPEND _MY_SYS_LIBS -l${_SYS_LIB})
else()
list(APPEND _MY_SYS_LIBS ${_SYS_LIB})
endif()
endforeach(_SYS_LIB)
# Find the link commands we care about for this target type
if("${TARGET_TYPE}" STREQUAL "SHARED_LIBRARY")
set(_LINK_CMDS CMAKE_C_CREATE_SHARED_LIBRARY CMAKE_CXX_CREATE_SHARED_LIBRARY)
elseif("${TARGET_TYPE}" STREQUAL "EXECUTABLE")
set(_LINK_CMDS CMAKE_C_LINK_EXECUTABLE CMAKE_CXX_LINK_EXECUTABLE)
endif()
# Now go through the link commands, convert them to lists, add system libs, remove duplicates
# and return to a string.
foreach(_LINK_CMD ${_LINK_CMDS})
string(REPLACE " " ";" _LINK_CMD_LIST "${${_LINK_CMD}}")
list(APPEND _LINK_CMD_LIST ${_MY_SYS_LIBS})
list(REMOVE_DUPLICATES _LINK_CMD_LIST)
string(REPLACE ";" " " ${_LINK_CMD} "${_LINK_CMD_LIST}")
endforeach(_LINK_CMD)
endif()
endmacro(bcm_add_system_libraries_to_link)
<file_sep># Netconf modules
if(NETCONF_SERVER)
bcm_module_name(netconf_bbf-xpon)
bcm_module_dependencies(PUBLIC sysrepo libnetconf2 netconf_modules)
bcm_module_header_paths(PUBLIC .)
bcm_module_cflags(PUBLIC -Wno-strict-prototypes)
bcm_module_definitions(PUBLIC -DNETCONF_MODULE_BBF_XPON -DDUMMY_BBF_XPON)
bcm_module_srcs(bbf-xpon.c)
bcm_create_lib_target()
endif()
<file_sep># Daemon support
bcm_module_name(daemon)
if("${OS}" STREQUAL "posix")
bcm_module_srcs(bcmolt_daemon.c)
bcm_module_dependencies(PUBLIC os utils_HDRONLY)
bcm_module_header_paths(PUBLIC .)
bcm_create_lib_target()
# daemon_attach application
bcm_add_subdirectory(attach)
endif()
<file_sep># This file contains CMake macros for building the different module types. This file is included
# in the top level CMakeLists.txt file so that the macros area available to all subdirectories.
# The macros available to the Aspen module CMakeLists.txt files are:
#
# - bcm_module_name(<name>) - Set the Aspen module name. The macro sets the global variable _MOD_NAME.
# Equivalent to the Make 'MOD_NAME'.
# - bcm_module_srcs([RESET] <src files>) - Set the module sources. The source files can be C, C++ or Assembly
# files. The macro appends the source to a global list, _MOD_SRCS, which is then used in rule creation.
# This macro can be called multiple times in a CMakeLists.txt file with additional source files. Equivalent
# to the Make 'srcs'. If the macro is called with the optional RESET parameter, it will reset the global.
# - bcm_module_header_paths(<PUBLIC|PRIVATE|RESET> <paths>) - Set the header paths to include. These can be
# public (included for libraries that have a dependency on this one) or private (only available
# for this library). The paths do not include the -I. The macro appends the paths to a global list,
# _MOD_PUBLIC_HDR or _MOD_PRIVATE_HDR, which are then used in rule creation. This macro can be called
# multiple times in a CMakeLists.txt file with additional paths. Equivalent to the Make 'MOD_INC_DIRS' when
# used with PUBLIC and the Make 'EXTRA_INCLUDES' when used with PRIVATE. If the macro is called with the
# optional RESET parameter, it will reset the global.
# - bcm_module_dependencies(<PUBLIC|PRIVATE|RESET> <dependencies>) - Add target dependencies. These can be
# public (included for libraries that have a dependency on this one) or private (only available
# for this library). The macro appends the dependencies to a global list, _MOD_PUBLIC_DEPS or _MOD_PRIVATE_DEPS,
# which are then used in rule creation. This macro can be called multiple times in a CMakeLists.txt file
# with additional dependencies. Equivalent to the Make 'MOD_DEPS' when used with PUBLIC. If the macro is
# called with the optional RESET parameter, it will reset the global.
# - bcm_module_optional_dependencies(<PUBLIC|PRIVATE|RESET> <dependencies>) - Add target dependencies that can
# be optional. They are only included if the target exists to build them. We check for the target at the
# end of adding all the sub-directories.
# - bcm_module_kernel_dependencies(<PUBLIC|PRIVATE> <dependencies>) - Add kernel dependencies which will pull
# in source files from linux library targets or Module.symvers from linux module targets. These are the
# dependencies that are part of the 'make' command formed to do the kernel build. If PUBLIC is used, then
# header-only dependencies are also added as PUBLIC dependencies on the target.
# - bcm_module_sys_libraries(<library names>) - Add system libraries (e.g. pthread) to the list of libraries
# we link with. These will only be valid with Linux builds, using gcc. The system libraries are added
# to the link command after the -Wl,--end-group.
# - bcm_module_cflags(<PUBLIC|PRIVATE|RESET> <cflags>) - Set the compile flags to use beyond the default.
# This does not include the -D definitions as they are handled by bcm_module_definitions() macro.
# These can be public (included for libraries that have a dependency on this one) or private (only available
# for this library). The macro appends the cflags to a global list, _MOD_PUBLIC_CFLAGS or _MOD_PRIVATE_CFLAGS,
# which are then used in rule creation. This macro can be called multiple times in a CMakeLists.txt file
# with additional compile flags. Equivalent to the Make 'EXTRA_CFLAGS' when used with PRIVATE. If the macro
# is called with the optional RESET parameter, it will reset the global.
# - bcm_module_definitions(<PUBLIC|PRIVATE|RESET> <definitions>) - Set the -D options for the module and must
# include the '-D'. These can be public (included for libraries that have a dependency on this one) or private
# (only available for this library). The macro appends the definitions to a global list, _MOD_PUBLIC_DEFS or
# _MOD_PRIVATE_DEFS, which are then used in rule creation. This macro can be called multiple times in a
# CMakeLists.txt file with additional definitions. Equivalent to the Make 'MOD_DEFS' when used with PUBLIC.
# If the macro is called with the optional RESET parameter, it will reset the global.
# - bcm_module_asm_definitions(<definitions>) - Set the -D options for the module and must include
# the '-D'. These are specifically for assembler definitions and are only supported as 'private'. They
# update the BCM_ASFLAGS locally, so the context is only for the calling module.
# - bcm_module_codegen_output(<paths from custom command>) - The code generation macro calls this one
# to get the output of the custom command that generates the .c/.h files from the model. This is done
# so the bcm_create_*_target() can add a custom target with that output to the target being created.
# Fixes an issue where multiple modules reference generated .h files before they get created.
# - bcm_module_function_overrides(<functions>) - Append to the list of functions that this module "wraps", or overrides.
# This uses the GCC linker --wrap functionality. The modifications to the linker flags will apply to
# any executable that depends on the current module.
#
# - bcm_create_lib_target([NO_RESET]) - Create the rule for building a static library. This macro can
# optionally have the 'NO_RESET' parameter to keep the target creation from clearing all the global
# variables. This can be used when defining multiple targets in a single CMakeLists.txt file. The
# macro will make use of any global variables set by using the bcm_moudle_... macros, above.
# - bcm_create_shared_lib_target() - Create the rule for building a shared library. This macro has an optional
# parameter to indicate the directory to install the resulting library. It will also use the globals created by
# the macros above. This macro call needs to be at the end of the CMakeLists.txt file after any of the
# bcm_module macros, above.
# - bcm_create_app_target() - Create the rule for building an application. This macro has an optional parameter
# to indicate the directory to install the resulting executable. It will also use the globals created by
# the macros above. This macro call needs to be at the end of the CMakeLists.txt file after any of the
# bcm_module macros, above.
# - bcm_create_native_lib_target() - Create the rule for building a library using the native compiler.
# This macro is used for building code generation tools where the resulting tool needs to run on the
# build server, regardless of the cross-compile options.
# - bcm_create_native_app_target() - Create the rule for building an application using the native compiler.
# This macro is used for building code generation tools where the resulting tool needs to run on the
# build server, regardless of the cross-compile options.
# - bcm_create_linux_lib_target() - Create the rule for building a Linux library target. This macro has
# no parameters, but will use the globals created by the macros above. This macro call needs to be at
# the end of the CMakeLists.txt file after any of the bcm_module macros, above.
# - bcm_create_linux_module_target() - Create the rule for building a Linux module. This macro has an optional
# parameter to indicate the directory to install the resulting module. It will also use the globals
# created by the macros above. This macro call needs to be at the end of the CMakeLists.txt file after
# any of the bcm_module macros, above.
#
#======
# Set the Compile and link flags here based on platform/board specific setttings at startup. The
# BCM_<FLAGS> value is set in he cmake/modules/<board|platform>.cmake file.
#======
bcm_stringify_flags(CMAKE_C_FLAGS ${BCM_CFLAGS})
bcm_stringify_flags(CMAKE_CXX_FLAGS ${BCM_CXXFLAGS})
bcm_stringify_flags(CMAKE_ASM_FLAGS ${BCM_ASFLAGS})
bcm_stringify_flags(CMAKE_EXE_LINKER_FLAGS ${BCM_LFLAGS})
# Start with no modules
unset(BCM_ALL_LIB_MODULES CACHE)
unset(BCM_ALL_APP_MODULES CACHE)
unset(BCM_ALL_SHARED_LIB_MODULES CACHE)
unset(BCM_GLOBAL_DEFINITIONS CACHE)
bcm_make_normal_option(CCACHE BOOL "Enable ccache" y)
if(${CCACHE} AND NOT "${TOOLCHAIN}" STREQUAL "armcc")
set(CMAKE_C_COMPILER_LAUNCHER ccache)
endif()
bcm_create_global_compile_definition(BCM_OS ${OS})
bcm_make_normal_option(IGNORE_STRIP BOOL "Ignore the STRIP directive on targets and install the target with symbols" n)
# The release build will set this to 'n' to not pollute the install directory
# We don't need this to be a 'make' option, but we want it in the cache.
set(BCM_INSTALL_STRIP_SYMBOLS y CACHE BOOL "Whether to install stipped symbols or not")
# Define the extension to use for header-only libraries we build internally
set(_HEADER_ONLY_EXT HDRONLY)
set(_KERNEL_EXT kernel)
#======
# PRIVATE: Add in the current directory as a private header if not set as private or public
#======
function(_bcm_add_default_header_paths)
set(_ALL_HDRS ${_MOD_PRIVATE_HDR} ${_MOD_PUBLIC_HDR})
if(${CMAKE_CURRENT_SOURCE_DIR} IN_LIST _ALL_HDRS)
# Current directory is already added
return()
elseif("." IN_LIST _ALL_HDRS)
# Current directory is already added
return()
else()
list(APPEND _MOD_PRIVATE_HDR ${CMAKE_CURRENT_SOURCE_DIR})
set(_MOD_PRIVATE_HDR ${_MOD_PRIVATE_HDR} PARENT_SCOPE)
endif ()
endfunction(_bcm_add_default_header_paths)
#======
# PRIVATE: Macro to create the public and private headers. We use the target_include_directories so the
# header files are transitive.
#
# @param TARGET_NAME [in] Target name to add property to.
#======
macro(_bcm_add_module_headers TARGET_NAME)
# Check if we need to add the current working directory on the default list.
_bcm_add_default_header_paths()
get_target_property(_TARGET_TYPE ${TARGET_NAME} TYPE)
if("${_TARGET_TYPE}" STREQUAL "UTILITY")
# Do nothing for custom targets
elseif(NOT DEFINED _MOD_SRCS)
if(DEFINED _MOD_PUBLIC_HDR)
target_include_directories(${TARGET_NAME} INTERFACE ${_MOD_PUBLIC_HDR})
endif()
else ()
if(DEFINED _MOD_PUBLIC_HDR)
target_include_directories(${TARGET_NAME} PUBLIC ${_MOD_PUBLIC_HDR})
endif()
if(DEFINED _MOD_PRIVATE_HDR)
target_include_directories(${TARGET_NAME} PRIVATE ${_MOD_PRIVATE_HDR})
endif()
endif()
endmacro(_bcm_add_module_headers)
#======
# PRIVATE: Macro to add the dependencies for the module. We use the target_link_libraries so the dependencies
# are transitive.
#
# @param TARGET_NAME [in] Target name to add property to.
#======
macro(_bcm_add_module_dependencies TARGET_NAME)
get_target_property(_TARGET_TYPE ${TARGET_NAME} TYPE)
if("${_TARGET_TYPE}" STREQUAL "UTILITY")
add_dependencies(${TARGET_NAME} ${_MOD_PUBLIC_DEPS} ${_MOD_PRIVATE_DEPS})
elseif(NOT DEFINED _MOD_SRCS)
if(DEFINED _MOD_PUBLIC_DEPS)
target_link_libraries(${TARGET_NAME} INTERFACE ${_MOD_PUBLIC_DEPS})
endif()
else ()
if(DEFINED _MOD_PUBLIC_DEPS)
target_link_libraries(${TARGET_NAME} PUBLIC ${_MOD_PUBLIC_DEPS})
endif()
if(DEFINED _MOD_PRIVATE_DEPS)
target_link_libraries(${TARGET_NAME} PRIVATE ${_MOD_PRIVATE_DEPS})
endif()
foreach(_FUNC ${_MOD_WRAPPED_FUNCS})
target_link_libraries(${TARGET_NAME} PRIVATE "-Wl,--wrap=${_FUNC}")
endforeach(_FUNC)
endif()
endmacro(_bcm_add_module_dependencies)
#======
# PRIVATE: Macro to add the optional dependencies for the module. Since these may not be present, we don't
# add them with the target_link_libraries. In post-processing we will do this if the optional dependency
# is present as a valid target. The target properties, INTERFACE_OPTIONAL_PUBLIC_LIBRARIES,
# INTERFACE_OPTIONAL_PRIVATE_LIBRARIES and INTERFACE_OPTIONAL_INTERFACE_LIBRARIES are used to colocate this
# information with the target.
#
# @param TARGET_NAME [in] Target name to add property to.
#======
macro(_bcm_add_module_optional_dependencies TARGET_NAME)
get_target_property(_TARGET_TYPE ${TARGET_NAME} TYPE)
if(NOT DEFINED _MOD_SRCS)
if(DEFINED _MOD_PUBLIC_OPT_DEPS)
set_target_properties(${TARGET_NAME} PROPERTIES
INTERFACE_OPTIONAL_INTERFACE_LIBRARIES ${_MOD_PUBLIC_OPT_DEPS})
endif()
else ()
if(DEFINED _MOD_PUBLIC_OPT_DEPS)
set_target_properties(${TARGET_NAME} PROPERTIES
INTERFACE_OPTIONAL_PUBLIC_LIBRARIES ${_MOD_PUBLIC_OPT_DEPS})
endif()
if(DEFINED _MOD_PRIVATE_OPT_DEPS)
set_target_properties(${TARGET_NAME} PROPERTIES
INTERFACE_OPTIONAL_PRIVATE_LIBRARIES ${_MOD_PRIVATE_OPT_DEPS})
endif()
endif()
endmacro(_bcm_add_module_optional_dependencies)
#======
# PRIVATE: Macro to add the system libraries to the INTERFACE_SYSTEM_LIBRARIES property so they can be
# added in post-processing at the end of the link. The global variable that collected these for the target
# is _MOD_SYSTEM_LIBS.
#
# @param TARGET_NAME [in] Target name to add property to.
#======
macro(_bcm_add_module_system_libraries TARGET_NAME)
if(DEFINED _MOD_SYSTEM_LIBS)
set_target_properties(${TARGET_NAME} PROPERTIES
INTERFACE_SYSTEM_LIBRARIES "${_MOD_SYSTEM_LIBS}")
endif()
endmacro(_bcm_add_module_system_libraries)
#======
# PRIVATE: Macro to add the cflags for the module. We use the target_compile_options so the cflags are
# transitive.
#
# @param TARGET_NAME [in] Target name to add property to.
#======
macro(_bcm_add_module_cflags TARGET_NAME)
if(NOT DEFINED _MOD_SRCS)
if(_MOD_PUBLIC_CFLAGS)
target_compile_options(${TARGET_NAME} INTERFACE ${_MOD_PUBLIC_CFLAGS})
bcm_stringify_flags(_MY_LINKER_FLAGS ${_MOD_PUBLIC_CFLAGS})
set_target_properties(${TARGET_NAME} PROPERTIES LINK_FLAGS "${_MY_LINKER_FLAGS}")
endif()
else ()
if(NOT "${DISABLE_EXTRA_WARNINGS}")
if(BCM_EXTRA_C_WARNINGS)
bcm_stringify_flags(BCM_WARNING_FLAGS ${BCM_EXTRA_C_WARNINGS})
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${BCM_WARNING_FLAGS}")
bcm_string_remove_duplicates(CMAKE_C_FLAGS ${CMAKE_C_FLAGS})
endif()
if(BCM_EXTRA_CXX_WARNINGS)
bcm_stringify_flags(BCM_WARNING_FLAGS ${BCM_EXTRA_CXX_WARNINGS})
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${BCM_WARNING_FLAGS}")
bcm_string_remove_duplicates(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS})
endif()
endif()
if(_MOD_PUBLIC_CFLAGS)
target_compile_options(${TARGET_NAME} PUBLIC ${_MOD_PUBLIC_CFLAGS})
bcm_stringify_flags(_MY_LINKER_FLAGS ${_MOD_PUBLIC_CFLAGS})
set_target_properties(${TARGET_NAME} PROPERTIES LINK_FLAGS "${_MY_LINKER_FLAGS}")
endif()
if(_MOD_PRIVATE_CFLAGS)
# For private flags, we only apply them to C and CXX files
unset(_C_SOURCE_FILES)
foreach(_SRC ${_MOD_SRCS})
get_source_file_property(_SRC_LANG ${_SRC} LANGUAGE)
if("${_SRC_LANG}" STREQUAL "C" OR "${_SRC_LANG}" STREQUAL "CXX")
list(APPEND _C_SOURCE_FILES ${_SRC})
endif()
endforeach(_SRC)
bcm_stringify_flags(_MY_FLAGS ${_MOD_PRIVATE_CFLAGS})
set_source_files_properties(${_C_SOURCE_FILES} PROPERTIES COMPILE_FLAGS "${_MY_FLAGS}")
set_target_properties(${TARGET_NAME} PROPERTIES LINK_FLAGS "${_MY_LINKER_FLAGS}")
endif()
endif()
endmacro(_bcm_add_module_cflags)
#======
# PRIVATE: Macro to add the definitions for the module. We use the target_compile_definitions so the
# definitions are transitive.
#
# @param TARGET_NAME [in] Target name to add property to.
#======
macro(_bcm_add_module_defs TARGET_NAME)
list(APPEND _MOD_PRIVATE_DEFS ${BCM_DEFINES})
if(NOT DEFINED _MOD_SRCS)
if(DEFINED _MOD_PUBLIC_DEFS)
target_compile_definitions(${TARGET_NAME} INTERFACE ${_MOD_PUBLIC_DEFS})
endif()
else ()
if(DEFINED _MOD_PUBLIC_DEFS)
target_compile_definitions(${TARGET_NAME} PUBLIC ${_MOD_PUBLIC_DEFS})
endif()
if(DEFINED _MOD_PRIVATE_DEFS)
target_compile_definitions(${TARGET_NAME} PRIVATE ${_MOD_PRIVATE_DEFS})
endif()
endif()
endmacro(_bcm_add_module_defs)
#======
# PRIVATE: Macro to check that the required variables are set
# @param ARGN [in] List of variables that are required for the target
#======
macro(_bcm_check_mandatory_variables)
foreach(_MY_MANVAR ${ARGN})
if(NOT DEFINED ${_MY_MANVAR})
file(RELATIVE_PATH _RELATIVE_SOURCE_DIR ${SOURCE_TOP} ${CMAKE_CURRENT_SOURCE_DIR})
message(FATAL_ERROR "${MSG_PREAMBLE} Must define [${ARGN}] in ${_RELATIVE_SOURCE_DIR}/CMakeLists.txt")
endif()
endforeach(_MY_MANVAR)
endmacro(_bcm_check_mandatory_variables)
#======
# PRIVATE: Macro to check that the PUBLIC/PRIVATE setting was passed in
# @param VIS [in] Visibility value
# @param TYPE [in] Who is doing the validation
#======
macro(_bcm_check_visibility_variable VIS TYPE)
if(NOT (("${VIS}" STREQUAL "PUBLIC") OR ("${VIS}" STREQUAL "PRIVATE")))
message(FATAL_ERROR "${MSG_PREAMBLE} Target=${_MOD_NAME} ${TYPE} requires 'PUBLIC' or 'PRIVATE' visibility. Given: '${VIS}'")
endif()
endmacro(_bcm_check_visibility_variable)
#======
# PRIVATE: Macro to determine if a flag is set in the parameters to a bcm_create_*_target() macro. We simply
# look in the list for the given varialble and return TRUE or FALSE depending on if it exists. If the option
# is 'STRIP', we only allow that for the host.
#
# @param ARG_SET [out] TRUE - argument exists / FALSE - argument does not exist
# @param ARG_FLAG [in] Flag we are looking for in the argument list
# @param ARGN [in] list of arguments given to the bcm_create_*_target() macro
#======
macro(_bcm_param_exists ARG_SET ARG_FLAG)
set(_ARG_LIST ${ARGN})
if(("${ARG_FLAG}" STREQUAL "STRIP") AND (("${SUBSYSTEM}" STREQUAL "embedded") OR IGNORE_STRIP))
# Not allowed for embedded and If told to ignore the strip directive (the user wants the unstripped result).
set(${ARG_SET} FALSE)
else()
if(${ARG_FLAG} IN_LIST _ARG_LIST)
set(${ARG_SET} TRUE)
else()
set(${ARG_SET} FALSE)
endif()
endif()
endmacro(_bcm_param_exists)
#======
# PRIVATE: Determine the install directory to use (if any) for the bcm_create_*_target() macro. If the EXPORT
# is set, it means we use the pre-defined install directories (bin, lib). If EXPORT is not set, we look for
# anything left once we've gone through all the possible parameters.
#
# @param INSTALL_DIR [out] Filepath to an install dir, will be ignored if EXPORT was set
# @param ARGN
#======
macro(_bcm_find_install_dir INSTALL_DIR)
# Define the list of possible arguments
set(_POSSIBLE_ARGS EXPORT NO_RESET INTERNAL STRIP RELEASE)
unset(${INSTALL_DIR})
set(_LOCAL_LIST ${ARGN})
_bcm_param_exists(_HAS_EXPORT EXPORT ${ARGN})
if(DEFINED _LOCAL_LIST)
if(NOT ${_HAS_EXPORT})
# Not an export so look for the install directory if it exists. Start by removing the known
# parameters we can have from the argument list. The remainder would be the install dir
list(REMOVE_ITEM _LOCAL_LIST ${_POSSIBLE_ARGS})
list(LENGTH _LOCAL_LIST _LOCAL_LIST_LEN)
if(${_LOCAL_LIST_LEN} EQUAL 1)
set(${INSTALL_DIR} ${_LOCAL_LIST})
elseif(${_LOCAL_LIST_LEN} GREATER 1)
bcm_message(FATAL_ERROR "More than one install directory given: ${_LOCAL_LIST}")
endif()
endif()
endif()
endmacro(_bcm_find_install_dir)
#======
# PRIVATE: Macro to strip the symbols from a shared library or executable and save them as debug symbols
#
# @param TARGET [in] Target we are stripping the symbols from
#======
macro(_bcm_strip_symbols TARGET)
set(_STRIP_OUTPUT_DIR strip)
if("${SUBSYSTEM}" STREQUAL "host")
add_custom_command(TARGET ${TARGET}
POST_BUILD
COMMAND mkdir -p ${_STRIP_OUTPUT_DIR}
COMMAND ${BCM_OBJCOPY} --strip-debug --strip-unneeded $<TARGET_FILE:${TARGET}>
${_STRIP_OUTPUT_DIR}/$<TARGET_FILE_NAME:${TARGET}>
COMMAND ${BCM_OBJCOPY} --only-keep-debug $<TARGET_FILE:${TARGET}>
${_STRIP_OUTPUT_DIR}/${TARGET}.debug_symbols
COMMAND ${BCM_OBJCOPY} --add-gnu-debuglink=${_STRIP_OUTPUT_DIR}/${TARGET}.debug_symbols
${_STRIP_OUTPUT_DIR}/$<TARGET_FILE_NAME:${TARGET}>
COMMAND tar -czf ${_STRIP_OUTPUT_DIR}/${TARGET}.debug_symbols.tar.gz
-C ${_STRIP_OUTPUT_DIR} ${TARGET}.debug_symbols
COMMENT "Stripping symbols from ${TARGET}")
endif()
endmacro(_bcm_strip_symbols)
#======
# PRIVATE: Macro to create the install steps for stripped targets. This must be called after the targets
# 'install' rule.
#
# @param TARGET [in] Target we are stripping the symbols from
# @param INSTALL_DIR [in] Install directory for the target
#======
macro(_bcm_strip_install TARGET INSTALL_DIR)
set(_STRIP_OUTPUT_DIR ${CMAKE_CURRENT_BINARY_DIR}/strip)
if("${SUBSYSTEM}" STREQUAL "host")
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/strip/$<TARGET_FILE_NAME:${TARGET}> DESTINATION ${INSTALL_DIR})
if(BCM_INSTALL_STRIP_SYMBOLS)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/strip/${TARGET}.debug_symbols.tar.gz DESTINATION ${INSTALL_DIR})
endif(BCM_INSTALL_STRIP_SYMBOLS)
endif()
endmacro(_bcm_strip_install)
#======
# PRIVATE: Macro to set the install rule if one is appropriate. Called by the App and Linux Module create macros.
# The given directory is relative to CMAKE_INSTALL_PREFIX defined in the top level CMakeLists.txt file. We also
# propagate the relative directory up so we can create a 'clean' for it. Use the cache for the propagation
# (variable BCM_INSTALL_DIRS).
# @param OUT_STR [out] What status to display for CMake log
# @param TARGET [in] Target to add the install rule for
# @param EXPORT [in] Boolean indicating if the target is to be exported
# @param INSTALL_DIR [in] If not to be exported, this optionally can have an install directory
# @param STRIP [in] Install the stripped version
#======
macro(_bcm_install_target OUT_STR TARGET EXPORT INSTALL_DIR STRIP)
unset(${OUT_STR})
unset(_ADDED_INSTALL_RULE)
if(${EXPORT})
# To be exported so use the defined install directories for the target and generated CMake files
# This is only supported for targets so we don't need to check that.
# If both RUNTIME_OUTPUT_DIRECTORY and RUNTIME_OUTPUT_NAME are set - install specific file
bcm_get_target_property(_TARGET_OUT_DIR ${TARGET} RUNTIME_OUTPUT_DIRECTORY)
bcm_get_target_property(_TARGET_OUT_NAME ${TARGET} RUNTIME_OUTPUT_NAME)
bcm_get_target_property(_TARGET_TYPE ${TARGET} TYPE)
if(NOT DEFINED _TARGET_OUT_DIR OR NOT DEFINED _TARGET_OUT_NAME)
if("${_TARGET_TYPE}" STREQUAL "EXECUTABLE")
set(_INSTALL_DIR bin)
else()
set(_INSTALL_DIR lib)
endif()
if(DEFINED _MOD_PUBLIC_HDR)
# There are public headers we need to export. For that, we need them in the build tree.
# Here we determine if they are in the build tree or not. If they are in the source tree,
# we link the directory to the "install tree", under 'include' and update the header
# information. If they are in the build tree, we leave them.
unset(_MY_MOD_PUBLIC_HDR)
foreach(_HDR ${_MOD_PUBLIC_HDR})
if("${_HDR}" MATCHES "${BUILD_TOP}")
# We can keep the path we have
list(APPEND _MY_MOD_PUBLIC_HDR ${_HDR})
else()
# The directory is in the source tree, so we need to make sure it shows up
# in the install tree.
if(IS_ABSOLUTE ${_HDR})
set(_ABSOLUTE_HDR ${_HDR})
else()
set(_ABSOLUTE_HDR ${CMAKE_CURRENT_SOURCE_DIR}/${_HDR})
endif()
file(RELATIVE_PATH _RELATIVE_HDR ${SOURCE_TOP} ${_ABSOLUTE_HDR})
file(GLOB _MY_HEADERS LIST_DIRECTORIES false RELATIVE ${SOURCE_TOP} ${_ABSOLUTE_HDR}/*.h)
# Link the headers in to the install tree.
foreach(_MY_HEADER ${_MY_HEADERS})
get_filename_component(_DIRNAME ${_MY_HEADER} DIRECTORY)
execute_process(COMMAND mkdir -p ${CMAKE_INSTALL_PREFIX}/include/${_DIRNAME})
execute_process(COMMAND ln -sf ${SOURCE_TOP}/${_MY_HEADER}
${CMAKE_INSTALL_PREFIX}/include/${_MY_HEADER})
endforeach(_MY_HEADER)
# Add the header path from the install directory
list(APPEND _MY_MOD_PUBLIC_HDR $<INSTALL_INTERFACE:${_RELATIEVE_HDR}>)
endif()
endforeach(_HDR)
# Update the public headers for later target properties
set(_MOD_PUBLIC_HDR ${_MY_MOD_PUBLIC_HDR})
endif()
if(IS_DIRECTORY ${CMAKE_INSTALL_PREFIX}/include)
install(TARGETS ${TARGET} DESTINATION ${_INSTALL_DIR} EXPORT ${TARGET} INCLUDES DESTINATION include)
else()
if(${STRIP})
# Add additional install steps for using the stripped version of files
_bcm_strip_install(${TARGET} ${_INSTALL_DIR})
else()
install(TARGETS ${TARGET} DESTINATION ${_INSTALL_DIR} EXPORT ${TARGET})
endif()
endif()
install(EXPORT ${TARGET} DESTINATION target-modules)
set(_ADDED_INSTALL_RULE TRUE)
endif()
elseif(DEFINED ${INSTALL_DIR})
set(_INSTALL_DIR ${${INSTALL_DIR}})
if(TARGET ${TARGET})
# If both RUNTIME_OUTPUT_DIRECTORY and RUNTIME_OUTPUT_NAME are set - install specific file
bcm_get_target_property(_TARGET_OUT_DIR ${TARGET} RUNTIME_OUTPUT_DIRECTORY)
bcm_get_target_property(_TARGET_OUT_NAME ${TARGET} RUNTIME_OUTPUT_NAME)
if(NOT DEFINED _TARGET_OUT_DIR OR NOT DEFINED _TARGET_OUT_NAME)
if(${STRIP})
# Add additional install steps for using the stripped version of files
_bcm_strip_install(${TARGET} ${_INSTALL_DIR})
else()
install(TARGETS ${TARGET} DESTINATION ${_INSTALL_DIR})
endif()
else()
install(FILES ${_TARGET_OUT_DIR}/${_TARGET_OUT_NAME} DESTINATION ${_INSTALL_DIR})
endif()
else()
install(FILES ${TARGET} DESTINATION ${_INSTALL_DIR})
endif()
set(_ADDED_INSTALL_RULE TRUE)
endif()
if(${_ADDED_INSTALL_RULE})
# Add the directory to the list in the cache, but don't store duplicates
list(APPEND BCM_INSTALL_DIRS ${_INSTALL_DIR})
list(REMOVE_DUPLICATES BCM_INSTALL_DIRS)
set(BCM_INSTALL_DIRS ${BCM_INSTALL_DIRS} CACHE STRING "List of Install Directories" FORCE)
set(${OUT_STR} ", install dir '${_INSTALL_DIR}'")
endif()
endmacro(_bcm_install_target)
#======
# PRIVATE: Macro to clear all the lists. Called after the build targets have been added
#======
macro(_bcm_module_globals_clear)
unset(_MOD_SRCS)
unset(_MOD_PUBLIC_HDR)
unset(_MOD_PRIVATE_HDR)
unset(_MOD_PUBLIC_DEPS)
unset(_MOD_PRIVATE_DEPS)
unset(_MOD_PUBLIC_OPT_DEPS)
unset(_MOD_PRIVATE_OPT_DEPS)
unset(_MOD_SYSTEM_LIBS)
unset(_MOD_PUBLIC_CFLAGS)
unset(_MOD_PRIVATE_CFLAGS)
unset(_MOD_PUBLIC_DEFS)
unset(_MOD_PRIVATE_DEFS)
unset(_MOD_CODEGEN_OUTPUT)
unset(_MOD_WRAPPED_FUNCS)
endmacro(_bcm_module_globals_clear)
#======
# PRIVATE: Macro to add all the target specific stuff. Done after the target is defined. By default, these
# are set for _MOD_NAME, but an optional alternative target can be given. The alternate is used when adding
# the kernel module targets for libraries.
#
# @param ARGN [in] Optional alternate target, default is the _MOD_NAME global
#======
macro(_bcm_module_add_target_specifics)
set(_OPTIONAL_MOD_NAME ${ARGN})
if(DEFINED _OPTIONAL_MOD_NAME)
set(_TARGET_NAME ${_OPTIONAL_MOD_NAME})
else()
set(_TARGET_NAME ${_MOD_NAME})
endif()
_bcm_add_module_headers(${_TARGET_NAME})
_bcm_add_module_dependencies(${_TARGET_NAME})
_bcm_add_module_optional_dependencies(${_TARGET_NAME})
_bcm_add_module_system_libraries(${_TARGET_NAME})
_bcm_add_module_cflags(${_TARGET_NAME})
_bcm_add_module_defs(${_TARGET_NAME})
endmacro(_bcm_module_add_target_specifics)
#======
# PRIVATE: Create an interface libary for the given module name. This is used for both the
# ${_MOD_NAME}_${_HEADER_ONLY_EXT} that can be used in place of hard-coded include paths and for Linux kernel
# module dependencies.
#
# @param LIB_NAME [in] What to name the library (e.g. ${_MOD_NAME}_${_HEADER_ONLY_EXT})
# @param EXTENSION [in] Extention to add to the target names
#======
function(_bcm_create_interface_lib LIB_NAME EXTENSION)
add_library(${LIB_NAME} INTERFACE)
# Clear the sources, get the proper dependencies and add headers/dependencies
unset(_MOD_SRCS)
string(REGEX REPLACE "([^;]+)" "\\1_${EXTENSION}" _MOD_PUBLIC_DEPS "${_MOD_PUBLIC_DEPS}")
# Make sure we restore any _HEADER_ONLY_EXT dependencies in the list (the regex would duplicate the extension)
string(REPLACE "_${EXTENSION}_${EXTENSION}" "_${EXTENSION}" _MOD_PUBLIC_DEPS "${_MOD_PUBLIC_DEPS}")
_bcm_add_module_headers(${LIB_NAME})
_bcm_add_module_dependencies(${LIB_NAME})
_bcm_add_module_defs(${LIB_NAME})
# If there is a corresponding codegen target, add a dependency on it for the kernel lib version as well.
# (this is useful for interface libraries, which normally build nothing).
if(DEFINED _MOD_CODEGEN_OUTPUT)
add_dependencies(${LIB_NAME} ${_MOD_NAME}_codegen)
endif()
endfunction(_bcm_create_interface_lib)
#======
# PRIVATE: Add a rule to install the binary in the release tree. We first check that the underlying macro exists
# since it won't in the release_tree.
#
# @param BINARY_NAME [in] Name of the binary we want in the release tree
#======
macro(_bcm_release_binary BINARY_NAME)
if(COMMAND bcm_release_install_binary)
bcm_release_install_binary(${BINARY_NAME})
endif()
endmacro(_bcm_release_binary)
#======
# PRIVATE: Add a per-module global to the cache
#
# @param CACHE_VAR [in] CMake cache variable name to update
# @param CACHE_DESC [in] Description to use for CMake cache entry
# @param ARGN [in] What to add to the CMake cache entry
#======
function(_bcm_add_to_global_cache_var CACHE_VAR CACHE_DESC)
if(ARGN)
list(APPEND ${CACHE_VAR} ${ARGN})
list(REMOVE_DUPLICATES ${CACHE_VAR})
set(${CACHE_VAR} ${${CACHE_VAR}} CACHE STRING "${CACHE_DESC}" FORCE)
endif()
endfunction(_bcm_add_to_global_cache_var)
#======
# Set the Aspen module name. The macro sets the global variable _MOD_NAME. Equivalent to the Make 'MOD_NAME'.
#
# @param MOD_NAME [in] Name of the module to build
#======
macro(bcm_module_name MOD_NAME)
set(_MOD_NAME ${MOD_NAME})
set(${_MOD_NAME}_EXISTS y CACHE BOOL "${_MOD_NAME} Exists" FORCE)
set(${_MOD_NAME}_SRC_DIR ${CMAKE_CURRENT_SOURCE_DIR} CACHE FILEPATH "${_MOD_NAME} Source Directory" FORCE)
set(${_MOD_NAME}_BINARY_DIR ${CMAKE_CURRENT_BINARY_DIR} CACHE FILEPATH "${_MOD_NAME} Build Directory" FORCE)
set(${_MOD_NAME}_PUBLIC_DEPS ${_MOD_PUBLIC_DEPS} CACHE STRING "${_MOD_NAME} Public Dependencies" FORCE)
set(${_MOD_NAME}_PRIVATE_DEPS ${_MOD_PRIVATE_DEPS} CACHE STRING "${_MOD_NAME} Private Dependencies" FORCE)
set(${_MOD_NAME}_PUBLIC_DEFS ${_MOD_PUBLIC_DEFS} CACHE STRING "${_MOD_NAME} Public Definitions" FORCE)
set(${_MOD_NAME}_PRIVATE_DEFS ${_MOD_PRIVATE_DEFS} CACHE STRING "${_MOD_NAME} Private Definitions" FORCE)
# Make sure we start with the default C/CXX flags
bcm_stringify_flags(CMAKE_C_FLAGS ${BCM_CFLAGS})
bcm_stringify_flags(CMAKE_CXX_FLAGS ${BCM_CXXFLAGS})
endmacro(bcm_module_name)
#======
# Set the module sources. The source files can be C, C++ or Assembly files. The macro appends the source
# to a global list, _MOD_SRCS, which is then used in rule creation. This macro can be called multiple times
# in a CMakeLists.txt file with additional source files. Equivalent to the Make 'srcs'. If called with 'RESET',
# this will unset the global variable. The RESET can be used when a single CMakeLists.txt file has multiple
# targets.
#
# @param ARGN [in] Sources to append to the running list (could be 'RESET' as well)
#======
macro(bcm_module_srcs)
if("${ARGV0}" STREQUAL "RESET")
unset(_MOD_SRCS)
else()
# All source files get added to the global
list(APPEND _MOD_SRCS ${ARGN})
endif()
endmacro(bcm_module_srcs)
#======
# Set the header paths to include. These can be public (included for libraries that have a dependency on
# this one) or private (only available for this library). The paths do not include the -I. The macro appends
# the paths to a global list, _MOD_PUBLIC_HDR or _MOD_PRIVATE_HDR, which are then used in rule creation.
# This macro can be called multiple times in a CMakeLists.txt file with additional paths. Equivalent to the
# Make 'MOD_INC_DIRS' when used with PUBLIC and the Make 'EXTRA_INCLUDES' when used with PRIVATE. If called
# with 'RESET', this will unset the global variable. The RESET can be used when a single CMakeLists.txt file
# has multiple targets.
#
# @param VIS [in] Indicate visibility of the headers <PUBLIC|PRIVATE> (or RESET to clear global)
# @param ARGN [in] Relative path to directories containing public header files
#======
macro(bcm_module_header_paths VIS)
if("${VIS}" STREQUAL "RESET")
unset(_MOD_PUBLIC_HDR)
unset(_MOD_PRIVATE_HDR)
else()
_bcm_check_visibility_variable(${VIS} "bcm_module_header_paths")
list(APPEND _MOD_${VIS}_HDR ${ARGN})
list(REMOVE_DUPLICATES _MOD_${VIS}_HDR)
endif()
endmacro(bcm_module_header_paths)
#======
# Add target dependencies. These can be public (included for libraries that have a dependency on this one)
# or private (only available for this library). The macro appends the dependencies to a global list,
# _MOD_PUBLIC_DEPS or _MOD_PRIVATE_DEPS, which are then used in rule creation. This macro can be called
# multiple times in a CMakeLists.txt file with additional dependencies. Equivalent to the Make 'MOD_DEPS'
# when used with PUBLIC. If called with 'RESET', this will unset the global variable. The RESET can be
# used when a single CMakeLists.txt file has multiple targets.
#
# @param VIS [in] Indicate visibility of the headers <PUBLIC|PRIVATE> (or RESET to clear global)
# @param ARGN [in] Modules this one is dependant on.
#======
macro(bcm_module_dependencies VIS)
if("${VIS}" STREQUAL "RESET")
unset(_MOD_PUBLIC_DEPS)
unset(_MOD_PRIVATE_DEPS)
else()
_bcm_check_visibility_variable(${VIS} "bcm_module_dependencies")
list(APPEND _MOD_${VIS}_DEPS ${ARGN})
list(REMOVE_DUPLICATES _MOD_${VIS}_DEPS)
# Add to per-module global list
_bcm_add_to_global_cache_var(${_MOD_NAME}_${VIS}_DEPS "${_MOD_NAME} ${VIS} Dependencies" ${ARGN})
endif()
endmacro(bcm_module_dependencies)
#======
# Add target optional dependencies. These can be public (included for libraries that have a dependency on this one)
# or private (only available for this library). The macro appends the dependencies to a global list,
# _MOD_PUBLIC_OPT_DEPS or _MOD_PRIVATE_OPT_DEPS, which are then used in rule creation. This macro can be called
# multiple times in a CMakeLists.txt file with additional dependencies. If called with 'RESET', this will
# unset the global variable. The RESET can be used when a single CMakeLists.txt file has multiple targets.
#
# @param VIS [in] Indicate visibility of the headers <PUBLIC|PRIVATE> (or RESET to clear global)
# @param ARGN [in] Modules this one is dependant on.
#======
macro(bcm_module_optional_dependencies VIS)
if("${VIS}" STREQUAL "RESET")
unset(_MOD_PUBLIC_OPT_DEPS)
unset(_MOD_PRIVATE_OPT_DEPS)
else()
_bcm_check_visibility_variable(${VIS} "bcm_module_optional_dependencies")
list(APPEND _MOD_${VIS}_OPT_DEPS ${ARGN})
list(REMOVE_DUPLICATES _MOD_${VIS}_OPT_DEPS)
endif()
endmacro(bcm_module_optional_dependencies)
#======
# Add target kernel dependencies. These can be public (included for libraries that have a dependency on this one)
# or private (only available for this library). The macro appends the dependencies to a global list,
# _MOD_PUBLIC_DEPS or _MOD_PRIVATE_DEPS, which are then used in rule creation. This macro can be called
# multiple times in a CMakeLists.txt file with additional dependencies. Equivalent to the Make 'MOD_DEPS'
# when used with PUBLIC.
#
# The kernel specific part of these is the appending of '_kernel' to the dependency names as this tells the
# kernel module build to pull in the source or Module.symvers for the linux libs and modules, respectively.
# This is always added as a private dependency.
#
# If the visibility is PUBLIC, then we also add the targets to the normal dependencies so they are available to
# those with a dependency on this module. Note that these would be header-only depenencies.
#
# @param VIS [in] Indicate visibility of the headers <PUBLIC|PRIVATE>
# @param ARGN [in] Modules this one is dependant on.
#======
macro(bcm_module_kernel_dependencies VIS)
_bcm_check_visibility_variable(${VIS} "bcm_module_kernel_dependencies")
set(_MY_DEPS_IN ${ARGN})
unset(_MY_PRIVATE_DEPS)
unset(_MY_PUBLIC_DEPS)
# Append the '_kernel' to all the dependencies given to indicate they are part of a module build
string(REGEX REPLACE "([^;]+)" "\\1_${_KERNEL_EXT}" _MY_PRIVATE_DEPS "${_MY_DEPS_IN}")
# If VIS == PUBLIC, we want the header-only versions (name without '_kernel') on the dependency list
if("${VIS}" STREQUAL "PUBLIC")
list(APPEND _MY_PUBLIC_DEPS ${_MY_DEPS_IN})
endif()
# Now add to the globals
list(APPEND _MOD_PRIVATE_DEPS ${_MY_PRIVATE_DEPS})
list(REMOVE_DUPLICATES _MOD_PRIVATE_DEPS)
if(_MY_PUBLIC_DEPS)
list(APPEND _MOD_PUBLIC_DEPS ${_MY_PUBLIC_DEPS})
list(REMOVE_DUPLICATES _MOD_PUBLIC_DEPS)
endif()
# Add to per-module global list
_bcm_add_to_global_cache_var(${_MOD_NAME}_PRIVATE_DEPS "${_MOD_NAME} PRIVATE Dependencies" ${_MY_PRIVATE_DEPS})
_bcm_add_to_global_cache_var(${_MOD_NAME}_PUBLIC_DEPS "${_MOD_NAME} PUBLIC Dependencies" ${_MY_PUBLIC_DEPS})
endmacro(bcm_module_kernel_dependencies)
#======
# Add target system libraries: The system libraries are always considered public and are stored in
# _MOD_SYSTEM_LIBS. A system library is any library that you don't want to be part of a -Wl,--start-group/
# --end-group. The system libraries will come at the end of the link command.
#
# @param ARGN [in] system libraries (no '-l'). Could also be 'RESET'
#======
macro(bcm_module_system_libraries)
if(${ARGC} GREATER 0)
if("${ARGV0}" STREQUAL "RESET")
unset(_MOD_SYSTEM_LIBS)
elseif("${ARGV0}" STREQUAL "PUBLIC" OR "${ARGV0}" STREQUAL "PRIVATE")
bcm_message(FATAL_ERROR "System library setting invalid parameter '${ARGV0}'")
else()
list(APPEND _MOD_SYSTEM_LIBS ${ARGN})
list(REMOVE_DUPLICATES _MOD_SYSTEM_LIBS)
endif()
endif()
endmacro(bcm_module_system_libraries)
#======
# Set the compile options to use beyond the default. This does not include the -D definitions as they are
# handled by bcm_module_definitions() macro. These can be public (included for libraries that have a
# dependency on this one) or private (only available for this library). The macro appends the cflags to
# a global list, _MOD_PUBLIC_CFLAGS or _MOD_PRIVATE_CFLAGS, which are then used in rule creation. This
# macro can be called multiple times in a CMakeLists.txt file with additional compile flags. Equivalent
# to the Make 'EXTRA_CFLAGS' when used with PRIVATE. If called with 'RESET', this will unset the global
# variable. The RESET can be used when a single CMakeLists.txt file has multiple targets.
#
# @param VIS [in] Indicate visibility of the headers <PUBLIC|PRIVATE> (or RESET to clear global)
# @param ARGN [in] Compile flags for this module.
#======
macro(bcm_module_cflags VIS)
if("${VIS}" STREQUAL "RESET")
unset(_MOD_PUBLIC_CFLAGS)
unset(_MOD_PRIVATE_CFLAGS)
else()
_bcm_check_visibility_variable(${VIS} "bcm_module_cflags")
list(APPEND _MOD_${VIS}_CFLAGS ${ARGN})
list(REMOVE_DUPLICATES _MOD_${VIS}_CFLAGS)
endif()
endmacro(bcm_module_cflags)
#======
# Set the -D options for the module and must include the '-D'. These can be public (included for libraries
# that have a dependency on this one) or private (only available for this library). The macro appends the
# definitions to a global list, _MOD_PUBLIC_DEFS or _MOD_PRIVATE_DEFS, which are then used in rule creation.
# This macro can be called multiple times in a CMakeLists.txt file with additional definitions. Equivalent
# to the Make 'MOD_DEFS' when used with PUBLIC. If called with 'RESET', this will unset the global variable.
# The RESET can be used when a single CMakeLists.txt file has multiple targets.
#
# @param VIS [in] Indicate visibility of the headers <PUBLIC|PRIVATE> (or RESET to clear global)
# @param ARGN [in] Compile flags for this module.
#======
macro(bcm_module_definitions VIS)
if("${VIS}" STREQUAL "RESET")
unset(_MOD_PUBLIC_DEFS)
unset(_MOD_PRIVATE_DEFS)
else()
_bcm_check_visibility_variable(${VIS} "bcm_module_definitions")
list(APPEND _MOD_${VIS}_DEFS ${ARGN})
list(REMOVE_DUPLICATES _MOD_${VIS}_DEFS)
# Add to per-module global list
_bcm_add_to_global_cache_var(${_MOD_NAME}_${VIS}_DEFS "${_MOD_NAME} ${VIS} Definitions" ${ARGN})
# Add to the global list
_bcm_add_to_global_cache_var(BCM_GLOBAL_DEFINITIONS "Broadcom Global Definitions" ${ARGN})
endif()
endmacro(bcm_module_definitions)
#======
# Add the code generation output for the module. The macro sets the global, _MOD_CODEGEN_OUTPUT.
# This is called from cmake/modules/codegen_macros.cmake to set a target for the generated .c/.h
# files.
#
# @param ARGN [in] Compile flags for this module.
#======
macro(bcm_module_codegen_output)
list(APPEND _MOD_CODEGEN_OUTPUT ${ARGN})
list(REMOVE_DUPLICATES _MOD_CODEGEN_OUTPUT)
endmacro(bcm_module_codegen_output)
#====
# Create a wrap function for the linker using the GCC "--wrap" functionality.
# The modifications to the linker flags will apply to any executable that depends on the current module.
#
# @param ARGV [in] list of functions to wrap
#====
macro(bcm_module_function_overrides)
list(APPEND _MOD_WRAPPED_FUNCS ${ARGN})
endmacro(bcm_module_function_overrides)
#====
# Batch compilation support
#====
bcm_make_debug_option(BATCH_COMPILE BOOL "Batch compilation (multiple files in a single compiler invocation)" n)
#======
# Clear batch compilation artifacts if any
#======
macro(batch_compile_clear)
file(REMOVE ${CMAKE_CURRENT_BINARY_DIR}/.${_MOD_NAME}.compile.files)
endmacro(batch_compile_clear)
#======
# Set batch compilation properties
#======
macro(batch_compile_prepare)
if(BATCH_COMPILE AND NOT ${_MOD_NAME}_disable_batch_compile)
# Remove stale batch compilation info if any
batch_compile_clear()
# Compile in batch(es) just before link
set_property(TARGET ${_MOD_NAME} PROPERTY C_COMPILER_LAUNCHER
${SOURCE_TOP}/cmake/scripts/batch_compile_cache.sh ${_MOD_NAME} ${CMAKE_C_COMPILER_LAUNCHER})
set_property(TARGET ${_MOD_NAME} PROPERTY CXX_COMPILER_LAUNCHER
${SOURCE_TOP}/cmake/scripts/batch_compile_cache.sh ${_MOD_NAME} ${CMAKE_CXX_COMPILER_LAUNCHER})
set_property(TARGET ${_MOD_NAME} PROPERTY RULE_LAUNCH_LINK
"${SOURCE_TOP}/cmake/scripts/batch_compile_execute.sh ${_MOD_NAME}")
endif()
endmacro(batch_compile_prepare)
#======
# Create the library target from the globals set. _MOD_NAME is required. For Linux module builds we want
# to include the headers and dependencies from a regular library, but not the CFLAGS, definitions or build
# rules. To handle this we create a second, parallel, interface library target for the Linux modules and
# libraries to use. Since we also call in to this macro from the Linux module and library builds, an optional
# parameter is provided that skips thee clearing of the global variables. It is up to the caller to do the clear
# when this parameter is used.
#
# @param ARGN [in] Optional parameters as:
# - NO_RESET with any other options (Don't clear the global variables)
# - INTERNAL used to control logging
# - EXPORT (indicates whether to export the library or not)
#======
macro(bcm_create_lib_target)
_bcm_check_mandatory_variables(_MOD_NAME)
_bcm_param_exists(_NO_RESET NO_RESET ${ARGN})
_bcm_param_exists(_EXPORT EXPORT ${ARGN})
_bcm_param_exists(_INTERNAL INTERNAL ${ARGN})
unset(_INSTALL_DIR)
# Store information that module is a library in the cache for other modules to see
set(${_MOD_NAME}_TYPE lib CACHE STRING "${_MOD_NAME} type" FORCE)
if(NOT DEFINED _MOD_SRCS)
# An interface library is one that has no source files, only headers. We use this of no source
# files are given.
add_library(${_MOD_NAME} INTERFACE)
else()
# If we have source files, this is treated as a static library.
add_library(${_MOD_NAME} STATIC ${_MOD_SRCS})
# Add library to global list
list(APPEND BCM_ALL_LIB_MODULES ${_MOD_NAME})
set(BCM_ALL_LIB_MODULES ${BCM_ALL_LIB_MODULES} CACHE STRING "All Library Modules" FORCE)
# Prepare for batch compilation if necessary
batch_compile_prepare()
# Set the install target if the macro was passed one.
_bcm_install_target(_OUT_STR ${_MOD_NAME} ${_EXPORT} _INSTALL_DIR FALSE)
endif()
# Add in the transitive properties to the library target
_bcm_module_add_target_specifics()
# If there is a corresponding codegen target, add a dependency on it
# (this is useful for interface libraries, which normally build nothing).
if(DEFINED _MOD_CODEGEN_OUTPUT)
add_custom_target(${_MOD_NAME}_codegen DEPENDS ${_MOD_CODEGEN_OUTPUT})
add_dependencies(${_MOD_NAME} ${_MOD_NAME}_codegen)
endif()
# Add an interface libary with the name, ${_MOD_NAME}_${_HEADER_ONLY_EXT}, that can be used as a dependency
# in place of hardcoded header paths. We want to include the definitions with this as well.
_bcm_create_interface_lib(${_MOD_NAME}_${_HEADER_ONLY_EXT} ${_HEADER_ONLY_EXT})
# Clear the variables only if not told to keep them
if(NOT ${_INTERNAL})
if(NOT ${_NO_RESET})
_bcm_module_globals_clear()
endif()
bcm_message(STATUS "Added 'lib' rules for '${_MOD_NAME}'")
endif()
endmacro(bcm_create_lib_target)
#======
# Create the shared library target from the globals set. _MOD_NAME are required. The
# shared library can be used on linux systems and its primary use case is BAL/SDN Agent.
#
# @param ARGN [in] Optional parameters as:
# - NO_RESET with any other options (Don't clear the global variables)
# - EXPORT (indicates whether to export the library or not)
# - STRIP (indicates that we should strip the symbols)
# - RELEASE (indicates that the resulting binary goes in host_driver_images
# - <install dir> or EXPORT (indicates whether to export or put in install dir)
#======
macro(bcm_create_shared_lib_target)
_bcm_check_mandatory_variables(_MOD_NAME)
_bcm_param_exists(_NO_RESET NO_RESET ${ARGN})
_bcm_param_exists(_EXPORT EXPORT ${ARGN})
_bcm_param_exists(_STRIP STRIP ${ARGN})
_bcm_param_exists(_RELEASE RELEASE ${ARGN})
_bcm_find_install_dir(_INSTALL_DIR ${ARGN})
# Store information that module is a shared library in the cache for other modules to see
set(${_MOD_NAME}_TYPE shared_lib CACHE STRING "${_MOD_NAME} type" FORCE)
# Add the library as shared or interface depending on the sources
if(NOT DEFINED _MOD_SRCS)
add_library(${_MOD_NAME} INTERFACE)
else()
bcm_add_system_libraries_to_link(${_MOD_NAME}_SYSTEM_LIBRARIES SHARED_LIBRARY)
add_library(${_MOD_NAME} SHARED ${_MOD_SRCS})
# Prepare for batch compilation if necessary
batch_compile_prepare()
endif()
# Determine if we should be stripping symbols
if(${_STRIP})
_bcm_strip_symbols(${_MOD_NAME})
endif()
# Set the install target if the macro was passed one.
_bcm_install_target(_OUT_STR ${_MOD_NAME} ${_EXPORT} _INSTALL_DIR ${_STRIP})
# Add an interface libary with the name, ${_MOD_NAME}_${_HEADER_ONLY_EXT}, that can be used as a dependency
# in place of hardcoded header paths. We want to include the definitions with this as well.
_bcm_create_interface_lib(${_MOD_NAME}_${_HEADER_ONLY_EXT} ${_HEADER_ONLY_EXT})
# Add to the global list
list(APPEND BCM_ALL_SHARED_LIB_MODULES ${_MOD_NAME})
set(BCM_ALL_SHARED_LIB_MODULES ${BCM_ALL_SHARED_LIB_MODULES} CACHE STRING "All Shared library Modules" FORCE)
# Add header files and library dependencies, then clear the globals
_bcm_module_add_target_specifics()
if(NOT ${_NO_RESET})
_bcm_module_globals_clear()
endif()
# If marked for RELEASE, install the binary if install macro exists
if(_RELEASE)
_bcm_release_binary(lib${_MOD_NAME}.so)
endif()
bcm_message(STATUS "Added 'shared_lib' rules for '${_MOD_NAME}'${_OUT_STR}")
endmacro(bcm_create_shared_lib_target)
#======
# Create the application target from the globals set. _MOD_NAME and _MOD_SRCS are required.
#
# @param ARGN [in] Optional parameters as:
# - NO_RESET with any other options (Don't clear the global variables)
# - EXPORT (indicates whether to export the library or not)
# - STRIP (indicates that we should strip the symbols)
# - RELEASE (indicates that the resulting binary goes in host_driver_images
# - <install dir> or EXPORT (indicates whether to export or put in install dir)
#======
macro(bcm_create_app_target)
_bcm_param_exists(_NO_RESET NO_RESET ${ARGN})
_bcm_param_exists(_EXPORT EXPORT ${ARGN})
_bcm_param_exists(_STRIP STRIP ${ARGN})
_bcm_param_exists(_RELEASE RELEASE ${ARGN})
_bcm_find_install_dir(_INSTALL_DIR ${ARGN})
# Store information that module is an application in the cache for other modules to see
set(${_MOD_NAME}_TYPE app CACHE STRING "${_MOD_NAME} type" FORCE)
_bcm_check_mandatory_variables(_MOD_NAME _MOD_SRCS)
bcm_add_system_libraries_to_link(${_MOD_NAME}_SYSTEM_LIBRARIES EXECUTABLE)
add_executable(${_MOD_NAME} ${_MOD_SRCS})
# Prepare for batch compilation if necessary
batch_compile_prepare()
# Determine if we should be stripping symbols
if(${_STRIP})
_bcm_strip_symbols(${_MOD_NAME})
endif()
# Set the install target if the macro was passed one.
_bcm_install_target(_OUT_STR ${_MOD_NAME} ${_EXPORT} _INSTALL_DIR ${_STRIP})
# If this is the ARM toolchain, we want to set the target properties for static linking
if(DEFINED ARM_TOOLCHAIN_PATH)
set_target_properties(${_MOD_NAME} PROPERTIES
LINK_SEARCH_START_STATIC 1
LINK_SEARCH_END_STATIC 1)
endif()
# Add an interface libary with the name, ${_MOD_NAME}_${_HEADER_ONLY_EXT}, that can be used as a dependency
# in place of hardcoded header paths. We want to include the definitions with this as well.
_bcm_create_interface_lib(${_MOD_NAME}_${_HEADER_ONLY_EXT} ${_HEADER_ONLY_EXT})
# Add to the global list
list(APPEND BCM_ALL_APP_MODULES ${_MOD_NAME})
set(BCM_ALL_APP_MODULES ${BCM_ALL_APP_MODULES} CACHE STRING "All Aplication Modules" FORCE)
# Add header files and library dependencies, then clear the globals
_bcm_module_add_target_specifics()
if(NOT ${_NO_RESET})
_bcm_module_globals_clear()
endif()
# If marked for RELEASE, install the binary if install macro exists
if(_RELEASE)
_bcm_release_binary(${_MOD_NAME})
endif()
bcm_message(STATUS "Added 'app' rules for '${_MOD_NAME}'${_OUT_STR}")
endmacro(bcm_create_app_target)
#======
# PRIVATE: Bring in the native build server compiler for the native_lib and native_app targets. We include
# the simulation definitions as they have the native compiler settings. The variables are in the context
# of the Aspen module using the native compiler, so it will not overwrite the cross-compiler for other
# Aspen modules.
#======
macro(_bcm_include_native)
# For this target type, we want to bring in the native compiler if not already using it. Simulation would
# already be using it, so need to bring it in for that case. Including 'sim' will set simulation build
# to true, so make sure we restore it.
if(NOT "${SIMULATION_BUILD}")
unset(BCM_CFLAGS)
unset(BCM_ASFLAGS)
unset(BCM_LFLAGS)
unset(ARM_TOOLCHAIN_PATH)
set(_SAVED_SIMULATION_BUILD ${SIMULATION_BUILD})
include(native)
bcm_stringify_flags(CMAKE_C_FLAGS ${BCM_CFLAGS})
bcm_stringify_flags(CMAKE_CXX_FLAGS ${BCM_CFLAGS})
bcm_stringify_flags(CMAKE_ASM_FLAGS ${BCM_ASFLAGS})
bcm_stringify_flags(CMAKE_EXE_LINKER_FLAGS ${BCM_LFLAGS})
bcm_stringify_flags(SIMULATION_BUILD ${_SAVED_SIMULATION_BUILD})
endif()
endmacro(_bcm_include_native)
#======
# Create the library target with the native compiler. This is the same as the bcm_create_lib_target(),
# except it builds with the simulation compiler. This is used to build tools (e.g. code generation) that must
# run on the build server.
#
# @param ARGN [in] Optional parameters as:
# - NO_RESET with any other options (Don't clear the global variables)
# - EXPORT (indicates whether to export or put in install dir)
#======
macro(bcm_create_native_lib_target)
_bcm_check_mandatory_variables(_MOD_NAME _MOD_SRCS)
_bcm_include_native()
bcm_create_lib_target(${ARGN})
endmacro(bcm_create_native_lib_target)
#======
# Create the application target with the native compiler. This is the same as the bcm_create_app_target(),
# except it builds with the simulation compiler. This is used to build tools (e.g. code generation) that must
# run on the build server. This macro will also add the resulting executable to the 'EXE' property on the target.
#
# @param ARGN [in] Optional parameters as:
# - NO_RESET with any other options (Don't clear the global variables)
# - <install dir> or EXPORT (indicates whether to export or put in install dir)
#======
macro(bcm_create_native_app_target)
_bcm_check_mandatory_variables(_MOD_NAME _MOD_SRCS)
_bcm_include_native()
set(DISABLE_PLATFORM_APP_TARGET ON)
bcm_create_app_target(${ARGN})
unset(DISABLE_PLATFORM_APP_TARGET)
# Make sure that cmake "forgets" that it might be cross-compiling
if(NOT "${SIMULATION_BUILD}")
set_target_properties(${_MOD_NAME} PROPERTIES RUNTIME_OUTPUT_NAME ${_MOD_NAME} SUFFIX "")
endif()
# Associate the resulting executable with the target
set_target_properties(${_MOD_NAME} PROPERTIES EXE ${CMAKE_CURRENT_BINARY_DIR}/${_MOD_NAME})
endmacro(bcm_create_native_app_target)
#======
# PRIVATE: Add the rule for copying the source files used in Linux libraries and modules. The files are copied
# to the build tree and placed in a directory named with the _KERNEL_MOD_NAME_EXT value (k3rn3l). Using
# this subdirectory allows us to have the same source file, different objects and all objects in the build tree.
# A copy is used instead of a symlink because we want the command to only run on updates. This allows us to
# use the IMPLICIT_DEPENDS to get the header file dependencies as well. When this was done with symlink it caused
# a rebuild of the kernel modules everytime.
#
# @param TARGET [out] Target that will link the source files
# @param SOURCE_LIST [out] List of source files with absolute path
# @param ARGN [in] 0 or more source files. If 0, nothing is done.
#======
macro(_bcm_kernel_copy_src TARGET SOURCE_LIST)
unset(${SOURCE_LIST})
foreach(_MOD_SRC ${ARGN})
get_filename_component(_MOD_SRC_NAME ${_MOD_SRC} NAME)
get_filename_component(_MOD_SRC_PATH ${_MOD_SRC} ABSOLUTE)
# The linux library source files are copied to the k3rn3l subdirectory of this Aspen module's
# binary tree.
set(_MOD_DST_DIR ${CMAKE_CURRENT_BINARY_DIR}/files)
set(_MOD_DST_PATH ${_MOD_DST_DIR}/${_MOD_SRC_NAME})
# Create the rule to copy the source file. We use the IMPLICIT_DEPENDS on the source to get all the
# header file dependencies.
add_custom_command(OUTPUT ${_MOD_DST_PATH}
COMMAND mkdir -p ${_MOD_DST_DIR}
COMMAND cp -f ${_MOD_SRC_PATH} ${_MOD_DST_PATH}
IMPLICIT_DEPENDS C ${_MOD_SRC_PATH}
DEPENDS ${_MOD_SRC_PATH} ${_MOD_PUBLIC_DEPS} ${_MOD_PRIVATE_DEPS})
# Add the source file to the source list so it can be used in the dependencies in the custom target
list(APPEND ${SOURCE_LIST} ${_MOD_DST_PATH})
endforeach(_MOD_SRC)
# Create a target that will run all the copies. The target is returned to the caller so the
# caller can use it in a dependency list.
set(${TARGET} _copy_${_MOD_NAME}_srcs)
add_custom_target(${${TARGET}} DEPENDS ${${SOURCE_LIST}})
endmacro(_bcm_kernel_copy_src)
#======
# Replace 'os' in the dependency lists with "os_linux". and define the non-header-only dependencies
# as 'kernel_target' type.
#
# @param DEPS [in] Dependencies to redo
#======
macro(_bcm_set_kernel_dependencies DEPS)
# Replace the OS dependency with the the os_linux
if("os" IN_LIST ${DEPS})
list(REMOVE_ITEM ${DEPS} os)
list(APPEND ${DEPS} os_linux)
endif()
if("os_${_HEADER_ONLY_EXT}" IN_LIST ${DEPS})
list(REMOVE_ITEM ${DEPS} os_${_HEADER_ONLY_EXT})
list(APPEND ${DEPS} os_linux_${_HEADER_ONLY_EXT})
endif()
# Walk the dependencies and replace entries appropriately. If it has the '_kernel' or '_HDRONLY' extension,
# we use it as-is. Any others we append '_HDRONLY' so no source or libraries are included (i.e. header-only
# library).
unset(_MY_DEPS)
foreach(_MY_DEP ${${DEPS}})
if(_MY_DEP MATCHES "_${_KERNEL_EXT}" OR _MY_DEP MATCHES "_${_HEADER_ONLY_EXT}")
list(APPEND _MY_DEPS ${_MY_DEP})
else()
list(APPEND _MY_DEPS ${_MY_DEP}_${_HEADER_ONLY_EXT})
endif()
endforeach(_MY_DEP)
set(${DEPS} ${_MY_DEPS})
endmacro(_bcm_set_kernel_dependencies)
#======
# Get the compile and link scripts for the kernel modules. We only need to do this once, not everytime through
# the macro below.
#======
bcm_find_cmake_script(_KMODULE_COMPILE_SCRIPT kmodule_source_cache.sh)
bcm_find_cmake_script(_KMODULE_LINK_SCRIPT kmodule_link.sh)
bcm_find_cmake_script(_KMODULE_AR_SCRIPT kmodule_archive.sh)
#======
# PRIVATE: Common processing at the beginning of both the linux library and linux module. Here we validate
# that we can use the macro and create the rules for copying the source files. We also call the
# 'bcm_create_lib_target() to create an app and kernel version of the library.
#
# @param CACHE_FILE [out] Base name of cache file used by scripts
# @param TYPE [in] "LIB" or "MODULE"
# @param TARGET [in] Name of the kernel target
#======
macro(_bcm_create_linux_common CACHE_FILE TYPE TARGET)
# First validate that this is not the embedded subsystem and that the OS_KERNEL is linux, otherwise
# the bcm_create_linux_<type>_target() macros can not be used.
if("${SUBSYSTEM}" STREQUAL "embedded")
bcm_message(FATAL_ERROR "Embedded subsystem can not create linux libraries/modules")
elseif(NOT "${OS_KERNEL}" STREQUAL "linux")
bcm_message(FATAL_ERROR "Can only build linux libraries/modules if kernel is linux")
endif()
# Next validate we got the inputs we are expecting.
_bcm_check_mandatory_variables(_MOD_NAME _MOD_SRCS)
# Rule to create the module source. The target here is a dependency of the _MOD_NAME target
_bcm_kernel_copy_src(_KERNEL_COPY_TARGET _KERNEL_SRCS ${_MOD_SRCS})
# For kernel builds we disable the extra warnings since we don't use them
set(DISABLE_EXTRA_WARNINGS TRUE)
# Add the kernel libraries we use. For Linux lib we use a static lib and for Linux module we use
# a shared lib.
unset(_LIB_TYPE)
if(${TYPE} STREQUAL "MODULE")
set(_LIB_TYPE SHARED)
endif()
add_library(${TARGET} ${_LIB_TYPE} ${_KERNEL_SRCS})
add_dependencies(${TARGET} ${_KERNEL_COPY_TARGET})
# Add the original module name as an interface lib for user space dependencies. Also create the header-only
# target for those that reference it.
add_library(${_MOD_NAME} INTERFACE)
_bcm_create_interface_lib(${_MOD_NAME}_${_HEADER_ONLY_EXT} ${_HEADER_ONLY_EXT})
# Add the definitions, header paths, dependencies to the targets
set(_MY_MOD_SRCS ${_MOD_SRCS})
unset(_MOD_SRCS)
_bcm_module_add_target_specifics()
set(_MOD_SRCS ${_MY_MOD_SRCS})
_bcm_set_kernel_dependencies(_MOD_PUBLIC_DEPS)
_bcm_set_kernel_dependencies(_MOD_PRIVATE_DEPS)
_bcm_module_add_target_specifics(${TARGET})
_bcm_module_globals_clear()
# Make sure the files we use for collection of object files, header paths and definitions are cleared before we
# start
set(${CACHE_FILE} .compile)
file(REMOVE ${CMAKE_CURRENT_BINARY_DIR}/${${CACHE_FILE}}.objs)
file(REMOVE ${CMAKE_CURRENT_BINARY_DIR}/${${CACHE_FILE}}.incl)
file(REMOVE ${CMAKE_CURRENT_BINARY_DIR}/${${CACHE_FILE}}.defs)
# Set the compile rule which is common for both linux lib and module
set_property(TARGET ${TARGET} PROPERTY C_COMPILER_LAUNCHER ${_KMODULE_COMPILE_SCRIPT} ${${CACHE_FILE}})
endmacro(_bcm_create_linux_common)
#======
# Create the Linux library target from the globals set. _MOD_NAME is required.
# The linux library is only a collection of source files that have not been compiled yet. A linux module
# that has a dependency on the linux library will compile the source at that time. For this macro, we create
# a user level library and a kernel level library by using 'bcm_create_lib_target()'. We then add the
# CFLAGS and definitions to the kernel library + add the object files as a target property. Both the user
# space and kernel libraries are created as INTERFACE libraries since we don't want to build anything here.
# We don't check for the host subsystem here since this macro should never be called for embedded code.
#======
macro(bcm_create_linux_lib_target)
set(_KERNEL_TARGET ${_MOD_NAME}_${_KERNEL_EXT})
_bcm_create_linux_common(_KMODULE_SOURCE_CACHE_FILE LIB ${_KERNEL_TARGET})
# Set the archive script to use
set_property(TARGET ${_KERNEL_TARGET} PROPERTY RULE_LAUNCH_LINK ${_KMODULE_AR_SCRIPT})
# Make sure we add any extra files to the clean rule for cleaning up kernel libraries
set(_FILES_TO_CLEAN files .compile.incl .compile.objs .compile.defs)
set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES "${_FILES_TO_CLEAN}")
bcm_message(STATUS "Added 'linux_lib' rules for '${_MOD_NAME}'")
endmacro(bcm_create_linux_lib_target)
#======
# Create the Linux module target from the globals set. _MOD_NAME and _MOD_SRCS are required.
# The macro is only valid for the host subsystem and if the OS_KERNEL is linux. We use the validate macro
# to check this.
#
# @param ARGN [in] Optional parameters as:
# - RELEASE (indicates that the resulting binary goes in host_driver_images
# - <install dir> or EXPORT (indicates whether to export or put in install dir)
#======
macro(bcm_create_linux_module_target)
_bcm_param_exists(_KERNEL_MOD_EXPORT EXPORT ${ARGN})
_bcm_param_exists(_RELEASE RELEASE ${ARGN})
_bcm_find_install_dir(_KERNEL_MOD_INSTALL_DIR ${ARGN})
# Run the common linux target processing
set(_KERNEL_TARGET ${_MOD_NAME}_${_KERNEL_EXT})
_bcm_create_linux_common(_KMODULE_SOURCE_CACHE_FILE MODULE ${_KERNEL_TARGET})
# Create the link command we will use. The link command needs to be a string, so we first create a list,
# then convert to string. Note that we only include the CROSS_COMPILE if it is set.
if(CROSS_COMPILE)
set(_KMODULE_CROSS_COMPILE "-c ${CROSS_COMPILE}")
endif(CROSS_COMPILE)
if(GCC_VERSION)
set(_KMODULE_GCC_VERSION "-h ${GCC_VERSION}")
endif(GCC_VERSION)
bcm_stringify_flags(_KMODULE_LINK_CMD
${_KMODULE_LINK_SCRIPT} -l ${KERNELDIR} -a ${KERNEL_ARCH} ${_KMODULE_CROSS_COMPILE}
-m ${_MOD_NAME} -b ${CMAKE_CURRENT_BINARY_DIR} -f ${_KMODULE_SOURCE_CACHE_FILE}
-v ${CMAKE_VERBOSE_MAKEFILE} ${_KMODULE_GCC_VERSION})
set_property(TARGET ${_KERNEL_TARGET} PROPERTY RULE_LAUNCH_LINK ${_KMODULE_LINK_CMD})
# Make sure we add any extra files to the clean rule for cleaning up kernel modules
set(_FILES_TO_CLEAN ${_MOD_NAME}.mod.c ${_MOD_NAME}.mod.o ${_MOD_NAME}.o built-in.o ${_MOD_NAME}.ko
.${_MOD_NAME}.mod.o.cmd .${_MOD_NAME}.ko.cmd .${_MOD_NAME}.o.cmd .built-in.o.cmd files
.compile.incl .compile.objs .compile.defs modules.order Module.symvers .tmp_versions)
set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES "${_FILES_TO_CLEAN}")
# Add the install for the kernel module
_bcm_install_target(_OUT_STR ${CMAKE_CURRENT_BINARY_DIR}/${_MOD_NAME}.ko ${_KERNEL_MOD_EXPORT}
_KERNEL_MOD_INSTALL_DIR FALSE)
# If marked for RELEASE, install the binary if install macro exists
if(_RELEASE)
_bcm_release_binary(${_MOD_NAME}.ko)
endif()
bcm_message(STATUS "Added 'linux module' rules for '${_MOD_NAME}'${_OUT_STR}")
endmacro(bcm_create_linux_module_target)
# Our build process requires that the cmake scan is initially run twice to generate a proper cache file. This allows
# us to put our build options anywhere in any CMake source file without having to pre-declare them. After the initial
# scan, CMake will automatically update the cache whenever a cmake source file changes.
#
# We force CMake to re-generate the Makefile the first time it is run by touching the cache file after it is initially
# generated. Unfortunately CMake doesn't normally let us execute commands after the cache is written, so we set up a
# listener on an internal variable that is accessed after the cache file is written, with a custom callback.
if(NOT EXISTS "${BUILD_TOP}/CMakeCache.txt")
function(_BCM_POST_CACHE_WRITE_HOOK)
# This will happen multiple times, but that's OK as long as the last one is after the cache is written.
execute_process(COMMAND ${CMAKE_COMMAND} -E touch "${BUILD_TOP}/CMakeCache.txt")
endfunction()
variable_watch(CMAKE_SKIP_RPATH _BCM_POST_CACHE_WRITE_HOOK)
endif()
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
/*******************************************************************
* bcmcli.c
*
* CLI engine
*
*******************************************************************/
#include <bcmos_system.h>
#define BCMCLI_INTERNAL
#include <bcmcli.h>
#include <bcmos_types.h>
#include <bcmolt_string.h>
#define BCMCLI_INBUF_LEN 4096
#define BCMCLI_MAX_QUAL_NAME_LENGTH 256
#define BCMCLI_UP_STR ".."
#define BCMCLI_ROOT_STR "/"
#define BCMCLI_COMMENT_CHAR '#'
#define BCMCLI_HELP_CHAR '?'
#define BCMCLI_ARRAY_DELIM_CHAR ','
#define BCMCLI_ROOT_HELP "root directory"
#define BCMCLI_MAX_PARM_VAL_LEN 256
#define BCMCLI_ENUM_MASK_DEL_CHAR '+'
#define BCMCLI_HELP_BUFFER_SIZE 16384
#define BCMCLI_MAX_ARRAY_LEN 128
#define BCMCLI_EQUAL_CHAR '='
#define BCMCLI_STRUCT_START_CHAR '{'
#define BCMCLI_STRUCT_END_CHAR '}'
#define BCMCLI_STRUCT_START_STR "{"
#define BCMCLI_STRUCT_END_STR "}"
#define BCMCLI_ARRAY_START_CHAR '['
#define BCMCLI_ARRAY_END_CHAR ']'
#define BCMCLI_ARRAY_START_STR "["
#define BCMCLI_ARRAY_END_STR "]"
#define BCMCLI_NO_VALUE_STR "-"
typedef enum { BCMCLI_ENTRY_DIR, BCMCLI_ENTRY_CMD } bcmcli_entry_selector;
/* External table - boolean values */
bcmcli_enum_val bcmcli_enum_bool_table[] = {
{ .name="true", .val = 1 },
{ .name="yes", .val = 1 },
{ .name="on", .val = 1 },
{ .name="false", .val = 0 },
{ .name="no", .val = 0 },
{ .name="off", .val = 0 },
BCMCLI_ENUM_LAST
};
/* Monitor token structure */
struct bcmcli_entry
{
struct bcmcli_entry *next;
char *name; /* Command/directory name */
char *help; /* Command/directory help */
bcmcli_entry_selector sel; /* Entry selector */
char *alias; /* Alias */
uint16_t alias_len; /* Alias length */
struct bcmcli_entry *parent; /* Parent directory */
bcmcli_access_right access_right;
union {
struct
{
struct bcmcli_entry *first; /* First entry in directory */
bcmcli_dir_extra_parm extras; /* Optional extras */
} dir;
struct
{
bcmcli_cmd_cb cmd_cb; /* Command callback */
bcmcli_cmd_parm *parms; /* Command parameters */
bcmcli_cmd_extra_parm extras; /* Optional extras */
uint16_t num_parms;
} cmd;
} u;
};
/* Token types */
typedef enum
{
BCMCLI_TOKEN_EMPTY = 0,
BCMCLI_TOKEN_UP = (1 << 0),
BCMCLI_TOKEN_ROOT = (1 << 1),
BCMCLI_TOKEN_BREAK = (1 << 2),
BCMCLI_TOKEN_HELP = (1 << 3),
BCMCLI_TOKEN_NAME = (1 << 4),
BCMCLI_TOKEN_VALUE = (1 << 5),
#define BCMCLI_TOKEN_TYPE_MASK 0xff
/* Flags */
BCMCLI_TOKEN_HAS_EQUAL_SIGN = (1 << 8),
BCMCLI_TOKEN_STRUCT_VALUE = (1 << 9),
BCMCLI_TOKEN_UNTERMINATED_STRUCT_VALUE = (1 << 10),
BCMCLI_TOKEN_UNTERMINATED_ARRAY_INDEX = (1 << 11),
} bcmcli_token_type;
/* Name, value pairs */
typedef struct
{
bcmcli_token_type type;
const char *name;
const char *value;
const char *index;
} bcmcli_name_value;
/* Command parameters array.
* These arrays can be stacked in case of hierarchical parameter structures (structs)
*/
typedef struct bcmcli_parm_array bcmcli_parm_array;
struct bcmcli_parm_array
{
bcmcli_cmd_parm *cmd_parms;
bcmcli_name_value *name_value_pairs;
uint32_t num_parms;
uint32_t num_pairs;
uint32_t num_parsed;
const char *in_parm;
bcmcli_parm_value *in_value;
STAILQ_ENTRY(bcmcli_parm_array) next;
};
/* CLI session data */
typedef struct
{
bcmcli_entry *curdir;
bcmcli_entry *curcmd;
bcmos_bool is_execution;
bcmos_bool suppress_err_print;
bcmcli_token_type cur_token_type;
STAILQ_HEAD(cmd_parms_stack, bcmcli_parm_array) cmd_parms_stack;
bcmcli_session *session;
const char *p_inbuf;
int stop_monitor;
char inbuf[BCMCLI_INBUF_LEN];
char help_buf[BCMCLI_HELP_BUFFER_SIZE];
bcmolt_string help_string;
} bcmcli_session_extras;
static bcmcli_entry *_bcmcli_root_dir;
static bcmcli_session_extras *_bcmcli_root_session;
static bcmcli_log_mode _bcmcli_log_mode;
static bcmcli_session *_bcmcli_log_session;
#define BCMCLI_MIN_NAME_LENGTH_FOR_ALIAS 3
#define BCMCLI_ROOT_NAME "/"
/* Internal functions */
static void _bcmcli_alloc_root(const bcmcli_session_parm *parm);
static void _bcmcli_display_dir(bcmcli_session_extras *mon_session, bcmcli_entry *p_dir );
static int _bcmcli_parm_array_validate(const char *name, bcmcli_cmd_parm parms[]);
static bcmcli_token_type _bcmcli_get_word(bcmcli_session_extras *session, char **inbuf, char **p_word);
static bcmcli_token_type _bcmcli_analyze_token( const char *name );
static bcmos_errno _bcmcli_parse_parms( bcmcli_session_extras *mon_session, bcmcli_entry *p_token,
bcmcli_name_value *pairs, int npairs);
static bcmos_errno _bcmcli_extend_parms( bcmcli_session_extras *mon_session, bcmcli_name_value *pairs,
int npairs, bcmos_bool last_is_space, char *insert_str, uint32_t insert_size);
static bcmcli_entry *_bcmcli_search_token( bcmcli_entry *p_dir, const char *name );
static void _bcmcli_help_dir( bcmcli_session_extras *mon_session, bcmcli_entry *p_dir );
static void _bcmcli_help_entry(bcmcli_session_extras *mon_session, bcmcli_entry *p_token,
bcmcli_name_value *pairs, int npairs);
static void _bcmcli_help_populated_cmd(bcmcli_session_extras *mon_session, bcmcli_entry *p_token,
const char *partial_match, bcmos_bool suppress_assigned);
static void _bcmcli_choose_alias( bcmcli_entry *p_dir, bcmcli_entry *p_new_token );
static bcmcli_cmd_parm *_bcmcli_find_named_parm(bcmcli_session_extras *mon_session, const char *name);
static char *_bcmcli_strlwr( char *s );
static int _bcmcli_stricmp( const char *s1, const char *s2, int len );
static bcmos_errno _bcmcli_dft_scan_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
bcmcli_parm_value *value, const char *string_val);
static const char *_bcmcli_get_type_name(const bcmcli_cmd_parm *parm);
static void _bcmcli_dft_print_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
const bcmcli_parm_value *value);
static bcmos_errno _bcmcli_enum_scan_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
bcmcli_parm_value *value, const char *string_val);
static void _bcmcli_enum_print_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
const bcmcli_parm_value *value);
static bcmos_errno _bcmcli_enum_mask_scan_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
bcmcli_parm_value *value, const char *string_val);
static void _bcmcli_enum_mask_print_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
const bcmcli_parm_value *value);
static bcmos_errno _bcmcli_struct_scan_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
bcmcli_parm_value *value, const char *string_val);
static void _bcmcli_struct_print_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
const bcmcli_parm_value *value);
static bcmos_errno _bcmcli_buffer_scan_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
bcmcli_parm_value *value, const char *string_val);
static void _bcmcli_buffer_print_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
const bcmcli_parm_value *value);
static const char *_bcmcli_qualified_name( bcmcli_entry *token, char *buffer, int size);
static bcmos_errno _bcmcli_split(bcmcli_session_extras *mon_session, const char **p_str, int p_str_len,
bcmcli_name_value **pairs, int *npairs);
static void _bcmcli_assign_callbacks(bcmcli_cmd_parm *parm);
static void _bcmcli_log_cmd(const char *cmd);
static void _bcmcli_log_rc(bcmos_errno rc);
/*
* Command parameter array stack manipulation
*/
static bcmcli_parm_array *_bcmcli_parm_array_create(bcmcli_session_extras *mon_session,
const char *in_parm, bcmcli_parm_value *in_value, const bcmcli_cmd_parm parms[],
bcmcli_name_value pairs[], int npairs);
static bcmos_errno _bcmcli_parm_array_extend(bcmcli_session_extras *mon_session,
bcmcli_parm_array *pa, uint32_t pos, const bcmcli_cmd_parm extra_parms[]);
static void _bcmcli_parm_array_push(bcmcli_session_extras *mon_session, bcmcli_parm_array *pa);
static bcmcli_parm_array *_bcmcli_parm_array_pop(bcmcli_session_extras *mon_session);
static bcmcli_parm_array *_bcmcli_parm_array_top(bcmcli_session_extras *mon_session);
static bcmcli_parm_array *_bcmcli_parm_array_cur(bcmcli_session_extras *mon_session);
static bcmos_bool _bcmcli_parm_array_is_all_set(bcmcli_session_extras *mon_session, bcmcli_parm_array *pa);
static inline bcmcli_session_extras *_bcmcli_session_data(bcmcli_session *session)
{
if (!session)
return _bcmcli_root_session;
return bcmcli_session_data(session);
}
/** Add subdirectory to the parent directory
*
* \param[in] parent Parent directory handle. NULL=root
* \param[in] name Directory name
* \param[in] help Help string
* \param[in] access_right Access rights
* \param[in] extras Optional directory descriptor. Mustn't be allocated on the stack.
* \return new directory handle or NULL in case of failure
*/
bcmcli_entry *bcmcli_dir_add(bcmcli_entry *parent, const char *name,
const char *help, bcmcli_access_right access_right,
const bcmcli_dir_extra_parm *extras)
{
bcmcli_entry *p_dir;
bcmcli_entry **p_e;
assert(name);
assert(help);
if (!name || !help)
return NULL;
if (!_bcmcli_root_dir)
{
_bcmcli_alloc_root(NULL);
if (!_bcmcli_root_dir)
return NULL;
}
if (!parent)
parent = _bcmcli_root_dir;
p_dir = bcmcli_dir_find(parent, name);
if (p_dir != NULL)
{
BCMOS_TRACE_ERR("%s directory already created.\n", name);
return NULL;
}
p_dir=(bcmcli_entry *)bcmos_calloc( sizeof(bcmcli_entry) + strlen(name) + strlen(help) + 2 );
if ( !p_dir )
return NULL;
p_dir->name = (char *)(p_dir + 1);
strcpy( p_dir->name, name);
p_dir->help = p_dir->name + strlen(name) + 1;
strcpy(p_dir->help, help);
p_dir->sel = BCMCLI_ENTRY_DIR;
_bcmcli_choose_alias( parent, p_dir );
p_dir->access_right = access_right;
if (extras)
p_dir->u.dir.extras = *extras;
/* Add new directory to the parent's list */
p_dir->parent = parent;
p_e = &(parent->u.dir.first);
while (*p_e)
p_e = &((*p_e)->next);
*p_e = p_dir;
return p_dir;
}
static bcmcli_entry * find_entry_in_dir( bcmcli_entry *dir, const char *name,
bcmcli_entry_selector type, uint16_t recursive_search)
{
bcmcli_entry *p1, *p;
if ( !dir )
{
dir = _bcmcli_root_dir;
if (!dir)
return NULL;
}
p = dir->u.dir.first;
while (p)
{
if ( !_bcmcli_stricmp(p->name, name, -1) && type == p->sel )
return p;
if ( recursive_search && p->sel == BCMCLI_ENTRY_DIR )
{
p1 = find_entry_in_dir(p, name , type, 1 );
if ( p1 )
return p1;
}
p = p->next;
}
return NULL;
}
/* Scan directory tree and look for directory with name starts from
* root directory with name root_name
*/
bcmcli_entry *bcmcli_dir_find(bcmcli_entry *parent, const char *name)
{
if ( !parent )
parent = _bcmcli_root_dir;
return find_entry_in_dir(parent, name, BCMCLI_ENTRY_DIR, 0 );
}
/* Scan directory tree and look for command named "name". */
bcmcli_entry *bcmcli_cmd_find(bcmcli_entry *parent, const char *name )
{
if ( !parent )
parent = _bcmcli_root_dir;
return find_entry_in_dir(parent, name, BCMCLI_ENTRY_CMD, 0 );
}
/* Get CLI entry info */
void bcmcli_entry_info_get(bcmcli_session *session, const bcmcli_entry *entry,
bcmos_bool *is_dir, const char **name, const char **descr, const bcmcli_entry **parent)
{
if (is_dir)
*is_dir = (entry->sel == BCMCLI_ENTRY_DIR);
if (name)
*name = entry->name;
if (descr)
*descr = entry->help;
if (parent)
*parent = entry->parent;
}
/* Validate command parameter or a structure field */
static bcmos_errno _bcmcli_parm_validate(const char *name, bcmcli_cmd_parm *parm)
{
bcmos_errno rc = BCM_ERR_PARM;
do
{
/* User-defined parameter must have a scan_cb callback for text->value conversion */
if ((parm->type==BCMCLI_PARM_USERDEF) && !parm->scan_cb)
{
bcmos_printf("MON: %s> scan_cb callback must be set for user-defined parameter %s\n", name, parm->name);
break;
}
if (parm->type==BCMCLI_PARM_ENUM || parm->type==BCMCLI_PARM_ENUM_MASK)
{
if (!parm->enum_table)
{
bcmos_printf("MON: %s> value table must be set in low_val for enum parameter %s\n", name, parm->name);
break;
}
/* Check default value if any */
if ((parm->flags & BCMCLI_PARM_FLAG_DEFVAL))
{
if (_bcmcli_enum_mask_scan_cb(_bcmcli_root_session->session, parm, &parm->value, parm->value.string) < 0)
{
bcmos_printf("MON: %s> default value %s doesn't match any value of enum parameter %s\n", name, parm->value.string, parm->name);
break;
}
}
else if ((parm->flags & BCMCLI_PARM_FLAG_OPTIONAL))
{
/* Optional enum parameters are initialized by their 1st value by default.
* All other parameters are initialized to 0.
*/
bcmcli_enum_val *values=parm->enum_table;
parm->value.enum_val = values[0].val;
}
/* All values of enum mask parameters mast be complementary bits */
if (parm->type==BCMCLI_PARM_ENUM_MASK)
{
long all_mask = 0;
bcmcli_enum_val *values;
for (values=parm->enum_table; values->name; ++values)
all_mask |= values->val;
for (values=parm->enum_table; values->name; ++values)
{
if ((all_mask & values->val) != values->val)
{
bcmos_printf("MON: %s> enum_table values of enum_mask parameters must be complementary bits\n", name);
break;
}
all_mask &= ~values->val;
}
if (values->name)
break;
}
}
else if (parm->type==BCMCLI_PARM_BUFFER)
{
if (!parm->value.buffer.start || !parm->value.buffer.len)
{
bcmos_printf("MON: %s> value.buffer.start is not set for BUFFER parameter %s\n", name, parm->name);
break;
}
if (parm->max_array_size)
{
bcmos_printf("MON: %s> BUFFER arrays are not supported %s\n", name, parm->name);
break;
}
}
else if (parm->type==BCMCLI_PARM_STRUCT)
{
if (parm->max_array_size)
{
int j;
for (j = 0; j < parm->max_array_size; j++)
{
if (!parm->values || !parm->values[j].fields)
{
bcmos_printf("MON: %s> fields are not set for struct array parameter %s, element %d\n", name, parm->name, j);
break;
}
if (_bcmcli_parm_array_validate(name, parm->values[j].fields) < 0)
break;
}
/* Problem ? */
if (j < parm->max_array_size)
break;
}
else
{
if (!parm->value.fields)
{
bcmos_printf("MON: %s> fields are not set for struct parameter %s\n", name, parm->name);
break;
}
if (_bcmcli_parm_array_validate(name, parm->value.fields) < 0)
break;
}
}
if (parm->max_array_size)
{
if (!parm->values && parm->type != BCMCLI_PARM_STRUCT)
{
bcmos_printf("MON: %s> parm->values must be set for parameter-array %s\n", name, parm->name);
break;
}
}
rc = BCM_ERR_OK;
} while (0);
return rc;
}
/* Validate parameters/fields array.
* returns the number of valid parameters >= 0 or error < 0
*/
static int _bcmcli_parm_array_validate(const char *name, bcmcli_cmd_parm parms[])
{
bcmcli_cmd_parm *p;
bcmos_errno rc = BCM_ERR_OK;
if (!parms)
return 0;
for (p = parms; p->name && rc == BCM_ERR_OK; ++p)
{
rc = _bcmcli_parm_validate(name, p);
}
return (rc == BCM_ERR_OK) ? (p - parms) : (int)rc;
}
/** Add CLI command
*
* \param[in] dir Handle of directory to add command to. NULL=root
* \param[in] name Command name
* \param[in] cmd_cb Command handler
* \param[in] help Help string
* \param[in] access_right Access rights
* \param[in] extras Optional extras
* \param[in] parms Optional parameters array. Must not be allocated on the stack!
* If parms!=NULL, the last parameter in the array must have name==NULL.
* \return
* 0 =OK\n
* <0 =error code
*/
bcmos_errno bcmcli_cmd_add(bcmcli_entry *dir, const char *name, bcmcli_cmd_cb cmd_cb,
const char *help, bcmcli_access_right access_right,
const bcmcli_cmd_extra_parm *extras, bcmcli_cmd_parm parms[])
{
bcmcli_entry *p_token;
bcmcli_entry **p_e;
int i;
assert(name);
assert(help);
assert(cmd_cb);
if (!name || !cmd_cb || !help)
return BCM_ERR_PARM;
if (!_bcmcli_root_dir)
{
_bcmcli_alloc_root(NULL);
if (!_bcmcli_root_dir)
return BCM_ERR_NOMEM;
}
if (!dir)
dir = _bcmcli_root_dir;
p_token=(bcmcli_entry *)bcmos_calloc( sizeof(bcmcli_entry) + strlen(name) + strlen(help) + 2 );
if ( !p_token )
return BCM_ERR_NOMEM;
/* Copy name */
p_token->name = (char *)(p_token + 1);
strcpy( p_token->name, name );
p_token->help = p_token->name + strlen(name) + 1;
strcpy(p_token->help, help);
p_token->sel = BCMCLI_ENTRY_CMD;
p_token->u.cmd.cmd_cb = cmd_cb;
p_token->u.cmd.parms = parms;
if (extras)
p_token->u.cmd.extras = *extras;
p_token->access_right = access_right;
/* Convert name to lower case and choose alias */
_bcmcli_choose_alias(dir, p_token );
/* Check parameters */
i = _bcmcli_parm_array_validate(name, parms);
if (i < 0)
{
bcmos_free( p_token );
return (bcmos_errno)i;
}
p_token->u.cmd.num_parms = i;
/* Add token to the directory */
p_token->parent = dir;
p_e = &(dir->u.dir.first);
while (*p_e)
p_e = &((*p_e)->next);
*p_e = p_token;
return BCM_ERR_OK;
}
/** Destroy token (command or directory)
* \param[in] token Directory or command token. NULL=root
*/
void bcmcli_token_destroy(bcmcli_entry *token)
{
if (!token)
{
if (!_bcmcli_root_dir)
return;
token = _bcmcli_root_dir;
}
/* Remove from parent's list */
if (token->parent)
{
bcmcli_entry **p_e;
p_e = &(token->parent->u.dir.first);
while (*p_e)
{
if (*p_e == token)
{
*p_e = token->next;
break;
}
p_e = &((*p_e)->next);
}
}
/* Remove all directory entries */
if (token->sel == BCMCLI_ENTRY_DIR)
{
bcmcli_entry *e = token->u.dir.first;
while ((e = token->u.dir.first))
bcmcli_token_destroy(e);
}
else if (token->u.cmd.extras.free_parms)
token->u.cmd.extras.free_parms(token->u.cmd.parms);
/* Release the token */
bcmos_free(token);
if (token == _bcmcli_root_dir)
{
_bcmcli_root_dir = NULL;
if (_bcmcli_root_session)
{
bcmcli_session_close(_bcmcli_root_session->session);
_bcmcli_root_session = NULL;
}
}
}
/** Open monitor session
*
* Monitor supports multiple simultaneous sessions with different
* access rights.
* Note that there already is a default session with full administrative rights,
* that takes input from stdin and outputs to stdout.
* \param[in] parm Session parameters. Must not be allocated on the stack.
* \param[out] p_session Session handle
* \return
* 0 =OK\n
* <0 =error code
*/
bcmos_errno bcmcli_session_open(const bcmcli_session_parm *parm, bcmcli_session **p_session)
{
bcmcli_session *session;
bcmcli_session_extras *mon_session;
bcmcli_session_parm session_parms;
bcmos_errno rc;
assert(p_session);
if (!p_session)
return BCM_ERR_PARM;
if (!_bcmcli_root_dir)
{
_bcmcli_alloc_root(parm);
if (!_bcmcli_root_dir)
return BCM_ERR_NOMEM;
}
if (parm)
session_parms = *parm;
else
{
memset(&session_parms, 0, sizeof(session_parms));
session_parms.name = "unnamed";
}
/* Open comm session */
session_parms.extra_size = sizeof(bcmcli_session_extras);
rc = bcmcli_session_open_user(&session_parms, &session);
if (rc)
return rc;
mon_session = _bcmcli_session_data(session);
mon_session->curdir = _bcmcli_root_dir;
mon_session->session = session;
*p_session = session;
return BCM_ERR_OK;
}
#define BCMCLI_PARSE_RETURN(ret) \
do { \
rc = ret; \
goto bcmcli_parse_out; \
} while (0)
/* Parse a single command. Stop on ';' or EOL */
static bcmos_errno bcmcli_parse_command(bcmcli_session *session)
{
bcmcli_session_extras *mon_session=_bcmcli_session_data(session);
bcmcli_entry *p_token;
bcmcli_name_value *pairs = NULL;
const char *inbuf_org = mon_session->p_inbuf;
int stop_parsing = 0;
int npairs;
int i;
bcmos_errno rc = BCM_ERR_OK;
/* Make sure we start fresh */
bcmcli_session_stack_reset(session);
STAILQ_INIT(&mon_session->cmd_parms_stack);
/* Split string to name/value pairs */
rc = _bcmcli_split(mon_session, &mon_session->p_inbuf, strlen(mon_session->p_inbuf), &pairs, &npairs);
if (rc)
{
if (rc == BCM_ERR_NOENT)
rc = BCM_ERR_OK;
BCMCLI_PARSE_RETURN(rc);
}
/* Interpret empty string as "display directory" */
if ( !npairs )
{
_bcmcli_display_dir(mon_session, mon_session->curdir );
BCMCLI_PARSE_RETURN(BCM_ERR_OK);
}
mon_session->is_execution = BCMOS_TRUE;
mon_session->suppress_err_print = BCMOS_FALSE;
/* Identify parameters */
for (i=0; i<npairs && !rc && !stop_parsing; i++)
{
switch (pairs[i].type & BCMCLI_TOKEN_TYPE_MASK)
{
case BCMCLI_TOKEN_NAME:
case BCMCLI_TOKEN_VALUE:
/* Identify command. The 1st pair can't contain name, only value */
if (pairs[i].name)
{
bcmcli_session_print(session, "**ERR: %s is unexpected\n", pairs[i].name);
BCMCLI_PARSE_RETURN(BCM_ERR_PARM);
}
p_token = _bcmcli_search_token(mon_session->curdir, pairs[i].value);
if (p_token == NULL)
{
bcmcli_session_print(session, "**ERR: %s is unexpected\n", pairs[i].value);
BCMCLI_PARSE_RETURN(BCM_ERR_PARM);
}
/* Directory or command ? */
if (p_token->sel == BCMCLI_ENTRY_DIR)
{
mon_session->curdir = p_token;
_bcmcli_display_dir(mon_session, mon_session->curdir );
}
else
{
bcmcli_parm_array *pa;
/* Function token */
stop_parsing = 1;
mon_session->curcmd = p_token;
rc = _bcmcli_parse_parms(mon_session, p_token, &pairs[i+1], npairs-i-1);
if (rc != BCM_ERR_OK)
{
mon_session->suppress_err_print = BCMOS_TRUE; /* already printed */
_bcmcli_help_entry(mon_session, p_token, &pairs[i+1], npairs-i-1);
break;
}
/* Successfully parsed parameters. Invoke command handler */
_bcmcli_log_cmd(inbuf_org);
pa = _bcmcli_parm_array_top(mon_session);
BUG_ON(pa == NULL);
rc = p_token->u.cmd.cmd_cb(session, pa->cmd_parms, pa->num_pairs);
if (rc)
{
char buffer[BCMCLI_MAX_QUAL_NAME_LENGTH];
bcmcli_session_print(session, "MON: %s> failed with error code %s(%d)\n",
_bcmcli_qualified_name(p_token, buffer, sizeof(buffer)),
bcmos_strerror(rc), rc);
}
_bcmcli_log_rc(rc);
}
break;
case BCMCLI_TOKEN_UP: /* Go to upper directory */
if (mon_session->curdir->parent)
mon_session->curdir = mon_session->curdir->parent;
_bcmcli_display_dir(mon_session, mon_session->curdir );
break;
case BCMCLI_TOKEN_ROOT: /* Go to the root directory */
mon_session->curdir = _bcmcli_root_dir;
_bcmcli_display_dir(mon_session, mon_session->curdir );
break;
case BCMCLI_TOKEN_HELP: /* Display help */
if (i < npairs-1 &&
((p_token = _bcmcli_search_token( mon_session->curdir, pairs[i+1].value)) != NULL ))
{
_bcmcli_help_entry(mon_session, p_token, &pairs[i+2], npairs-i-2);
}
else
{
_bcmcli_help_dir(mon_session, mon_session->curdir);
}
stop_parsing = 1;
break;
default:
stop_parsing = 1;
break;
}
}
bcmcli_parse_out:
return rc;
}
/** Context extension */
bcmos_errno bcmcli_extend(bcmcli_session *session, char *input_str, char *insert_str, uint32_t insert_size)
{
bcmcli_session_extras *mon_session = _bcmcli_session_data(session);
bcmcli_entry *p_token;
bcmcli_name_value *pairs = NULL;
bcmos_bool last_is_space;
int npairs;
bcmos_errno rc = BCM_ERR_OK;
if (!mon_session || !mon_session->curdir || !input_str)
return BCM_ERR_PARM;
insert_str[0] = 0;
mon_session->p_inbuf = input_str;
last_is_space = strlen(input_str) && (input_str[strlen(input_str) - 1] == ' ');
/* Make sure we start fresh */
bcmcli_session_stack_reset(session);
STAILQ_INIT(&mon_session->cmd_parms_stack);
/* Split string to name/value pairs */
rc = _bcmcli_split(mon_session, &mon_session->p_inbuf, strlen(mon_session->p_inbuf), &pairs, &npairs);
if (rc)
return rc;
/* empty list - display list of commands */
if ( !npairs )
{
_bcmcli_display_dir(mon_session, mon_session->curdir );
BCMCLI_PARSE_RETURN(BCM_ERR_OK);
}
mon_session->is_execution = BCMOS_FALSE;
mon_session->suppress_err_print = BCMOS_TRUE;
/* Identify parameters */
switch (pairs[0].type)
{
case BCMCLI_TOKEN_NAME:
case BCMCLI_TOKEN_VALUE:
/* Identify command. The 1st pair can't contain name, only value */
if (pairs[0].name ||
!(p_token = _bcmcli_search_token(mon_session->curdir, pairs[0].value)))
{
_bcmcli_display_dir(mon_session, mon_session->curdir );
BCMCLI_PARSE_RETURN(BCM_ERR_PARM);
}
/* Directory or command ? */
if (p_token->sel != BCMCLI_ENTRY_CMD)
BCMCLI_PARSE_RETURN(BCM_ERR_OK);
/* Function token */
mon_session->curcmd = p_token;
rc = _bcmcli_extend_parms(mon_session, &pairs[1], npairs-1, last_is_space, insert_str, insert_size);
break;
default:
break;
}
bcmcli_parse_out:
return rc;
}
/** Parse and execute input string.
* input_string can contain multiple commands delimited by ';'
*
* \param[in] session Session handle
* \param[in] input_string String to be parsed. May consist of multiple ';'-delimited commands
*/
bcmos_errno bcmcli_parse(bcmcli_session *session, char* input_string)
{
bcmcli_session_extras *mon_session=_bcmcli_session_data(session);
uint32_t input_len;
int rc = 0;
if (!mon_session || !mon_session->curdir || !input_string)
return BCM_ERR_PARM;
input_len = strlen(input_string);
if (!input_len)
return BCM_ERR_OK;
/* cut CR, LF if any */
while (input_len && (input_string[input_len-1]=='\n' || input_string[input_len-1]=='\r'))
input_string[--input_len]=0;
mon_session->p_inbuf = input_string;
mon_session->stop_monitor = 0;
do {
rc = bcmcli_parse_command(session);
} while (mon_session->p_inbuf && mon_session->p_inbuf[0] && !mon_session->stop_monitor && !rc);
return rc ? BCM_ERR_PARSE : BCM_ERR_OK;
}
/** Read input and parse iteratively until EOF or bcmcli_is_stopped()
*
* \param[in] session Session handle
* \return
* =0 - OK \n
*/
bcmos_errno bcmcli_driver(bcmcli_session *session)
{
bcmcli_session_extras *mon_session=_bcmcli_session_data(session);
session = mon_session->session;
mon_session->stop_monitor = 0;
while (!bcmcli_is_stopped(session) &&
bcmcli_session_gets(session, mon_session->inbuf, sizeof(mon_session->inbuf)-1))
{
/* Session could've been stopped while in "gets". Check again and proceed if active */
if (!bcmcli_is_stopped(session))
bcmcli_parse(session, mon_session->inbuf);
}
return BCM_ERR_OK;
}
/* Stop monitor driver */
void bcmcli_stop( bcmcli_session *session )
{
bcmcli_session_extras *mon_session=_bcmcli_session_data(session);
assert(mon_session);
mon_session->stop_monitor = 1;
}
/** Returns 1 if monitor session is stopped
* \param[in] session Session handle
* \returns 1 if monitor session stopped by bcmcli_stop()\n
* 0 otherwise
*/
bcmos_bool bcmcli_is_stopped(bcmcli_session *session)
{
bcmcli_session_extras *mon_session=_bcmcli_session_data(session);
return mon_session->stop_monitor;
}
/** Get parameter number given its name.
* The function is intended for use by command handlers
* \param[in] session Session handle
* \param[in,out] parm_name Parameter name
* \return
* >=0 - parameter number\n
* <0 - parameter with this name doesn't exist
*/
int bcmcli_parm_number(bcmcli_session *session, const char *parm_name)
{
bcmcli_session_extras *mon_session=_bcmcli_session_data(session);
bcmcli_parm_array *pa;
int i;
if (!parm_name || !mon_session || !mon_session->curcmd)
return BCM_ERR_PARM;
pa = _bcmcli_parm_array_top(mon_session);
if (!pa || !pa->cmd_parms)
return BCM_ERR_PARM;
for(i=0;
pa->cmd_parms[i].name &&
_bcmcli_stricmp( parm_name, pa->cmd_parms[i].name, -1);
i++)
;
if (!pa->cmd_parms[i].name)
return BCM_ERR_PARM;
return i;
}
/** Get parameter by name
* The function is intended for use by command handlers
* \param[in] session Session handle
* \param[in] parm_name Parameter name
* \return
* parameter pointer or NULL if not found
*/
bcmcli_cmd_parm *bcmcli_parm_get(bcmcli_session *session, const char *parm_name)
{
bcmcli_session_extras *mon_session=_bcmcli_session_data(session);
bcmcli_parm_array *pa;
int nparm;
if (!mon_session)
return NULL;
pa = _bcmcli_parm_array_top(mon_session);
if (!pa || !pa->cmd_parms)
return NULL;
nparm = bcmcli_parm_number(session, parm_name);
if (nparm < 0)
{
return NULL;
}
return &pa->cmd_parms[nparm];
}
/** Check if parameter is set
* \param[in] session Session handle
* \param[in] parm_number Parameter number
* \return
* 1 if parameter is set\n
* 0 if parameter is not set or parm_number is invalid
*/
bcmos_errno bcmcli_parm_check(bcmcli_session *session, int parm_number)
{
bcmcli_session_extras *mon_session=_bcmcli_session_data(session);
bcmcli_parm_array *pa;
if (!mon_session || !mon_session->curcmd)
return BCM_ERR_PARM;
pa = _bcmcli_parm_array_top(mon_session);
if (!pa || !pa->cmd_parms)
return BCM_ERR_PARM;
if ((unsigned)parm_number >= pa->num_parms)
return BCM_ERR_PARM;
if (!(pa->cmd_parms[parm_number].flags & BCMCLI_PARM_FLAG_ASSIGNED))
return BCM_ERR_NOENT;
return BCM_ERR_OK;
}
/** Get enum's parameter string value given its internal value
* \param[in] session Session handle
* \param[in] parm Parameter
* \return
* enum string value or NULL if parameter is not enum or
* internal value is invalid
*/
const char *bcmcli_enum_parm_stringval(bcmcli_session *session, const bcmcli_cmd_parm *parm)
{
if (!parm || parm->type != BCMCLI_PARM_ENUM)
return NULL;
return bcmcli_enum_stringval(parm->enum_table, parm->value.unumber);
}
/* Get current directory handle */
bcmcli_entry *bcmcli_dir_get(bcmcli_session *session)
{
bcmcli_session_extras *mon_session=_bcmcli_session_data(session);
if (!mon_session)
return NULL;
return mon_session->curdir;
}
/* Set current directory */
bcmos_errno bcmcli_dir_set(bcmcli_session *session, bcmcli_entry *dir)
{
bcmcli_session_extras *mon_session=_bcmcli_session_data(session);
if (!mon_session)
return BCM_ERR_PARM;
/* Check access rights */
if (!dir)
dir = _bcmcli_root_dir;
if (dir->access_right > bcmcli_session_access_right(mon_session->session))
return BCM_ERR_PERM;
mon_session->curdir = dir;
return BCM_ERR_OK;
}
/** Get command that is being executed.
* The function is intended for use from command handler.
* \param[in] session Session handle
* \return The current command handle
*/
bcmcli_entry *bcmcli_cmd_get(bcmcli_session *session)
{
bcmcli_session_extras *mon_session=_bcmcli_session_data(session);
if (!mon_session)
return NULL;
return mon_session->curcmd;
}
/** Get token name
* \param[in] token Directory or command token
* \return directory token name
*/
const char *bcmcli_token_name(bcmcli_entry *token)
{
if (!token)
return NULL;
return token->name;
}
bcmcli_cmd_parm *bcmcli_find_named_parm(bcmcli_session *session, const char *name)
{
bcmcli_cmd_parm * cmd_parm;
if ( !session || !name || *name=='\0')
return NULL;
cmd_parm = _bcmcli_find_named_parm(_bcmcli_session_data(session), name);
if(cmd_parm && (cmd_parm->flags & BCMCLI_PARM_FLAG_ASSIGNED))
{
return cmd_parm;
}
return NULL;
}
/* Return TRUE if parameter value is set */
bcmos_bool bcmcli_parm_value_is_set(bcmcli_session *session, const bcmcli_cmd_parm *parm, uint32_t value_index)
{
bcmcli_session_extras *mon_session=_bcmcli_session_data(session);
if (value_index >= BCMCLI_MAX_ARRAY_LEN)
{
bcmcli_print(NULL, "MON> Value index %u is out of range\n", value_index);
return BCMOS_FALSE;
}
if (!mon_session)
{
bcmcli_print(NULL, "MON> Session %p is invalid\n", session);
return BCMOS_FALSE;
}
if (!parm->max_array_size)
return parm->value.is_set;
if (value_index >= parm->array_size || !parm->values)
return BCMOS_FALSE;
return parm->values[value_index].is_set;
}
/** Print CLI parameter value
* \param[in] session Session handle
* \param[in] parm Parameter
*/
static void bcmcli_parm_value_print(bcmcli_session *session, const bcmcli_cmd_parm *parm,
const bcmcli_parm_value *value)
{
parm->print_cb(session, parm, value);
}
/** Print CLI parameter
* \param[in] session Session handle
* \param[in] parm Parameter
*/
void bcmcli_parm_print(bcmcli_session *session, const bcmcli_cmd_parm *parm)
{
if (!bcmcli_parm_is_set(session, parm))
{
bcmcli_print(session, "%s=*unset*", parm->name);
return;
}
if (parm->max_array_size)
{
int i;
int values_printed=0;
if (parm->type != BCMCLI_PARM_STRUCT)
bcmcli_print(session, "%s=", parm->name);
for (i=0; i<parm->array_size; i++)
{
if (i && parm->type != BCMCLI_PARM_STRUCT)
bcmcli_print(session, ",");
if (parm->values[i].is_set)
{
if (parm->type == BCMCLI_PARM_STRUCT)
bcmcli_print(session, "%s%s[%d]=", values_printed ? " " : "", parm->name, i);
bcmcli_parm_value_print(session, parm, &parm->values[i]);
++values_printed;
}
}
}
else
{
bcmcli_print(session, "%s=", parm->name);
bcmcli_parm_value_print(session, parm, &parm->value);
}
}
/** Enable / disable CLI command logging
* \param[in] mode Logging flags
* \param[in] session Log session. Must be set if mode != BCMCLI_CMD_LOG_NONE
* \return 0=OK or error <0
*/
bcmos_errno bcmcli_log_set(bcmcli_log_mode mode, bcmcli_session *session)
{
if (mode != BCMCLI_LOG_NONE && session == NULL)
{
BCMOS_TRACE_ERR("log session must be set\n");
return BCM_ERR_PARM;
}
if (mode == BCMCLI_LOG_NONE)
{
_bcmcli_log_session = NULL;
}
else
{
_bcmcli_log_session = session;
}
_bcmcli_log_mode = mode;
return BCM_ERR_OK;
}
/** Write string to CLI log.
* The function is ignored if CLI logging is not enabled using bcmcli_log_set()
* \param[in] format printf-like format followed by arguments
*/
void bcmcli_log(const char *format, ...)
{
va_list ap;
if (!_bcmcli_log_session)
return;
va_start(ap, format);
bcmcli_session_vprint(_bcmcli_log_session, format, ap);
va_end(ap);
}
/*********************************************************/
/* Internal functions */
/*********************************************************/
static void _bcmcli_log_cmd(const char *cmd)
{
switch (_bcmcli_log_mode)
{
case BCMCLI_LOG_CLI:
bcmcli_log("%s\n", cmd);
break;
case BCMCLI_LOG_C_COMMENT:
bcmcli_log("/* %s */\n", cmd);
break;
default:
break;
}
}
static void _bcmcli_log_rc(bcmos_errno rc)
{
switch (_bcmcli_log_mode)
{
case BCMCLI_LOG_CLI:
bcmcli_log("# CLI command completed: %s (%d)\n", bcmos_strerror(rc), rc);
break;
case BCMCLI_LOG_C_COMMENT:
bcmcli_log("/* CLI command completed: %s (%d) */\n", bcmos_strerror(rc), rc);
break;
default:
break;
}
}
static bcmolt_string *_bcmcli_help_string_init(bcmcli_session_extras *mon_session)
{
bcmolt_string_init(&mon_session->help_string, mon_session->help_buf, sizeof(mon_session->help_buf));
return &mon_session->help_string;
}
#ifdef CONFIG_LINENOISE
static bcmos_errno _bcmcli_line_edit_cmd(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
if (n_parms > 0)
{
if ((parm[0].flags & BCMCLI_PARM_FLAG_ASSIGNED))
{
linenoiseSetDumbTerminal(session->ln_session, ! parm[0].value.number);
if ((parm[2].flags & BCMCLI_PARM_FLAG_ASSIGNED) && parm[0].value.number && parm[2].value.number)
linenoiseForceSmartTerminal(session->ln_session, BCMOS_TRUE);
}
if ((parm[1].flags & BCMCLI_PARM_FLAG_ASSIGNED))
linenoiseSetMultiLine(session->ln_session, parm[1].value.number);
}
else
{
int dumb = linenoiseGetDumbTerminal(session->ln_session);
int multiline = linenoiseGetMultiLine(session->ln_session);
bcmcli_session_print(session, "Line editing: %s Multiline: %s\n",
dumb ? "off" : "on", multiline ? "on" : "off");
}
return BCM_ERR_OK;
}
#endif
/* Allocate root directory and default session */
static void _bcmcli_alloc_root(const bcmcli_session_parm *first_session_parm)
{
bcmcli_session_parm session_parms;
bcmcli_session *session;
int rc;
/* The very first call. Allocate root structure */
if ((_bcmcli_root_dir=(bcmcli_entry *)bcmos_calloc(sizeof(bcmcli_entry) + strlen(BCMCLI_ROOT_HELP) + 2 )) == NULL)
return;
_bcmcli_root_dir->name = (char *)(_bcmcli_root_dir + 1);
_bcmcli_root_dir->help = (char *)(_bcmcli_root_dir->name + 1);
strcpy(_bcmcli_root_dir->help, BCMCLI_ROOT_HELP);
_bcmcli_root_dir->sel = BCMCLI_ENTRY_DIR;
_bcmcli_root_dir->access_right = BCMCLI_ACCESS_GUEST;
memset(&session_parms, 0, sizeof(session_parms));
session_parms.access_right = BCMCLI_ACCESS_ADMIN;
session_parms.extra_size = sizeof(bcmcli_session_extras);
session_parms.name = "monroot";
if (first_session_parm)
{
session_parms.line_edit_mode = first_session_parm->line_edit_mode;
}
rc = bcmcli_session_open(&session_parms, &session);
if (rc)
{
bcmos_free(_bcmcli_root_dir);
_bcmcli_root_dir = NULL;
_bcmcli_root_session = NULL;
return;
}
_bcmcli_root_session = _bcmcli_session_data(session);
_bcmcli_root_session->session = session;
_bcmcli_root_session->curdir = _bcmcli_root_dir;
/* Add command to disable/enable line editing */
#ifdef CONFIG_LINENOISE
if (session_parms.line_edit_mode != BCMCLI_LINE_EDIT_DISABLE)
{
BCMCLI_MAKE_CMD(NULL, "~", "Enable/disable/query line editing", _bcmcli_line_edit_cmd,
BCMCLI_MAKE_PARM_ENUM("enable", "Enable line editing", bcmcli_enum_bool_table, BCMCLI_PARM_FLAG_OPTIONAL),
BCMCLI_MAKE_PARM_ENUM("multiline", "Enable multiline mode", bcmcli_enum_bool_table,
BCMCLI_PARM_FLAG_OPTIONAL),
BCMCLI_MAKE_PARM_ENUM("force", "Force line editing mode", bcmcli_enum_bool_table,
BCMCLI_PARM_FLAG_OPTIONAL));
}
#endif
}
/* Display directory */
static void _bcmcli_display_dir(bcmcli_session_extras *mon_session, bcmcli_entry *p_dir)
{
bcmcli_session *session = mon_session->session;
bcmcli_entry *p_token;
bcmcli_entry *prev=NULL;
bcmolt_string *help_string = _bcmcli_help_string_init(mon_session);
bcmolt_string_append(help_string, "%s%s> ", (p_dir==_bcmcli_root_dir)?"":".../", p_dir->name );
p_token = p_dir->u.dir.first;
while ( p_token )
{
if (p_token->access_right <= bcmcli_session_access_right(session))
{
if (prev)
bcmolt_string_append(help_string, ", ");
bcmolt_string_append(help_string, "%s", p_token->name );
if (p_token->sel == BCMCLI_ENTRY_DIR )
bcmolt_string_append(help_string, "/");
prev = p_token;
}
p_token = p_token->next;
}
bcmolt_string_append(help_string, "\n");
bcmcli_session_print(session, "%s", bcmolt_string_get(help_string));
}
/* Is character that can be used in a single token ? */
static inline int _bcmcli_is_special_char(char c)
{
if (!c)
return 0;
return (c == BCMCLI_HELP_CHAR || c == BCMCLI_COMMENT_CHAR || c == BCMCLI_EQUAL_CHAR);
}
/* Make a preliminary analizis of <name> token.
* Returns a token type (Empty, Up, Root, Break, Name)
*/
static bcmcli_token_type _bcmcli_analyze_token( const char *name )
{
if (!name[0] || name[0]==';')
return BCMCLI_TOKEN_EMPTY;
if (*name == BCMCLI_COMMENT_CHAR)
return BCMCLI_TOKEN_BREAK;
if (!strcmp(name, BCMCLI_UP_STR))
return BCMCLI_TOKEN_UP;
if (!strcmp(name, BCMCLI_ROOT_STR))
return BCMCLI_TOKEN_ROOT;
if (*name == BCMCLI_HELP_CHAR)
return BCMCLI_TOKEN_HELP;
return BCMCLI_TOKEN_VALUE;
}
/* isspace wrapper */
static inline int _bcmcli_isspace(char c)
{
return isspace((int)c);
}
/* Cut the first word from <p_inbuf>.
* - Return pointer to start of the word in p_word
* - 0 terminator is inserted in the end of the word
* - session->p_inbuf is updated to point after the word
* Returns token type
*/
static bcmcli_token_type _bcmcli_get_word(bcmcli_session_extras *mon_session, char **buf, char **p_word)
{
bcmcli_token_type token_type = BCMCLI_TOKEN_EMPTY;
bcmcli_token_type token_flags = BCMCLI_TOKEN_EMPTY;
char *p_inbuf = *buf;
char next_char = 0;
bcmos_bool quoted_string = BCMOS_FALSE;
/* Skip leading blanks */
while (*p_inbuf && (_bcmcli_isspace(*p_inbuf) || (*p_inbuf==',')))
++p_inbuf;
*buf = p_inbuf;
if (! *p_inbuf)
return BCMCLI_TOKEN_EMPTY;
if (*p_inbuf == ';')
{
*p_inbuf = 0;
*buf = ++p_inbuf;
return BCMCLI_TOKEN_EMPTY;
}
/* Quoted string ? */
if (*p_inbuf == '"')
{
quoted_string = BCMOS_TRUE;
*p_word = ++p_inbuf;
while ( *p_inbuf && *p_inbuf!='"' )
++p_inbuf;
if (*p_inbuf != '"')
{
bcmcli_session_print(mon_session->session, "MON: unterminated string %s\n", *p_word);
*buf = p_inbuf; /* progress parser past the point of failure */
return BCMCLI_TOKEN_EMPTY;
}
if (*p_inbuf)
*(p_inbuf++) = 0;
}
else if (*p_inbuf == BCMCLI_STRUCT_START_CHAR)
{
int bracket_count = 1;
token_flags |= BCMCLI_TOKEN_STRUCT_VALUE;
quoted_string = BCMOS_TRUE;
*p_word = p_inbuf++;
while (*p_inbuf && bracket_count)
{
if (*p_inbuf == BCMCLI_STRUCT_START_CHAR)
++bracket_count;
else if (*p_inbuf == BCMCLI_STRUCT_END_CHAR)
--bracket_count;
++p_inbuf;
}
if (bracket_count)
token_flags |= BCMCLI_TOKEN_UNTERMINATED_STRUCT_VALUE;
else if (*p_inbuf)
*(p_inbuf++) = 0;
}
else
{
*p_word = p_inbuf;
if (!_bcmcli_is_special_char(*p_inbuf))
{
do ++p_inbuf;
while (*p_inbuf && !_bcmcli_isspace(*p_inbuf) && *p_inbuf!=';' && !_bcmcli_is_special_char(*p_inbuf));
/* Skip trailing spaces */
while (*p_inbuf && _bcmcli_isspace(*p_inbuf))
*(p_inbuf++) = 0;
next_char = *p_inbuf;
if (next_char == BCMCLI_EQUAL_CHAR)
{
*(p_inbuf++) = 0;
token_flags |= BCMCLI_TOKEN_HAS_EQUAL_SIGN;
}
}
else if (*p_inbuf)
{
++p_inbuf;
}
}
*buf = p_inbuf;
token_type = _bcmcli_analyze_token( *p_word );
if (token_type == BCMCLI_TOKEN_VALUE &&
(next_char == BCMCLI_EQUAL_CHAR ||
((token_flags & BCMCLI_TOKEN_STRUCT_VALUE) == 0 && strchr(*p_word, BCMCLI_ARRAY_START_CHAR) != NULL)))
{
token_type = BCMCLI_TOKEN_NAME;
}
if ((token_type == BCMCLI_TOKEN_EMPTY) && quoted_string)
token_type = BCMCLI_TOKEN_VALUE;
token_type |= token_flags;
return token_type;
}
/* split indexed name in format "name[index]" to "name" and "index" component */
static bcmos_errno _bcmcli_set_name_index(bcmcli_session_extras *mon_session, bcmcli_name_value *pair)
{
char *p_bra, *p_ket;
uint32_t len;
if (!pair->name)
return BCM_ERR_OK;
p_bra = strchr(pair->name, BCMCLI_ARRAY_START_CHAR);
if (!p_bra)
return BCM_ERR_OK;
p_ket = strchr(p_bra+1, BCMCLI_ARRAY_END_CHAR);
/* Handle case of missing closing bracket. It can happen either by mistake
* or during tab completion
*/
if (!p_ket)
{
/* If we are past "=" sign and index is not terminated - it is an error */
if (pair->value)
{
bcmcli_session_print(mon_session->session, "MON: unterminated array index %s\n", pair->name);
return BCM_ERR_PARM;
}
pair->type |= BCMCLI_TOKEN_UNTERMINATED_ARRAY_INDEX;
}
*(p_bra++) = 0;
if (p_ket)
*p_ket = 0;
/* Skip leading and trailing spaces */
while (*p_bra && _bcmcli_isspace(*p_bra))
++p_bra;
len = strlen(p_bra);
while (len && _bcmcli_isspace(p_bra[len-1]))
{
p_bra[len-1] = 0;
--len;
}
pair->index = p_bra;
return BCM_ERR_OK;
}
#define BCMCLI_SPLIT_RETURN(_rc, _p_str, _copy, _p_stop) \
do { \
*(_p_str) += (_p_stop - _copy);\
return (_rc);\
} while (0)
/* Split string str to [name=]value pairs.
* *p_str updated to point to the place where parser stopped
*/
static bcmos_errno _bcmcli_split(bcmcli_session_extras *mon_session, const char **p_str, int p_str_len,
bcmcli_name_value **p_pairs, int *p_npairs)
{
const char *str;
bcmcli_name_value *pairs;
char *copy_of_str, *tmp_str;
char *word;
bcmcli_token_type token_type, prev_type=BCMCLI_TOKEN_EMPTY;
int n = 0;
bcmos_errno rc;
if (!p_str || !*p_str)
return BCM_ERR_PARM;
str = *p_str;
/* Make a copy of parsed string because we are going to insert 0 terminators */
copy_of_str = bcmcli_session_stack_calloc(mon_session->session, p_str_len + 1);
if (!copy_of_str)
return BCM_ERR_NOMEM;
strncpy(copy_of_str, str, p_str_len);
copy_of_str[p_str_len] = '\0';
/* Calculate number of pairs first */
tmp_str = copy_of_str;
token_type = _bcmcli_get_word(mon_session, &tmp_str, &word);
while (token_type != BCMCLI_TOKEN_EMPTY && !(token_type & BCMCLI_TOKEN_BREAK))
{
/* Skip =value */
if (!((prev_type & BCMCLI_TOKEN_NAME) && (token_type & BCMCLI_TOKEN_VALUE)))
++n;
prev_type = token_type;
token_type = _bcmcli_get_word(mon_session, &tmp_str, &word);
}
*p_npairs = n;
if (!n)
{
*p_pairs = NULL;
rc = (token_type & BCMCLI_TOKEN_BREAK) ? BCM_ERR_NOENT : BCM_ERR_OK;
BCMCLI_SPLIT_RETURN(rc, p_str, copy_of_str, tmp_str);
}
/* Allocate name/value pairs on session stack */
*p_pairs = pairs = bcmcli_session_stack_calloc(mon_session->session, n * sizeof(bcmcli_name_value));
if (!pairs)
BCMCLI_SPLIT_RETURN(BCM_ERR_NOMEM, p_str, copy_of_str, tmp_str);
/* Now restore the copy of the original string and set names and values */
rc = BCM_ERR_OK;
strncpy(copy_of_str, str, p_str_len);
copy_of_str[p_str_len] = '\0';
tmp_str = copy_of_str;
token_type = _bcmcli_get_word(mon_session, &tmp_str, &word);
prev_type = BCMCLI_TOKEN_EMPTY;
--pairs; /* it is going to be pre-incremented */
while ((token_type != BCMCLI_TOKEN_EMPTY) && !(token_type & BCMCLI_TOKEN_BREAK))
{
if (!((prev_type & BCMCLI_TOKEN_NAME) && (token_type & BCMCLI_TOKEN_VALUE)))
++pairs;
pairs->type = token_type;
if (token_type & BCMCLI_TOKEN_NAME)
{
pairs->name = word;
rc = _bcmcli_set_name_index(mon_session, pairs);
if (rc != BCM_ERR_OK)
break;
}
else
{
pairs->value = word;
}
prev_type = token_type;
token_type = _bcmcli_get_word(mon_session, &tmp_str, &word);
}
BCMCLI_SPLIT_RETURN(rc, p_str, copy_of_str, tmp_str);
}
/* Find parameter by name */
static bcmcli_cmd_parm *_bcmcli_find_named_parm(bcmcli_session_extras *mon_session, const char *name)
{
bcmcli_parm_array *pa = _bcmcli_parm_array_cur(mon_session);
int i;
if (!pa || !pa->cmd_parms)
return NULL;
for (i = 0; i < pa->num_parms; i++)
{
if (!_bcmcli_stricmp(name, pa->cmd_parms[i].name, -1))
return &pa->cmd_parms[i];
}
return NULL;
}
/* Extend session parameter table based on selector value */
static bcmos_errno _bcmcli_extend_parm_table(bcmcli_session_extras *mon_session,
bcmcli_parm_array *pa, bcmcli_cmd_parm **p_selector, const char *value)
{
bcmcli_cmd_parm *selector = *p_selector;
bcmcli_enum_val *values=selector->enum_table;
int nsel = selector - pa->cmd_parms;
bcmos_errno err;
/* Find selected value */
while (values->name)
{
if (!_bcmcli_stricmp(values->name, value, -1))
break;
++values;
}
if (!values->name)
return BCM_ERR_INTERNAL;
/* Extend current parameters array */
err = _bcmcli_parm_array_extend(mon_session, pa, nsel + 1, values->parms);
if (err == BCM_ERR_OK)
{
*p_selector = &pa->cmd_parms[nsel];
}
return err;
}
/* Parse a single parameter value (scalar value or array element) */
static bcmos_errno _bcmcli_parse_1value(bcmcli_session_extras *mon_session, const char *block_name,
bcmcli_cmd_parm *parm, bcmcli_parm_value *value, const char *string_value,
int val_len)
{
bcmos_errno rc;
if (val_len >= 0)
{
/* We are dealing with array element. string_value is comma rather than
* 0-terminated. Copy it aside.
*/
char val_copy[val_len + 1];
strncpy(val_copy, string_value, val_len);
val_copy[val_len] = 0;
rc = parm->scan_cb(mon_session->session, parm, value, val_copy);
}
else
{
rc = parm->scan_cb(mon_session->session, parm, value, string_value);
}
if (rc == BCM_ERR_OK)
{
value->is_set = BCMOS_TRUE;
}
else
{
if (!mon_session->suppress_err_print)
{
bcmcli_session_print(mon_session->session, "MON: %s> <%s>: value %s is invalid\n",
block_name, parm->name, string_value);
}
}
return rc;
}
/* Parse parameter value, including array value (comma-delimited list of element values) */
static bcmos_errno _bcmcli_parse_value(bcmcli_session_extras *mon_session, const char *block_name,
bcmcli_cmd_parm *parm, bcmcli_name_value *name_value)
{
bcmos_errno rc = BCM_ERR_OK;
const char *string_value = name_value->value;
if (name_value->index && !parm->max_array_size)
{
bcmcli_session_print(mon_session->session, "MON: %s>: <%s> unexpected index %s\n",
block_name, parm->name, name_value->index);
return BCM_ERR_PARM;
}
if (parm->max_array_size)
{
uint32_t i = 0;
uint32_t index;
/* Specific index ? */
if (name_value->index)
{
char *p_end = NULL;
index = strtoul(name_value->index, &p_end, 0);
if (index >= parm->max_array_size || (p_end && *p_end) )
{
bcmcli_session_print(mon_session->session, "MON: %s>: <%s> index %s is invalid\n",
block_name, parm->name, name_value->index);
return BCM_ERR_PARM;
}
rc = _bcmcli_parse_1value(mon_session, block_name,
parm, &parm->values[index], string_value, -1);
if (rc == BCM_ERR_OK && parm->array_size < index + 1)
parm->array_size = index + 1;
}
else if (_bcmcli_stricmp(string_value, BCMCLI_ARRAY_EMPTY, -1))
{
/* parse comma-delimited array element values */
for (i = 0; i < parm->max_array_size && string_value && *string_value && !rc; i++)
{
const char *pcomma;
int val_len;
pcomma = strchr(string_value, BCMCLI_ARRAY_DELIM_CHAR);
if (pcomma)
{
val_len = pcomma - string_value;
}
else
{
val_len = -1; /* to the end of string */
}
/* No value ? */
if (_bcmcli_stricmp(string_value, BCMCLI_PARM_NO_VALUE, val_len))
{
rc = _bcmcli_parse_1value(mon_session, block_name,
parm, &parm->values[i], string_value, val_len);
}
string_value = pcomma ? pcomma + 1 : NULL;
}
/* If all parsed values were ok, but we have more values than array size - it is an error */
if (string_value && *string_value && !rc)
{
rc = BCM_ERR_TOO_MANY;
if (!mon_session->suppress_err_print)
{
bcmcli_session_print(mon_session->session, "MON: %s> <%s>: too many values. %s is invalid\n",
block_name, parm->name, string_value);
}
}
parm->array_size = i;
}
}
else
{
if (string_value && strcmp(string_value, BCMCLI_PARM_NO_VALUE))
{
rc = _bcmcli_parse_1value(mon_session, block_name,
parm, &parm->value, string_value, -1);
}
}
return rc;
}
/* Populate session parameters. Apply selectors */
static bcmos_errno _bcmcli_populate_parms(
bcmcli_session_extras *mon_session,
const char *block_name,
bcmcli_parm_array *pa)
{
const char *parm_value;
int positional=1;
bcmcli_cmd_parm *parms = pa->cmd_parms;
bcmcli_name_value *pairs = pa->name_value_pairs;
bcmcli_cmd_parm *cur_parm;
bcmos_errno rc = BCM_ERR_OK;
int i;
int j;
pa->num_parsed = 0;
parms=pa->cmd_parms;
/* Build a format string */
for (i=0; i<pa->num_pairs && pairs[i].type != BCMCLI_TOKEN_BREAK; i++)
{
mon_session->cur_token_type = pairs[i].type;
parm_value = pairs[i].value;
pa->num_parsed = i;
cur_parm = NULL;
rc = BCM_ERR_PARM;
/* Named parameter ? */
if (pairs[i].name)
{
positional = 0; /* No more positional parameters */
/* Check name */
cur_parm = _bcmcli_find_named_parm(mon_session, pairs[i].name);
if (!cur_parm)
{
if (!mon_session->suppress_err_print)
{
bcmcli_session_print(mon_session->session, "MON: %s> parameter <%s> doesn't exist\n",
block_name, pairs[i].name);
}
break;
}
if (!parm_value)
{
if (!mon_session->suppress_err_print)
{
bcmcli_session_print(mon_session->session, "MON: %s> <%s>: value is missing\n",
block_name, cur_parm->name);
}
break;
}
}
else
{
/* Parse the parameter name alone (without =value) if the proper flag is set. */
if (parm_value
&& ((cur_parm = _bcmcli_find_named_parm(mon_session, parm_value)) != NULL)
&& (cur_parm->flags & BCMCLI_PARM_FLAG_OMIT_VAL) != 0)
{
parm_value = NULL;
cur_parm->flags |= BCMCLI_PARM_FLAG_DEFVAL;
/* If the value-less parameter is an enum, set it to the first enum value. Else, leave it default. */
if (cur_parm->type == BCMCLI_PARM_ENUM)
{
cur_parm->value.enum_val = cur_parm->enum_table->val;
}
positional = 0; /* No more positional parameters */
}
else if (parms)
{
if (!positional || (parms[i].type == BCMCLI_PARM_STRUCT))
{
if (!mon_session->suppress_err_print)
bcmcli_session_print(mon_session->session, "MON: %s> Expected named parameter. Got %s\n", block_name, parm_value);
break;
}
cur_parm = &parms[i];
}
if (!cur_parm || !cur_parm->name)
{
if (!mon_session->suppress_err_print)
bcmcli_session_print(mon_session->session, "MON: %s> Too many parameters. %s is unexpected\n", block_name, parm_value);
break;
}
}
if ((cur_parm->flags & BCMCLI_PARM_FLAG_ASSIGNED) && !cur_parm->max_array_size)
{
if (!mon_session->suppress_err_print)
{
bcmcli_session_print(mon_session->session, "MON: %s> Attempt to assign parameter %s more than once\n",
block_name, cur_parm->name);
}
break;
}
if (pairs[i].index && !cur_parm->max_array_size)
{
bcmcli_session_print(mon_session->session, "MON: %s> %s: index %s is unexpected for scalar parameter\n",
block_name, cur_parm->name, pairs[i].index);
}
if (parm_value)
{
if (cur_parm->type == BCMCLI_PARM_STRING)
cur_parm->value.string = parm_value;
else
{
rc = _bcmcli_parse_value(mon_session, block_name, cur_parm, &pairs[i]);
if (rc)
break;
/* For parameter-selector extend list of parameters accordingly */
if (cur_parm->flags & BCMCLI_PARM_FLAG_SELECTOR)
{
rc = _bcmcli_extend_parm_table(mon_session, pa, &cur_parm, parm_value);
if (rc)
break;
}
}
cur_parm->flags |= BCMCLI_PARM_FLAG_ASSIGNED;
/* Check range */
if ((cur_parm->flags & BCMCLI_PARM_FLAG_RANGE))
{
if (cur_parm->max_array_size)
{
for (j = 0; j < cur_parm->array_size; j++)
{
if (((cur_parm->values[j].number < cur_parm->low_val) ||
(cur_parm->values[j].number > cur_parm->hi_val)))
{
bcmcli_session_print(mon_session->session, "\nMON: %s> <%s>: %ld out of range (%ld, %ld)\n",
block_name, cur_parm->name, cur_parm->values[j].number, cur_parm->low_val, cur_parm->hi_val);
rc = BCM_ERR_RANGE;
break;
}
}
if (j < cur_parm->array_size)
break;
}
else if (((cur_parm->value.number < cur_parm->low_val) ||
(cur_parm->value.number > cur_parm->hi_val)))
{
bcmcli_session_print(mon_session->session, "\nMON: %s> <%s>: %ld out of range (%ld, %ld)\n",
block_name, cur_parm->name, cur_parm->value.number, cur_parm->low_val, cur_parm->hi_val);
rc = BCM_ERR_RANGE;
break;
}
}
}
rc = BCM_ERR_OK;
}
pa->num_parsed = i;
/* Final validation */
if (mon_session->is_execution && rc == BCM_ERR_OK)
{
/* Make sure that all mandatory parameters are set. Process default values */
for (i=0; i<pa->num_parms; i++)
{
rc = BCM_ERR_PARM;
cur_parm = &pa->cmd_parms[i];
if (!(cur_parm->flags & BCMCLI_PARM_FLAG_ASSIGNED))
{
if ((cur_parm->flags & BCMCLI_PARM_FLAG_DEFVAL))
{
cur_parm->flags |= BCMCLI_PARM_FLAG_ASSIGNED;
}
else if (!(cur_parm->flags & BCMCLI_PARM_FLAG_OPTIONAL) )
{
/* Mandatory parameter missing */
bcmcli_session_print(mon_session->session, "MON: %s> Mandatory parameter <%s> is missing\n",
block_name, cur_parm->name);
break;
}
}
rc = BCM_ERR_OK;
}
}
return rc;
}
/* Parse p_inbuf string based on parameter descriptions in <p_token>.
* Fill parameter values in <p_token>.
* Returns the number of parameters filled or BCM_ERR_PARM
* To Do: add a option of one-by-one user input of missing parameters.
*/
static bcmos_errno _bcmcli_parse_parms( bcmcli_session_extras *mon_session, bcmcli_entry *cmd, bcmcli_name_value *pairs, int npairs)
{
bcmcli_parm_array *pa;
bcmos_errno rc;
/* Make sure that all structures are terminated */
if (npairs && (pairs[npairs-1].type & BCMCLI_TOKEN_UNTERMINATED_STRUCT_VALUE))
{
bcmcli_session_print(mon_session->session, "MON: %s> Unterminated structure <%s>\n",
cmd->name, pairs[npairs-1].name ? pairs[npairs-1].name : "");
return BCM_ERR_PARM;
}
/* Create parameters array */
pa = _bcmcli_parm_array_create(mon_session, NULL, NULL, cmd->u.cmd.parms, pairs, npairs);
if (pa == NULL)
return BCM_ERR_NOMEM;
/* Populate parameter table */
mon_session->curcmd = cmd;
rc = _bcmcli_populate_parms(mon_session, cmd->name, pa);
return rc;
}
/* insert value skipping partial match trhat is already present */
static void _bcmcli_insert(const char *partial_match, const char *insert_val1,
const char *insert_val2, char *insert_str, uint32_t insert_size)
{
if (partial_match)
insert_val1 += strlen(partial_match);
bcmolt_strncat(insert_str, insert_val1, insert_size);
if (insert_val2)
bcmolt_strncat(insert_str, insert_val2, insert_size);
}
static void _bcmcli_update_longest_match(char *longest_match, const char *name)
{
uint32_t nlen = strlen(name);
uint32_t lmlen = strlen(longest_match);
if (nlen < lmlen)
{
lmlen = nlen;
}
while (lmlen && memcmp(longest_match, name, lmlen))
{
--lmlen;
}
longest_match[lmlen] = 0;
}
static void _bcmcli_help_parm_brief(bcmcli_session_extras *mon_session, const bcmcli_cmd_parm *parm)
{
bcmcli_session_print(mon_session->session, "\n\t%s(%s)", parm->name, _bcmcli_get_type_name(parm));
if (parm->max_array_size || parm->type == BCMCLI_PARM_BUFFER)
{
uint32_t num_entries = (parm->type == BCMCLI_PARM_BUFFER) ? parm->value.buffer.len : parm->max_array_size;
bcmcli_session_print(mon_session->session, "[%u]", num_entries);
}
if ((parm->flags & BCMCLI_PARM_FLAG_RANGE))
{
bcmcli_parm_value low_val = { {.number = parm->low_val} };
bcmcli_parm_value hi_val = { {.number = parm->hi_val} };
bcmcli_session_print(mon_session->session, " [");
parm->print_cb(mon_session->session, parm, &low_val);
bcmcli_session_print(mon_session->session, "..");
parm->print_cb(mon_session->session, parm, &hi_val);
bcmcli_session_print(mon_session->session, "]");
}
bcmcli_session_print(mon_session->session, "- %s\n", parm->description);
}
/* extend value.
* If !enum - do nothing
* If more than 1 matching value - display them
* If no matching value - do nothing
* If 1 matching value - insert
*/
static void _bcmcli_extend_value(bcmcli_session_extras *mon_session, bcmcli_cmd_parm *parm,
const char *partial_value, char *insert_str, uint32_t insert_size)
{
int nmatch = 0;
bcmcli_enum_val *vals = parm->enum_table;
char longest_match[BCMCLI_MAX_SEARCH_SUBSTR_LENGTH]="";
if ((parm->type != BCMCLI_PARM_ENUM && parm->type != BCMCLI_PARM_ENUM_MASK) || !vals)
{
if (parm->type == BCMCLI_PARM_STRUCT && partial_value == NULL)
bcmolt_strncat(insert_str, BCMCLI_STRUCT_START_STR, insert_size);
_bcmcli_help_parm_brief(mon_session, parm);
return;
}
/* If enum mask, partial value can be a sum of values. Skip past the last '+' sign */
if (parm->type == BCMCLI_PARM_ENUM_MASK && partial_value)
{
char *pdel = strrchr(partial_value, BCMCLI_ENUM_MASK_DEL_CHAR);
if (pdel)
partial_value = pdel + 1;
}
while (vals->name)
{
if (!partial_value || !strncmp(vals->name, partial_value, strlen(partial_value)))
{
if (!nmatch)
{
bcmolt_strncat(longest_match, vals->name, sizeof(longest_match));
}
else
{
_bcmcli_update_longest_match(longest_match, vals->name);
}
++nmatch;
}
++vals;
}
if (!nmatch)
return;
if (nmatch == 1)
{
_bcmcli_insert(partial_value, longest_match, " ", insert_str, insert_size);
return;
}
/* display all matching values */
_bcmcli_insert(partial_value, longest_match, "", insert_str, insert_size);
bcmcli_session_print(mon_session->session, "\n");
vals = parm->enum_table;
while (vals->name)
{
if (!partial_value || !strncmp(vals->name, partial_value, strlen(partial_value)))
bcmcli_session_print(mon_session->session, " %s", vals->name);
++vals;
}
bcmcli_session_print(mon_session->session, "\n");
}
/* calculate number of matching parameter names */
static int _bcmcli_num_matching_names(bcmcli_session_extras *mon_session, const char *partial_value, const bcmcli_cmd_parm **first_match)
{
bcmcli_parm_array *pa = _bcmcli_parm_array_cur(mon_session);
int i;
int nmatch = 0;
*first_match = NULL;
if (!pa)
return 0;
for (i = 0; i < pa->num_parms; i++)
{
uint32_t flags = pa->cmd_parms[i].flags;
if ((flags & BCMCLI_PARM_FLAG_ASSIGNED))
continue;
if (partial_value && strncmp(pa->cmd_parms[i].name, partial_value, strlen(partial_value)))
continue;
if (*first_match == NULL)
*first_match = &pa->cmd_parms[i];
++nmatch;
}
return nmatch;
}
/* calculate longest matching string.
* returns number of matching parameters
*/
static int _bcmcli_longest_match(bcmcli_session_extras *mon_session, const char *partial_value,
char *longest_match, uint32_t longest_match_size, const bcmcli_cmd_parm **first_match)
{
int nmatch0 = _bcmcli_num_matching_names(mon_session, partial_value, first_match);
int nmatch;
const char *match_name;
if (!nmatch0)
return 0;
match_name = (*first_match)->name;
if (nmatch0 == 1)
{
bcmolt_strncpy(longest_match, match_name, longest_match_size);
return nmatch0;
}
bcmolt_strncpy(longest_match, match_name, longest_match_size);
nmatch = _bcmcli_num_matching_names(mon_session, longest_match, first_match);
while (nmatch != nmatch0)
{
longest_match[strlen(longest_match)-1] = 0;
nmatch = _bcmcli_num_matching_names(mon_session, longest_match, first_match);
}
return nmatch0;
}
/* display/insert unset matching names
* If more than 1 matching value - display them
* If no matching value - do nothing
* If 1 matching value - insert
*/
static void _bcmcli_extend_name(bcmcli_session_extras *mon_session, const char *partial_value,
char *insert_str, uint32_t insert_size)
{
char longest_match[BCMCLI_MAX_SEARCH_SUBSTR_LENGTH]="";
const bcmcli_cmd_parm *first_match;
int nmatch = _bcmcli_longest_match(mon_session, partial_value, longest_match,
sizeof(longest_match), &first_match);
if (!nmatch)
return;
if (!partial_value || strcmp(partial_value, longest_match) || (nmatch==1))
{
if (nmatch == 1 && first_match->type == BCMCLI_PARM_STRUCT && first_match->max_array_size)
{
_bcmcli_insert(partial_value, longest_match, BCMCLI_ARRAY_START_STR, insert_str, insert_size);
}
else
{
_bcmcli_insert(partial_value, longest_match, (nmatch == 1) ? "=" : "", insert_str, insert_size);
if (nmatch == 1 && first_match->type == BCMCLI_PARM_STRUCT)
bcmolt_strncat(insert_str, BCMCLI_STRUCT_START_STR, insert_size);
}
}
else
{
_bcmcli_help_populated_cmd(mon_session, mon_session->curcmd, partial_value, BCMOS_TRUE);
}
}
static bcmos_bool _bcmcli_is_first_struct_field(bcmcli_session_extras *mon_session)
{
bcmcli_parm_array *pa = _bcmcli_parm_array_cur(mon_session);
return (pa != _bcmcli_parm_array_top(mon_session) && !pa->num_parsed);
}
static bcmos_errno _bcmcli_extend_parms( bcmcli_session_extras *mon_session, bcmcli_name_value *pairs,
int npairs, bcmos_bool last_is_space, char *insert_str, uint32_t insert_size)
{
bcmos_errno rc;
bcmcli_cmd_parm *help_parm = NULL;
bcmcli_parm_array *pa;
int i;
/* Create parameters array */
pa = _bcmcli_parm_array_create(mon_session, NULL, NULL, mon_session->curcmd->u.cmd.parms, pairs, npairs);
if (pa == NULL)
return BCM_ERR_NOMEM;
rc = _bcmcli_populate_parms(mon_session, mon_session->curcmd->name, pa);
pa = _bcmcli_parm_array_cur(mon_session);
if (!pa)
return BCM_ERR_INTERNAL;
if (rc == BCM_ERR_OK)
{
/* If it is unterminated structure and all fields are set, insert terminator */
if ((pa != _bcmcli_parm_array_top(mon_session)) && _bcmcli_parm_array_is_all_set(mon_session, pa))
{
bcmolt_strncat(insert_str, BCMCLI_STRUCT_END_STR, insert_size);
pa = _bcmcli_parm_array_pop(mon_session);
}
/* So far so good */
/* If there is unset mandatory parameter - insert its name.
* Otherwise, display list of unset optionally parameters
*/
/* Find mandatory parameter that is still unassigned */
for (i = 0; i < pa->num_parms; i++)
{
uint32_t flags = pa->cmd_parms[i].flags;
if (!(flags & (BCMCLI_PARM_FLAG_OPTIONAL | BCMCLI_PARM_FLAG_DEFVAL | BCMCLI_PARM_FLAG_ASSIGNED)))
{
help_parm = &pa->cmd_parms[i];
break;
}
}
if (help_parm)
{
/* About to insert the next mandatory parameter.
* Add space before name if it is not the 1st structure field
*/
if (!last_is_space && !_bcmcli_is_first_struct_field(mon_session))
bcmolt_strncat(insert_str, " ", insert_size);
bcmolt_strncat(insert_str, help_parm->name, insert_size);
if (help_parm->type == BCMCLI_PARM_STRUCT)
{
if (help_parm->max_array_size)
bcmolt_strncat(insert_str, BCMCLI_ARRAY_START_STR, insert_size);
else
bcmolt_strncat(insert_str, "=" BCMCLI_STRUCT_START_STR, insert_size);
}
else
{
bcmolt_strncat(insert_str, "=", insert_size);
}
}
else if (!_bcmcli_parm_array_is_all_set(mon_session, pa))
{
if (!last_is_space && !_bcmcli_is_first_struct_field(mon_session))
bcmolt_strncat(insert_str, " ", insert_size);
_bcmcli_help_populated_cmd(mon_session, mon_session->curcmd, NULL, BCMOS_TRUE);
}
}
else
{
/* Parsing failed. See what stopped at */
if ((pa->num_parsed < pa->num_pairs) && (pa->name_value_pairs != NULL))
{
bcmcli_name_value *last_pair;
last_pair = &pa->name_value_pairs[pa->num_parsed];
/* Try to identify by name */
help_parm = _bcmcli_find_named_parm(mon_session, last_pair->name ? last_pair->name : last_pair->value);
if (help_parm)
{
/* Handle arrays */
if (last_pair->index)
{
if (!help_parm->max_array_size)
return BCM_ERR_OK; /* Error message is already printed */
if (! *last_pair->index)
{
_bcmcli_help_parm_brief(mon_session, help_parm);
return BCM_ERR_OK;
}
if ((last_pair->type & BCMCLI_TOKEN_UNTERMINATED_ARRAY_INDEX) != 0)
{
bcmolt_strncat(insert_str, BCMCLI_ARRAY_END_STR, insert_size);
}
if (!last_pair->value && !(last_pair->type & BCMCLI_TOKEN_HAS_EQUAL_SIGN))
{
bcmolt_strncat(insert_str, "=", insert_size);
}
}
else if (help_parm->max_array_size && help_parm->type == BCMCLI_PARM_STRUCT)
{
/* Setting multiple values at once is not supported for structures */
bcmolt_strncat(insert_str, BCMCLI_ARRAY_START_STR, insert_size);
_bcmcli_help_parm_brief(mon_session, help_parm);
return BCM_ERR_OK;
}
else if (!help_parm->max_array_size &&
!last_pair->name &&
!(last_pair->type & BCMCLI_TOKEN_HAS_EQUAL_SIGN))
{
bcmolt_strncat(insert_str, "=", insert_size);
}
/* Looking for values */
_bcmcli_extend_value(mon_session, help_parm, last_pair->value, insert_str, insert_size);
}
else
{
/* Looking for partial name */
_bcmcli_extend_name(mon_session, last_pair->name ? last_pair->name : last_pair->value,
insert_str, insert_size);
}
}
}
return BCM_ERR_OK;
}
/* Identify token in the given directory */
static bcmcli_entry *_bcmcli_search_token1( bcmcli_entry *p_dir, const char **p_name, int name_len )
{
bcmcli_entry *p_token = NULL;
const char *name = *p_name;
bcmcli_token_type type=_bcmcli_analyze_token(name);
/* Name can be qualified */
if ((type & BCMCLI_TOKEN_VALUE) && !strncmp(name, BCMCLI_UP_STR, name_len))
type = BCMCLI_TOKEN_UP;
switch(type & BCMCLI_TOKEN_TYPE_MASK)
{
case BCMCLI_TOKEN_ROOT:
p_token = _bcmcli_root_dir;
*p_name = name + strlen(BCMCLI_ROOT_STR);
break;
case BCMCLI_TOKEN_UP:
if (p_dir->parent)
p_token = p_dir->parent;
else
p_token = p_dir;
*p_name = name + strlen(BCMCLI_UP_STR) + 1;
break;
case BCMCLI_TOKEN_NAME:
case BCMCLI_TOKEN_VALUE:
/* Check alias */
p_token = p_dir->u.dir.first;
while ( p_token )
{
if (p_token->alias &&
(name_len == p_token->alias_len) &&
!_bcmcli_stricmp(p_token->alias, name, p_token->alias_len))
break;
p_token = p_token->next;
}
if (!p_token)
{
bcmcli_entry *partial_match = NULL;
/* Check name */
p_token = p_dir->u.dir.first;
while( p_token )
{
if (!_bcmcli_stricmp(p_token->name, name, name_len))
{
if (name_len == strlen(p_token->name))
break;
if (!partial_match)
partial_match = p_token;
}
p_token = p_token->next;
}
if (!p_token)
p_token = partial_match;
}
*p_name = name + name_len + 1;
break;
default:
break;
}
return p_token;
}
/* Search a token by name in the current directory.
* The name can be qualified (contain path)
*/
static bcmcli_entry *_bcmcli_search_token( bcmcli_entry *p_dir, const char *name )
{
bcmcli_entry *p_token;
const char *name0 = name;
const char *p_slash;
if (!name[0])
return p_dir;
/* Check if name is qualified */
do
{
p_slash = strchr(name, '/');
if (p_slash)
{
if (p_slash == name0)
{
p_dir = p_token = _bcmcli_root_dir;
name = p_slash + 1;
}
else
{
p_token = _bcmcli_search_token1(p_dir, &name, p_slash - name);
if (p_token && (p_token->sel == BCMCLI_ENTRY_DIR))
p_dir = p_token;
}
}
else
{
p_token = _bcmcli_search_token1(p_dir, &name, strlen(name));
}
} while (p_slash && p_token && *name);
return p_token;
}
/* Display help for each entry in the current directory */
static void _bcmcli_help_dir(bcmcli_session_extras *mon_session, bcmcli_entry *p_dir)
{
bcmolt_string *help_string = _bcmcli_help_string_init(mon_session);
bcmcli_entry *p_token;
char buffer[BCMCLI_MAX_QUAL_NAME_LENGTH];
_bcmcli_qualified_name(p_dir, buffer, sizeof(buffer));
bcmolt_string_append(help_string, "Directory %s/ - %s\n", buffer, p_dir->help);
bcmolt_string_append(help_string, "Commands:\n");
p_token = p_dir->u.dir.first;
while (p_token)
{
if (bcmcli_session_access_right(mon_session->session) >= p_token->access_right)
{
if (p_token->sel == BCMCLI_ENTRY_DIR)
bcmolt_string_append(help_string, "\t%s/: %s directory\n", p_token->name, p_token->help );
else
{
char *peol = strchr(p_token->help, '\n');
int help_len = peol ? peol - p_token->help : (int)strlen(p_token->help);
bcmolt_string_append(help_string, "\t%s(%d parms): %.*s\n",
p_token->name, p_token->u.cmd.num_parms, help_len, p_token->help );
}
}
p_token = p_token->next;
}
bcmolt_string_append(help_string, "Type ? <name> for command help, \"/\"-root, \"..\"-upper\n" );
bcmcli_session_print(mon_session->session, "%s", bcmolt_string_get(help_string));
}
/* Display help a token */
static void _bcmcli_help_populated_cmd(bcmcli_session_extras *mon_session, bcmcli_entry *p_token,
const char *partial_match, bcmos_bool suppress_assigned)
{
bcmcli_parm_array *pa = _bcmcli_parm_array_cur(mon_session);
char bra, ket;
uint16_t i;
if (!pa)
return;
if (suppress_assigned)
bcmcli_session_print(mon_session->session, "\n");
for ( i=0; i<pa->num_parms; i++ )
{
bcmcli_cmd_parm *cur_parm = &pa->cmd_parms[i];
if (suppress_assigned && (cur_parm->flags & BCMCLI_PARM_FLAG_ASSIGNED))
continue;
if (partial_match && memcmp(partial_match, cur_parm->name, strlen(partial_match)))
continue;
if ((cur_parm->flags & BCMCLI_PARM_FLAG_OPTIONAL))
{
bra = '[';
ket=']';
}
else
{
bra = '<';
ket='>';
}
bcmcli_session_print(mon_session->session, "\t%c%s(%s)", bra, cur_parm->name, _bcmcli_get_type_name(cur_parm) );
if (cur_parm->max_array_size || cur_parm->type == BCMCLI_PARM_BUFFER)
{
uint32_t num_entries = (cur_parm->type == BCMCLI_PARM_BUFFER) ? cur_parm->value.buffer.len : cur_parm->max_array_size;
bcmcli_session_print(mon_session->session, "[%u]", num_entries);
}
if (cur_parm->type == BCMCLI_PARM_ENUM || cur_parm->type == BCMCLI_PARM_ENUM_MASK)
{
bcmcli_enum_val *values=cur_parm->enum_table;
bcmcli_session_print(mon_session->session, " {");
while (values->name)
{
if (values!=cur_parm->enum_table)
bcmcli_session_print(mon_session->session, ", ");
bcmcli_session_print(mon_session->session, "%s", values->name);
++values;
}
bcmcli_session_print(mon_session->session, "}");
}
if ((cur_parm->flags & BCMCLI_PARM_FLAG_DEFVAL))
{
bcmcli_session_print(mon_session->session, "=");
cur_parm->print_cb(mon_session->session, cur_parm, &cur_parm->value);
}
if ((cur_parm->flags & BCMCLI_PARM_FLAG_RANGE))
{
bcmcli_parm_value low_val = { {.number = cur_parm->low_val} };
bcmcli_parm_value hi_val = { {.number = cur_parm->hi_val} };
bcmcli_session_print(mon_session->session, " [");
cur_parm->print_cb(mon_session->session, cur_parm, &low_val);
bcmcli_session_print(mon_session->session, "..");
cur_parm->print_cb(mon_session->session, cur_parm, &hi_val);
bcmcli_session_print(mon_session->session, "]");
}
bcmcli_session_print(mon_session->session, "%c ", ket);
bcmcli_session_print(mon_session->session, "- %s\n", cur_parm->description);
}
/* Print extra help if command has unresolved selector */
if (pa->num_parms &&
(pa->cmd_parms[pa->num_parms-1].flags & BCMCLI_PARM_FLAG_SELECTOR) &&
!(pa->cmd_parms[pa->num_parms-1].flags & BCMCLI_PARM_FLAG_ASSIGNED))
{
const char *sel_name = pa->cmd_parms[pa->num_parms-1].name;
bcmcli_session_print(mon_session->session, "Add %s=%s_value to see %s-specific parameters\n",
sel_name, sel_name, sel_name);
}
bcmcli_session_print(mon_session->session, "\n");
}
/* Display help a token */
static void _bcmcli_help_entry(bcmcli_session_extras *mon_session, bcmcli_entry *p_token,
bcmcli_name_value *pairs, int npairs)
{
char buffer[BCMCLI_MAX_QUAL_NAME_LENGTH];
bcmcli_parm_array *pa;
if (p_token->sel == BCMCLI_ENTRY_DIR)
{
_bcmcli_help_dir(mon_session, p_token);
return;
}
mon_session->curcmd = p_token;
pa = _bcmcli_parm_array_cur(mon_session);
if (pa == NULL)
{
/* Create parameters array */
pa = _bcmcli_parm_array_create(mon_session, NULL, NULL, p_token->u.cmd.parms, pairs, npairs);
if (pa == NULL)
return;
/* Populate parameter table */
_bcmcli_populate_parms(mon_session, p_token->name, pa);
}
_bcmcli_qualified_name(p_token, buffer, sizeof(buffer));
bcmcli_session_print(mon_session->session, "%s: \t%s\n", buffer, p_token->help );
if (pa->num_parms)
{
if (pa->in_parm)
bcmcli_session_print(mon_session->session, "Structure %s fields:\n", pa->in_parm);
else
bcmcli_session_print(mon_session->session, "Parameters:\n");
_bcmcli_help_populated_cmd(mon_session, p_token, NULL, BCMOS_FALSE);
}
}
/* Choose unique alias for <name> in <p_dir> */
/* Currently only single-character aliases are supported */
static void __bcmcli_chooseAlias(bcmcli_entry *p_dir, bcmcli_entry *p_new_token, int from)
{
bcmcli_entry *p_token;
int i;
char c;
_bcmcli_strlwr( p_new_token->name );
i = from;
while ( p_new_token->name[i] )
{
c = p_new_token->name[i];
p_token = p_dir->u.dir.first;
while ( p_token )
{
if (p_token->alias &&
(tolower( *p_token->alias ) == c) )
break;
if (strlen(p_token->name)<=2 && tolower(p_token->name[0])==c)
break;
p_token = p_token->next;
}
if (p_token)
++i;
else
{
p_new_token->name[i] = toupper( c );
p_new_token->alias = &p_new_token->name[i];
p_new_token->alias_len = 1;
break;
}
}
}
/* isupper wrapper */
static inline int _bcmcli_isupper(char c)
{
return isupper((int)c);
}
static void _bcmcli_choose_alias(bcmcli_entry *p_dir, bcmcli_entry *p_new_token)
{
int i=0;
p_new_token->alias_len = 0;
p_new_token->alias = NULL;
/* Don't try to alias something short */
if (strlen(p_new_token->name) < BCMCLI_MIN_NAME_LENGTH_FOR_ALIAS)
return;
/* Try pre-set alias 1st */
while ( p_new_token->name[i] )
{
if (_bcmcli_isupper(p_new_token->name[i]))
break;
i++;
}
if (p_new_token->name[i])
__bcmcli_chooseAlias(p_dir, p_new_token, i);
if (p_new_token->alias != &p_new_token->name[i])
__bcmcli_chooseAlias(p_dir, p_new_token, 0);
}
/* Convert string s to lower case. Return pointer to s */
static char * _bcmcli_strlwr( char *s )
{
char *s0=s;
while ( *s )
{
*s = tolower( *s );
++s;
}
return s0;
}
/* Compare strings case incensitive */
static int _bcmcli_stricmp(const char *s1, const char *s2, int len)
{
int i;
for ( i=0; (i<len || len<0); i++ )
{
if (tolower( s1[i]) != tolower( s2[i] ))
return 1;
if (!s1[i])
break;
}
return 0;
}
static const char *_bcmcli_get_type_name(const bcmcli_cmd_parm *parm)
{
bcmcli_parm_type type = parm->type;
static const char *type_name[] = {
[BCMCLI_PARM_DECIMAL] = "decimal",
[BCMCLI_PARM_DECIMAL64] = "decimal64",
[BCMCLI_PARM_UDECIMAL] = "udecimal",
[BCMCLI_PARM_UDECIMAL64] = "udecimal64",
[BCMCLI_PARM_HEX] = "hex",
[BCMCLI_PARM_HEX64] = "hex64",
[BCMCLI_PARM_NUMBER] = "number",
[BCMCLI_PARM_NUMBER64] = "number64",
[BCMCLI_PARM_UNUMBER] = "unumber",
[BCMCLI_PARM_UNUMBER64] = "unumber64",
[BCMCLI_PARM_FLOAT] = "float",
[BCMCLI_PARM_DOUBLE] = "double",
[BCMCLI_PARM_ENUM] = "enum",
[BCMCLI_PARM_ENUM_MASK] = "enum_mask",
[BCMCLI_PARM_STRING] = "string",
[BCMCLI_PARM_IP] = "IP",
[BCMCLI_PARM_IPV6] = "IPv6",
[BCMCLI_PARM_MAC] = "MAC",
[BCMCLI_PARM_BUFFER] = "buffer",
[BCMCLI_PARM_STRUCT] = "struct",
[BCMCLI_PARM_USERDEF] = "userdef",
};
static const char *undefined = "undefined";
static const char *selector = "selector";
if (type > BCMCLI_PARM_USERDEF || !type_name[type])
return undefined;
if (type == BCMCLI_PARM_ENUM && (parm->flags & BCMCLI_PARM_FLAG_SELECTOR))
return selector;
return type_name[type];
}
/* Assign default callbacks */
static void _bcmcli_assign_callbacks(bcmcli_cmd_parm *parm)
{
if (parm->type == BCMCLI_PARM_ENUM)
{
parm->scan_cb = _bcmcli_enum_scan_cb;
parm->print_cb = _bcmcli_enum_print_cb;
}
else if (parm->type == BCMCLI_PARM_ENUM_MASK)
{
parm->scan_cb = _bcmcli_enum_mask_scan_cb;
parm->print_cb = _bcmcli_enum_mask_print_cb;
}
else if (parm->type == BCMCLI_PARM_BUFFER)
{
if (!parm->scan_cb)
parm->scan_cb = _bcmcli_buffer_scan_cb;
if (!parm->print_cb)
parm->print_cb = _bcmcli_buffer_print_cb;
}
else if (parm->type == BCMCLI_PARM_STRUCT)
{
parm->scan_cb = _bcmcli_struct_scan_cb;
parm->print_cb = _bcmcli_struct_print_cb;
}
else
{
if (!parm->scan_cb)
parm->scan_cb = _bcmcli_dft_scan_cb;
if (!parm->print_cb)
parm->print_cb = _bcmcli_dft_print_cb;
}
}
/* Convert hex-string to binary data.
* Returns: converted length >=0 or error < 0
*/
static int _bcmcli_strhex(const char *src, uint8_t *dst, uint16_t dst_len)
{
uint16_t src_len = (uint16_t)strlen( src );
uint16_t i = src_len, j, shift = 0;
if ( !dst || !dst_len || (src_len > 2*dst_len) || (src_len%2) )
{
return BCM_ERR_PARM;
}
/* Calculate hex buffer length and fill it up from right-to-left
* in order to start the process from LS nibble
*/
dst_len = src_len / 2;
memset(dst, 0, dst_len);
j = dst_len-1;
do
{
int c = src[--i];
if ( (c>='0') && (c<='9') )
{
c = c - '0';
}
else if ( (c>='a') && (c<='f') )
{
c = 0xA + c - 'a';
}
else if ( (c>='A') && (c<='F') )
{
c = 0xA + c - 'A';
}
else
{
return BCM_ERR_PARM;
}
dst[j] |= (uint8_t)(c<<shift); /* shift can have 1 of 2 values: 0 and 4 */
j -= shift>>2; /* move to the next byte if we've just filled the ms nibble */
shift ^= 4; /* alternate nibbles */
} while ( i );
return dst_len;
}
/* Default function for string->value conversion.
* Returns 0 if OK
*/
static bcmos_errno _bcmcli_dft_scan_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
bcmcli_parm_value *value, const char *string_val)
{
char *p_end = NULL;
int n;
if (parm->type == BCMCLI_PARM_UDECIMAL ||
parm->type == BCMCLI_PARM_UDECIMAL64 ||
parm->type == BCMCLI_PARM_UNUMBER ||
parm->type == BCMCLI_PARM_UNUMBER64)
{
/* strtoul returns OK even when parsing a negative number */
if (string_val[0] == '-')
{
return BCM_ERR_PARM;
}
}
switch(parm->type)
{
case BCMCLI_PARM_DECIMAL:
value->number = strtol(string_val, &p_end, 10);
break;
case BCMCLI_PARM_UDECIMAL:
value->unumber = strtoul(string_val, &p_end, 10);
break;
case BCMCLI_PARM_DECIMAL64:
value->number64 = strtoll(string_val, &p_end, 10);
break;
case BCMCLI_PARM_UDECIMAL64:
value->unumber64 = strtoull(string_val, &p_end, 10);
break;
case BCMCLI_PARM_HEX:
value->unumber = strtoul(string_val, &p_end, 16);
break;
case BCMCLI_PARM_HEX64:
value->unumber64 = strtoull(string_val, &p_end, 16);
break;
case BCMCLI_PARM_NUMBER:
value->number = strtol(string_val, &p_end, 0);
break;
case BCMCLI_PARM_UNUMBER:
value->unumber = strtoul(string_val, &p_end, 0);
break;
case BCMCLI_PARM_NUMBER64:
value->number64 = strtoll(string_val, &p_end, 0);
break;
case BCMCLI_PARM_UNUMBER64:
value->unumber64 = strtoull(string_val, &p_end, 0);
break;
case BCMCLI_PARM_FLOAT:
case BCMCLI_PARM_DOUBLE:
value->d = strtod(string_val, &p_end);
break;
case BCMCLI_PARM_MAC:
{
unsigned m0, m1, m2, m3, m4, m5;
n = sscanf(string_val, "%02x:%02x:%02x:%02x:%02x:%02x",
&m0, &m1, &m2, &m3, &m4, &m5);
if (n != 6)
{
n = sscanf(string_val, "%02x%02x%02x%02x%02x%02x",
&m0, &m1, &m2, &m3, &m4, &m5);
}
if (n != 6)
return BCM_ERR_PARM;
if (m0 > 255 || m1 > 255 || m2 > 255 || m3 > 255 || m4 > 255 || m5 > 255)
return BCM_ERR_PARM;
value->mac.u8[0] = m0;
value->mac.u8[1] = m1;
value->mac.u8[2] = m2;
value->mac.u8[3] = m3;
value->mac.u8[4] = m4;
value->mac.u8[5] = m5;
break;
}
case BCMCLI_PARM_IP:
{
int n1, n2, n3, n4;
n = sscanf(string_val, "%d.%d.%d.%d", &n1, &n2, &n3, &n4);
if (n != 4)
return BCM_ERR_PARM;
if ((unsigned)n1 > 255 || (unsigned)n2 > 255 || (unsigned)n3 > 255 || (unsigned)n4 > 255)
return BCM_ERR_PARM;
value->unumber = (n1 << 24) | (n2 << 16) | (n3 << 8) | n4;
break;
}
case BCMCLI_PARM_IPV6:
{
unsigned a[16];
n = sscanf(string_val, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
&a[0], &a[1], &a[2], &a[3], &a[4], &a[5], &a[6], &a[7],
&a[8], &a[9], &a[10], &a[11], &a[12], &a[13], &a[14], &a[15]);
if (n != 16)
return BCM_ERR_PARM;
for (n = 0; n < 16; n++)
{
if (a[n] > 255)
return BCM_ERR_PARM;
value->ipv6.u8[n] = a[n];
}
break;
}
default:
return BCM_ERR_PARM;
}
if (p_end && *p_end)
return BCM_ERR_PARM;
return BCM_ERR_OK;
}
static void _bcmcli_dft_print_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
const bcmcli_parm_value *value)
{
switch(parm->type)
{
case BCMCLI_PARM_DECIMAL:
bcmcli_print(session, "%ld", value->number);
break;
case BCMCLI_PARM_UDECIMAL:
bcmcli_print(session, "%lu", value->unumber);
break;
case BCMCLI_PARM_DECIMAL64:
bcmcli_print(session, "%lld", value->number64);
break;
case BCMCLI_PARM_UDECIMAL64:
bcmcli_print(session, "%llu", value->unumber64);
break;
case BCMCLI_PARM_HEX:
bcmcli_print(session, "0x%lx", value->unumber);
break;
case BCMCLI_PARM_HEX64:
bcmcli_print(session, "0x%llx", value->unumber64);
break;
case BCMCLI_PARM_NUMBER:
bcmcli_print(session, "%ld", value->number);
break;
case BCMCLI_PARM_NUMBER64:
bcmcli_print(session, "%lld", value->number64);
break;
case BCMCLI_PARM_UNUMBER:
bcmcli_print(session, "%lu", value->unumber);
break;
case BCMCLI_PARM_UNUMBER64:
bcmcli_print(session, "%llu", value->unumber64);
break;
case BCMCLI_PARM_FLOAT:
case BCMCLI_PARM_DOUBLE:
bcmcli_print(session, "%f", value->d);
break;
case BCMCLI_PARM_STRING:
bcmcli_print(session, "%s", value->string);
break;
case BCMCLI_PARM_MAC:
bcmcli_print(session, "%02x:%02x:%02x:%02x:%02x:%02x",
value->mac.u8[0], value->mac.u8[1], value->mac.u8[2],
value->mac.u8[3], value->mac.u8[4], value->mac.u8[5]);
break;
case BCMCLI_PARM_IP:
bcmcli_print(session, "%d.%d.%d.%d",
(int)((value->unumber >> 24) & 0xff), (int)((value->unumber >> 16) & 0xff),
(int)((value->unumber >> 8) & 0xff), (int)(value->unumber & 0xff));
break;
case BCMCLI_PARM_IPV6:
bcmcli_print(session, "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
value->ipv6.u8[0], value->ipv6.u8[1], value->ipv6.u8[2], value->ipv6.u8[3],
value->ipv6.u8[4], value->ipv6.u8[5], value->ipv6.u8[6], value->ipv6.u8[7],
value->ipv6.u8[8], value->ipv6.u8[9], value->ipv6.u8[10], value->ipv6.u8[11],
value->ipv6.u8[12], value->ipv6.u8[13], value->ipv6.u8[14], value->ipv6.u8[15]);
break;
default:
bcmcli_print(session, "*unknown*");
}
}
static bcmos_errno _bcmcli_enum_scan_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
bcmcli_parm_value *value, const char *string_val)
{
bcmcli_enum_val *values=parm->enum_table;
while (values->name)
{
if (!_bcmcli_stricmp(values->name, string_val, -1))
{
value->enum_val = values->val;
return BCM_ERR_OK;
}
++values;
}
return BCM_ERR_PARM;
}
static void _bcmcli_enum_print_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
const bcmcli_parm_value *value)
{
bcmcli_enum_val *values=parm->enum_table;
while (values->name)
{
if (values->val == value->enum_val)
break;
++values;
}
if (values->name)
bcmcli_print(session, "%s", values->name);
else
bcmcli_print(session, "*invalid*");
}
static bcmos_errno _bcmcli_enum_mask_scan_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
bcmcli_parm_value *value, const char *string_val)
{
bcmcli_parm_value val1;
char *del;
bcmos_errno err;
value->number = 0;
/* string_val is a combination of enum values separated by BCMCLI_ENUM_MASK_DEL_STR */
del = strchr(string_val, BCMCLI_ENUM_MASK_DEL_CHAR);
while (del)
{
char single_val[64];
if (del - string_val >= sizeof(single_val))
return BCM_ERR_OVERFLOW;
memcpy(single_val, string_val, del - string_val);
single_val[del - string_val] = 0;
err = _bcmcli_enum_scan_cb(session, parm, &val1, single_val);
if (err)
return err;
value->enum_val |= val1.enum_val;
string_val = del+1;
del = strchr(string_val, BCMCLI_ENUM_MASK_DEL_CHAR);
}
err = _bcmcli_enum_scan_cb(session, parm, &val1, string_val);
if (err)
return err;
value->number |= val1.enum_val;
return BCM_ERR_OK;
}
static void _bcmcli_enum_mask_print_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
const bcmcli_parm_value *value)
{
bcmcli_enum_val *values=parm->enum_table;
const char *none = NULL;
int nprinted = 0;
while (values->name)
{
if (values->val == 0)
{
none = values->name;
}
if ((values->val & value->enum_val) != 0)
{
if (values != parm->enum_table)
bcmcli_print(session, BCMCLI_ENUM_MASK_DEL_STR);
bcmcli_print(session, "%s", values->name);
++nprinted;
}
++values;
}
if (! nprinted)
bcmcli_print(session, "%s", NULL != none ? none : "0");
}
static bcmos_errno _bcmcli_buffer_scan_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
bcmcli_parm_value *value, const char *string_val)
{
int n;
if (!value->buffer.start)
return BCM_ERR_PARM;
/* coverity[misra_violation] - cross-assignment under union is OK - they're both in the same union member */
value->buffer.curr = value->buffer.start;
if (strcmp(string_val, BCMCLI_NO_VALUE_STR) == 0)
{
return BCM_ERR_OK;
}
n = _bcmcli_strhex(string_val, value->buffer.start, value->buffer.len);
if (n < 0)
return BCM_ERR_PARSE;
if (!bcmolt_buf_skip(&value->buffer, n))
return BCM_ERR_PARM;
return BCM_ERR_OK;
}
static void _bcmcli_buffer_print_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
const bcmcli_parm_value *value)
{
if (value->buffer.len == 0)
{
bcmcli_print(session, BCMCLI_NO_VALUE_STR);
}
else
{
uint32_t length = bcmolt_buf_get_used(&value->buffer);
int i;
for (i = 0; i < length; i++)
{
bcmcli_print(session, "%02x", value->buffer.start[i]);
}
}
}
/* Handle value containing a list of space-delimited struct field values surrounded by braces */
static bcmos_errno _bcmcli_struct_scan_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
bcmcli_parm_value *value, const char *string_val)
{
bcmcli_session_extras *mon_session = _bcmcli_session_data(session);
bcmcli_token_type struct_token_type = mon_session->cur_token_type;
const char *p_val = string_val;
int p_val_len = strlen(p_val);
bcmcli_name_value *pairs = NULL;
int npairs = 0;
bcmcli_parm_array *pa;
bcmos_errno rc;
/* make sure the value is surrounded by braces (the end brace is optional in case of tab completion) */
if (p_val_len == 0 || p_val[0] != BCMCLI_STRUCT_START_CHAR)
return BCM_ERR_PARM;
/* extract the space-delimited set of field_name=field_value pairs inside the braces */
p_val_len -= (p_val[p_val_len - 1] == BCMCLI_STRUCT_END_CHAR) ? 2 : 1;
p_val++;
rc = _bcmcli_split(mon_session, &p_val, p_val_len, &pairs, &npairs);
if (rc != BCM_ERR_OK)
return rc;
/* Create parameters array */
pa = _bcmcli_parm_array_create(mon_session, parm->name, value, value->fields, pairs, npairs);
if (pa == NULL)
return BCM_ERR_NOMEM;
rc = _bcmcli_populate_parms(mon_session, parm->name, pa);
/* Pop parameter arrays stack if parsing was succesful and struct descriptor properly terminated */
if (rc == BCM_ERR_OK && (struct_token_type & BCMCLI_TOKEN_UNTERMINATED_STRUCT_VALUE) == 0)
_bcmcli_parm_array_pop(mon_session);
return rc;
}
static void _bcmcli_struct_print_cb(bcmcli_session *session, const bcmcli_cmd_parm *parm,
const bcmcli_parm_value *value)
{
const bcmcli_cmd_parm *field;
bcmos_bool first = BCMOS_TRUE;
bcmcli_print(session, "%c", BCMCLI_STRUCT_START_CHAR);
for (field = value->fields; field && field->name; ++field)
{
if (!bcmcli_parm_is_set(session, field))
continue;
if (!first)
bcmcli_print(session, " ");
bcmcli_parm_print(session, field);
first = BCMOS_FALSE;
}
bcmcli_print(session, "%c", BCMCLI_STRUCT_END_CHAR);
}
static const char *_bcmcli_qualified_name(bcmcli_entry *token, char *buffer, int size )
{
bcmcli_entry *parent = token->parent;
char qual_name[BCMCLI_MAX_QUAL_NAME_LENGTH];
*buffer=0;
while (parent)
{
bcmolt_strncpy(qual_name, parent->name, sizeof(qual_name));
if (parent->parent)
bcmolt_strncat(qual_name, "/", sizeof(qual_name));
bcmolt_strncat(qual_name, buffer, sizeof(qual_name));
bcmolt_strncpy(buffer, qual_name, size);
parent = parent->parent;
}
size -= strlen(buffer);
bcmolt_strncat(buffer, token->name, size);
return buffer;
}
/*
* Command parameter array stack manipulation
*/
/* Create command parameters array the template specified at
* CLI command registration time
*/
static bcmcli_parm_array *_bcmcli_parm_array_create(bcmcli_session_extras *mon_session,
const char *in_parm, bcmcli_parm_value *in_value, const bcmcli_cmd_parm parms[],
bcmcli_name_value pairs[], int npairs)
{
bcmcli_parm_array *pa;
pa = bcmcli_session_stack_calloc(mon_session->session, sizeof(bcmcli_parm_array));
if (!pa)
return NULL;
pa->in_value = in_value;
pa->in_parm = in_parm;
if (_bcmcli_parm_array_extend(mon_session, pa, 0, parms) != BCM_ERR_OK)
return NULL;
pa->name_value_pairs = pairs;
pa->num_pairs = npairs;
_bcmcli_parm_array_push(mon_session, pa);
return pa;
}
/* Extend command parameters array.
* This function is used when processing command selector.
* Additional parameters based on the selector value are inserted into the existing
* array in position "pos"
*/
static bcmos_errno _bcmcli_parm_array_extend(bcmcli_session_extras *mon_session,
bcmcli_parm_array *pa, uint32_t pos, const bcmcli_cmd_parm extra_parms[])
{
uint32_t num_parms;
bcmcli_cmd_parm *parms;
uint32_t num_extra_parms;
int i;
/* Calculate number of parameters */
if (!extra_parms)
return BCM_ERR_OK;
/* Count extra parameters */
for (i = 0; extra_parms[i].name != NULL; i++)
;
num_extra_parms = i;
if (!num_extra_parms)
return BCM_ERR_OK;
/* Allocate new block for extended array. The old block will be released eventually
* when session memory pool is restored
*/
num_parms = pa->num_parms + num_extra_parms;
parms = bcmcli_session_stack_calloc(mon_session->session, (num_parms + 1) * sizeof(bcmcli_cmd_parm));
if (!parms)
return BCM_ERR_NOMEM;
/* Copy parameters before the insertion point */
if (pos)
{
memcpy(parms, pa->cmd_parms, pos * sizeof(bcmcli_cmd_parm));
}
/* Copy additional parameters */
for (i = 0; i < num_extra_parms; i++)
{
bcmcli_parm_value *values;
bcmcli_cmd_parm *p = &parms[pos+i];
*p = extra_parms[i];
_bcmcli_assign_callbacks(p);
/* Copy "values" array for arrays */
if (p->max_array_size)
{
if (!p->values)
{
bcmcli_print(mon_session->session, "MON %s> \"values\" is not set in array parameter %s\n",
mon_session->curcmd->name, p->name);
return BCM_ERR_INTERNAL;
}
values = bcmcli_session_stack_calloc(mon_session->session, p->max_array_size * sizeof(bcmcli_parm_value));
if (!values)
return BCM_ERR_NOMEM;
memcpy(values, p->values, p->max_array_size * sizeof(bcmcli_parm_value));
p->values = values;
}
}
/* Copy parameters after insertion point */
if (pos < pa->num_parms)
{
memcpy(parms + pos + num_extra_parms, pa->cmd_parms + pos,
(pa->num_parms - pos) * sizeof(bcmcli_cmd_parm));
}
/* Assign new block */
pa->cmd_parms = parms;
pa->num_parms += num_extra_parms;
if (pa->in_value)
pa->in_value->fields = parms;
return BCM_ERR_OK;
}
static void _bcmcli_parm_array_push(bcmcli_session_extras *mon_session, bcmcli_parm_array *pa)
{
STAILQ_INSERT_HEAD(&mon_session->cmd_parms_stack, pa, next);
}
static bcmcli_parm_array *_bcmcli_parm_array_pop(bcmcli_session_extras *mon_session)
{
STAILQ_REMOVE_HEAD(&mon_session->cmd_parms_stack, next);
return STAILQ_FIRST(&mon_session->cmd_parms_stack);
}
/* Top-most array. Top-level CLI parameters */
static bcmcli_parm_array *_bcmcli_parm_array_top(bcmcli_session_extras *mon_session)
{
return STAILQ_LAST(&mon_session->cmd_parms_stack, bcmcli_parm_array, next);
}
/* Current (inner-most) CLI parameters */
static bcmcli_parm_array *_bcmcli_parm_array_cur(bcmcli_session_extras *mon_session)
{
return STAILQ_FIRST(&mon_session->cmd_parms_stack);
}
/* Return TRUE if all parameters in parm array are set */
static bcmos_bool _bcmcli_parm_array_is_all_set(bcmcli_session_extras *mon_session, bcmcli_parm_array *pa)
{
bcmos_bool all_set = BCMOS_TRUE;
int i;
if (!pa->cmd_parms)
return BCMOS_TRUE;
for (i = 0; i < pa->num_parms && all_set; i++)
all_set = bcmcli_parm_is_set(mon_session->session, &pa->cmd_parms[i]);
return all_set;
}
/*
* Exports
*/
EXPORT_SYMBOL(bcmcli_dir_add);
EXPORT_SYMBOL(bcmcli_dir_find);
EXPORT_SYMBOL(bcmcli_token_name);
EXPORT_SYMBOL(bcmcli_cmd_add);
EXPORT_SYMBOL(bcmcli_session_open);
EXPORT_SYMBOL(bcmcli_session_close);
EXPORT_SYMBOL(bcmcli_parse);
EXPORT_SYMBOL(bcmcli_stop);
EXPORT_SYMBOL(bcmcli_is_stopped);
EXPORT_SYMBOL(bcmcli_dir_get);
EXPORT_SYMBOL(bcmcli_dir_set);
EXPORT_SYMBOL(bcmcli_parm_number);
EXPORT_SYMBOL(bcmcli_parm_is_set);
EXPORT_SYMBOL(bcmcli_enum_parm_stringval);
EXPORT_SYMBOL(bcmcli_token_destroy);
EXPORT_SYMBOL(bcmcli_enum_bool_table);
<file_sep>/*
* <:copyright-BRCM:2016-2020:Apache:standard
*
* Copyright (c) 2016-2020 Broadcom. All Rights Reserved
*
* The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* :>
*
*****************************************************************************/
/*
* bbf-xpon.c
*/
#include <bcmos_system.h>
#include <bcmolt_netconf_module_utils.h>
#include <bbf-xpon.h>
#define BBF_XPON_MODULE_NAME "bbf-xpon"
#define BBF_XPONVANI_MODULE_NAME "bbf-xponvani"
#define BBF_XPON_IFTYPE_MODULE_NAME "bbf-xpon-if-type"
#define BBF_XPONGEMTCONT_MODULE_NAME "bbf-xpongemtcont"
#define BBF_L2_FORWARDING_MODULE_NAME "bbf-l2-forwarding"
#define IETF_HARDWARE_MODULE_NAME "ietf-hardware"
#define BBF_HARDWARE_TYPES_MODULE_NAME "bbf-hardware-types"
#ifdef TR385_ISSUE2
#define BBF_XPON_ONU_STATES_MODULE_NAME "bbf-xpon-onu-state"
#else
#define BBF_XPON_ONU_STATES_MODULE_NAME "bbf-xpon-onu-states"
#endif
#define BBF_QOS_CLASSIFIERS_MODULE_NAME "bbf-qos-classifiers"
#define BBF_QOS_POLICIES_MODULE_NAME "bbf-qos-policies"
#define BBF_LINK_TABLE_MODULE_NAME "bbf-link-table"
#define IETF_INTERFACES_MODULE_NAME "ietf-interfaces"
#define BBF_XPON_INTERFACE_PATH_BASE "/ietf-interfaces:interfaces/interface"
#define BBF_XPON_INTERFACE_STATE_PATH_BASE "/ietf-interfaces:interfaces-state/interface"
#define BCM_SR_MODULE_CHANGE_SUBSCR_FLAGS SR_SUBSCR_ENABLED | SR_SUBSCR_CTX_REUSE
sr_subscription_ctx_t *sr_ctx;
static const char* ietf_interfaces_features[] = {
"*",
NULL
};
static const char* xponvani_features[] = {
"configurable-v-ani-onu-id",
NULL
};
static const char* xpongemtcont_features[] = {
"configurable-gemport-id",
"configurable-alloc-id",
NULL
};
static const char* l2_forwarding_features[] = {
"forwarding-databases",
"shared-forwarding-databases",
"mac-learning",
"split-horizon-profiles",
NULL
};
static const char* ietf_hardware_features[] = {
"*",
NULL
};
#define XPON_MAX_NAME_LENGTH 64
#define XPON_MAX_XPATH_LENGTH 256
typedef struct xpon_channel_termination xpon_channel_termination;
struct xpon_channel_termination
{
char name[XPON_MAX_NAME_LENGTH];
STAILQ_ENTRY(xpon_channel_termination) next;
};
static STAILQ_HEAD(, xpon_channel_termination) channel_termination_list;
/* Find interface by name */
static xpon_channel_termination *bbf_xpon_channel_termination_get(const char *name)
{
xpon_channel_termination *ct, *ct_tmp;
STAILQ_FOREACH_SAFE(ct, &channel_termination_list, next, ct_tmp)
{
if (!strcmp(ct->name, name))
break;
}
return ct;
}
/* Add channel-termination if doesn't exist */
static bcmos_errno bbf_xpon_channel_termination_add(const char *name)
{
xpon_channel_termination *ct = bbf_xpon_channel_termination_get(name);
if (ct == NULL)
{
ct = bcmos_calloc(sizeof(xpon_channel_termination));
if (ct == NULL)
return BCM_ERR_NOMEM;
strncpy(ct->name, name, sizeof(ct->name) - 1);
STAILQ_INSERT_TAIL(&channel_termination_list, ct, next);
NC_LOG_INFO("channel-termination '%s' added\n", ct->name);
}
return BCM_ERR_OK;
}
/* Delete channel-termination if exists */
static bcmos_errno bbf_xpon_channel_termination_delete(const char *name)
{
xpon_channel_termination *ct = bbf_xpon_channel_termination_get(name);
if (ct != NULL)
{
NC_LOG_INFO("channel-termination '%s' deleted\n", ct->name);
STAILQ_REMOVE_SAFE(&channel_termination_list, ct, xpon_channel_termination, next);
bcmos_free(ct);
}
return BCM_ERR_OK;
}
/* Data store change indication callback */
static int bbf_xpon_change_cb(sr_session_ctx_t *srs, const char *module_name,
const char *xpath, sr_event_t event, uint32_t request_id, void *private_ctx)
{
sr_change_iter_t *sr_iter = NULL;
sr_change_oper_t sr_oper;
sr_val_t *sr_old_val = NULL, *sr_new_val = NULL;
char qualified_xpath[XPON_MAX_XPATH_LENGTH];
char keyname[XPON_MAX_NAME_LENGTH];
int sr_rc;
bcmos_errno err = BCM_ERR_OK;
NC_LOG_INFO("xpath=%s event=%d\n", xpath, event);
/* We only handle CHANGE and ABORT events.
* Since there is no way to reserve resources in advance and no way to fail the APPLY event,
* configuration is applied in VERIFY event.
* There are no other verifiers, but if there are and they fail,
* ABORT event will roll-back the changes.
*/
if (event == SR_EV_DONE)
return SR_ERR_OK;
snprintf(qualified_xpath, sizeof(qualified_xpath)-1, "%s//.", xpath);
qualified_xpath[sizeof(qualified_xpath)-1] = 0;
for (sr_rc = sr_get_changes_iter(srs, qualified_xpath, &sr_iter);
(err == BCM_ERR_OK) && (sr_rc == SR_ERR_OK) &&
(sr_rc = sr_get_change_next(srs, sr_iter, &sr_oper, &sr_old_val, &sr_new_val)) == SR_ERR_OK;
nc_sr_free_value_pair(&sr_old_val, &sr_new_val))
{
const char *iter_xpath;
sr_val_t *sr_val;
NC_LOG_DBG("old_val=%s new_val=%s. Leaf type %d\n",
sr_old_val ? sr_old_val->xpath : "none",
sr_new_val ? sr_new_val->xpath : "none",
sr_old_val ? sr_old_val->type : sr_new_val->type);
if ((sr_old_val && ((sr_old_val->type == SR_LIST_T) && (sr_oper != SR_OP_MOVED))) ||
(sr_new_val && ((sr_new_val->type == SR_LIST_T) && (sr_oper != SR_OP_MOVED))) ||
(sr_old_val && (sr_old_val->type == SR_CONTAINER_T)) ||
(sr_new_val && (sr_new_val->type == SR_CONTAINER_T)))
{
/* no semantic meaning */
continue;
}
sr_val = sr_new_val ? sr_new_val : sr_old_val;
iter_xpath = sr_val->xpath;
if (strstr(iter_xpath, "channel-termination/") == NULL)
continue;
/* Channel termination: add/remove */
*keyname = 0;
if (nc_xpath_key_get(iter_xpath, "name", keyname, sizeof(keyname)) != BCM_ERR_OK ||
! *keyname)
{
continue;
}
if (sr_new_val != NULL)
bbf_xpon_channel_termination_add(keyname);
else
bbf_xpon_channel_termination_delete(keyname);
}
nc_sr_free_value_pair(&sr_old_val, &sr_new_val);
sr_free_change_iter(sr_iter);
return SR_ERR_OK;
}
static int xpon_channel_termination_oper_populate(
sr_session_ctx_t *session,
const char *xpath,
struct lyd_node **parent,
xpon_channel_termination *ct)
{
const struct ly_ctx *ctx = sr_get_context(sr_session_get_connection(session));
*parent = nc_ly_sub_value_add(ctx, *parent, xpath, "admin-status", "up");
*parent = nc_ly_sub_value_add(ctx, *parent, xpath, "oper-status", "up");
*parent = nc_ly_sub_value_add(ctx, *parent, xpath,
"bbf-xpon:channel-termination/pon-id-display", "0");
*parent = nc_ly_sub_value_add(ctx, *parent, xpath,
"bbf-xpon:channel-termination/location", "bbf-xpon-types:inside-olt");
return SR_ERR_OK;
}
static int xpon_interface_state_get_cb(sr_session_ctx_t *session, const char *module_name,
const char *xpath, const char *request_path, uint32_t request_id,
struct lyd_node **parent, void *private_data)
{
int sr_rc = SR_ERR_OK;
xpon_channel_termination *ct = NULL;
NC_LOG_INFO("module=%s xpath=%s request=%s\n", module_name, xpath, request_path);
if (strcmp(module_name, IETF_INTERFACES_MODULE_NAME))
return SR_ERR_OK;
if ((xpath != NULL && strchr(xpath, '[') != NULL) ||
(request_path != NULL && strchr(request_path, '[') != NULL))
{
/* Get specific interface */
char keyname[XPON_MAX_NAME_LENGTH]="";
if (xpath != NULL && strchr(xpath, '[') != NULL)
{
nc_xpath_key_get(xpath, "name", keyname, sizeof(keyname));
}
else
{
nc_xpath_key_get(request_path, "name", keyname, sizeof(keyname));
}
if (*keyname)
{
ct = bbf_xpon_channel_termination_get(keyname);
if (ct != NULL)
xpon_channel_termination_oper_populate(session, xpath, parent, ct);
}
}
else
{
/* All interfaces */
xpon_channel_termination *ct_tmp;
char full_xpath[XPON_MAX_XPATH_LENGTH];
STAILQ_FOREACH_SAFE(ct, &channel_termination_list, next, ct_tmp)
{
snprintf(full_xpath, sizeof(full_xpath)-1, "%s[name='%s']", xpath, ct->name);
xpon_channel_termination_oper_populate(session, full_xpath, parent, ct);
}
}
return sr_rc;
}
/* Subscribe to configuration change events */
static bcmos_errno bbf_xpon_subscribe(sr_session_ctx_t *srs)
{
int sr_rc;
/* subscribe to events */
sr_rc = sr_module_change_subscribe(srs, IETF_INTERFACES_MODULE_NAME, BBF_XPON_INTERFACE_PATH_BASE,
bbf_xpon_change_cb, NULL, 0, BCM_SR_MODULE_CHANGE_SUBSCR_FLAGS,
&sr_ctx);
if (SR_ERR_OK == sr_rc)
{
NC_LOG_INFO("Subscribed to %s subtree changes.\n", BBF_XPON_INTERFACE_PATH_BASE);
}
else
{
NC_LOG_ERR("Failed to subscribe to %s subtree changes (%s).\n",
BBF_XPON_INTERFACE_PATH_BASE, sr_strerror(sr_rc));
}
/* Subscribe for operational data retrieval */
sr_rc = sr_oper_get_items_subscribe(srs, IETF_INTERFACES_MODULE_NAME, BBF_XPON_INTERFACE_STATE_PATH_BASE,
xpon_interface_state_get_cb, NULL, SR_SUBSCR_CTX_REUSE, &sr_ctx);
if (SR_ERR_OK != sr_rc) {
NC_LOG_ERR("Failed to subscribe to %s subtree operation data retrieval (%s).",
BBF_XPON_INTERFACE_STATE_PATH_BASE, sr_strerror(sr_rc));
}
return (sr_rc == SR_ERR_OK) ? BCM_ERR_OK : BCM_ERR_INTERNAL;
}
bcmos_errno bbf_xpon_module_init(sr_session_ctx_t *srs, struct ly_ctx *ly_ctx)
{
bcmos_errno err = BCM_ERR_INTERNAL;
const struct lys_module *ietf_intf_mod;
const struct lys_module *xponvani_mod;
const struct lys_module *xpongemtcont_mod;
const struct lys_module *l2_forwarding_mod;
const struct lys_module *ietf_hardware_mod;
const struct lys_module *bbf_hardware_types_mod;
const struct lys_module *onu_states_mod;
int i;
STAILQ_INIT(&channel_termination_list);
do {
/* make sure that ietf-interfaces module is loaded */
ietf_intf_mod = ly_ctx_get_module(ly_ctx, IETF_INTERFACES_MODULE_NAME, NULL, 1);
if (ietf_intf_mod == NULL)
{
ietf_intf_mod = ly_ctx_load_module(ly_ctx, IETF_INTERFACES_MODULE_NAME, NULL);
if (ietf_intf_mod == NULL)
{
NC_LOG_ERR(IETF_INTERFACES_MODULE_NAME ": can't find the schema in sysrepo\n");
break;
}
}
/* make sure that bbf-xponvani module is loaded */
xponvani_mod = ly_ctx_get_module(ly_ctx, BBF_XPONVANI_MODULE_NAME, NULL, 1);
if (xponvani_mod == NULL)
{
xponvani_mod = ly_ctx_load_module(ly_ctx, BBF_XPONVANI_MODULE_NAME, NULL);
if (xponvani_mod == NULL)
{
NC_LOG_ERR(BBF_XPONVANI_MODULE_NAME ": can't find the schema in sysrepo\n");
break;
}
}
/* make sure that bbf-xpongemtcont module is loaded */
xpongemtcont_mod = ly_ctx_get_module(ly_ctx, BBF_XPONGEMTCONT_MODULE_NAME, NULL, 1);
if (xpongemtcont_mod == NULL)
{
xpongemtcont_mod = ly_ctx_load_module(ly_ctx, BBF_XPONGEMTCONT_MODULE_NAME, NULL);
if (xpongemtcont_mod == NULL)
{
NC_LOG_ERR(BBF_XPONGEMTCONT_MODULE_NAME ": can't find the schema in sysrepo\n");
break;
}
}
/* make sure that bbf-xpongemtcont module is loaded */
l2_forwarding_mod = ly_ctx_get_module(ly_ctx, BBF_L2_FORWARDING_MODULE_NAME, NULL, 1);
if (l2_forwarding_mod == NULL)
{
l2_forwarding_mod = ly_ctx_load_module(ly_ctx, BBF_L2_FORWARDING_MODULE_NAME, NULL);
if (l2_forwarding_mod == NULL)
{
NC_LOG_ERR(BBF_L2_FORWARDING_MODULE_NAME ": can't find the schema in sysrepo\n");
break;
}
}
/* make sure that ietf-hardware module is loaded */
ietf_hardware_mod = ly_ctx_get_module(ly_ctx, IETF_HARDWARE_MODULE_NAME, NULL, 1);
if (ietf_hardware_mod == NULL)
{
ietf_hardware_mod = ly_ctx_load_module(ly_ctx, IETF_HARDWARE_MODULE_NAME, NULL);
if (ietf_hardware_mod == NULL)
{
NC_LOG_ERR(IETF_HARDWARE_MODULE_NAME ": can't find the schema in sysrepo\n");
break;
}
}
/* make sure that bbf-hardware-types module is loaded */
bbf_hardware_types_mod = ly_ctx_get_module(ly_ctx, BBF_HARDWARE_TYPES_MODULE_NAME, NULL, 1);
if (bbf_hardware_types_mod == NULL)
{
bbf_hardware_types_mod = ly_ctx_load_module(ly_ctx, BBF_HARDWARE_TYPES_MODULE_NAME, NULL);
if (bbf_hardware_types_mod == NULL)
{
NC_LOG_ERR(BBF_HARDWARE_TYPES_MODULE_NAME ": can't find the schema in sysrepo\n");
break;
}
}
/* make sure that bbf-xpon-onu-states module is loaded */
onu_states_mod = ly_ctx_get_module(ly_ctx, BBF_XPON_ONU_STATES_MODULE_NAME, NULL, 1);
if (onu_states_mod == NULL)
{
onu_states_mod = ly_ctx_load_module(ly_ctx, BBF_XPON_ONU_STATES_MODULE_NAME, NULL);
if (onu_states_mod == NULL)
{
NC_LOG_ERR(BBF_XPON_ONU_STATES_MODULE_NAME ": can't find the schema in sysrepo\n");
break;
}
}
/* Enable all relevant features are enabled in sysrepo */
for (i = 0; ietf_interfaces_features[i]; i++)
{
if (lys_features_enable(ietf_intf_mod, ietf_interfaces_features[i]))
{
NC_LOG_ERR("%s: can't enable feature %s\n", IETF_INTERFACES_MODULE_NAME, ietf_interfaces_features[i]);
break;
}
}
if (ietf_interfaces_features[i])
break;
for (i = 0; xponvani_features[i]; i++)
{
if (lys_features_enable(xponvani_mod, xponvani_features[i]))
{
NC_LOG_ERR("%s: can't enable feature %s\n", BBF_XPONVANI_MODULE_NAME, xponvani_features[i]);
break;
}
}
if (xponvani_features[i])
break;
for (i = 0; xpongemtcont_features[i]; i++)
{
if (lys_features_enable(xpongemtcont_mod, xpongemtcont_features[i]))
{
NC_LOG_ERR("%s: can't enable feature %s\n", BBF_XPONGEMTCONT_MODULE_NAME, xpongemtcont_features[i]);
break;
}
}
if (xpongemtcont_features[i])
break;
for (i = 0; l2_forwarding_features[i]; i++)
{
if (lys_features_enable(l2_forwarding_mod, l2_forwarding_features[i]))
{
NC_LOG_ERR("%s: can't enable feature %s\n", BBF_L2_FORWARDING_MODULE_NAME, l2_forwarding_features[i]);
break;
}
}
if (l2_forwarding_features[i])
break;
for (i = 0; ietf_hardware_features[i]; i++)
{
if (lys_features_enable(ietf_hardware_mod, ietf_hardware_features[i]))
{
NC_LOG_ERR("%s: can't enable feature %s\n", IETF_HARDWARE_MODULE_NAME, ietf_hardware_features[i]);
break;
}
}
if (ietf_hardware_features[i])
break;
err = bbf_xpon_subscribe(srs);
} while (0);
return err;
}
bcmos_errno bbf_xpon_module_start(sr_session_ctx_t *srs, struct ly_ctx *ly_ctx)
{
return BCM_ERR_OK;
}
void bbf_xpon_module_exit(sr_session_ctx_t *srs, struct ly_ctx *ly_ctx)
{
}
bcmos_bool xpon_cterm_is_onu_state_notifiable(const char *cterm_name, const char *state)
{
return BCMOS_TRUE;
}
<file_sep># yang models
#
include(third_party)
set(YANG_MODEL_PACKAGE_VERSION "2.0")
# Netopeer2 consists from multiple components
# Umbrella module
bcm_3rdparty_module_name(yang-models ${YANG_MODEL_PACKAGE_VERSION})
bcm_3rdparty_add_dependencies(sysrepo)
if(BCM_CONFIG_HOST MATCHES "x86")
set(_SYSREPOCTL ${CMAKE_BINARY_DIR}/fs/bin/sysrepoctl)
else()
set(_SYSREPOCTL ${CMAKE_BINARY_DIR}/../host-sim/fs/bin/sysrepoctl)
endif()
set(_SYSREPOTOOL_WRAPPER ${CMAKE_BINARY_DIR}/fs/bin/sysrepotool.sh)
if(SYSREPO_SHM_PREFIX AND NOT "${SYSREPO_SHM_PREFIX}" STREQUAL "none")
set(ENV{SYSREPO_SHM_PREFIX} ${SYSREPO_SHM_PREFIX})
endif()
bcm_make_normal_option(USE_OBBAA_YANG_MODELS bool "Use models from OB-BAA bundle" y)
bcm_make_normal_option(OBBAA_DEVICE_ADAPTER_VERSION string "OB-BAA device adapter vesrion: 1.0 or 2.0" "1.0")
unset(_DIRS)
if (USE_OBBAA_YANG_MODELS)
if(NOT ("${OBBAA_DEVICE_ADAPTER_VERSION}" STREQUAL "1.0") AND NOT ("${OBBAA_DEVICE_ADAPTER_VERSION}" STREQUAL "2.0"))
message(FATAL_ERROR "OBBAA_DEVICE_ADAPTER_VERSION '${OBBAA_DEVICE_ADAPTER_VERSION}' is invalid. Must be 1.0 or 2.0")
endif()
if("${OBBAA_DEVICE_ADAPTER_VERSION}" STREQUAL "1.0")
set(TR385_ISSUE2 n CACHE BOOL "TR-385 Issue 2" FORCE)
else()
set(TR385_ISSUE2 y CACHE BOOL "TR-385 Issue 2" FORCE)
endif()
set(_OB_BAA_MODEL_DIR ${CMAKE_CURRENT_SOURCE_DIR}/OB-BAA-standard-olt-adapter/${OBBAA_DEVICE_ADAPTER_VERSION}/yang)
list(APPEND _DIRS ${_OB_BAA_MODEL_DIR})
set(_TR_385_EQUIPMENT_DIR ${_OB_BAA_MODEL_DIR})
set(_TR_385_INTERFACE_DIR ${_OB_BAA_MODEL_DIR})
else()
set(_TR_385_VERSION issue2 CACHE STRING "TR-385 standard version")
file(GLOB_RECURSE _DIRS_AND_FILES LIST_DIRECTORIES true ${CMAKE_CURRENT_SOURCE_DIR}/*)
foreach(_DIR ${_DIRS_AND_FILES})
if(IS_DIRECTORY ${_DIR} AND NOT "${_DIR}" MATCHES "${CMAKE_CURRENT_SOURCE_DIR}/OB-BAA-standard-olt-adapter.*")
list(APPEND _DIRS ${_DIR})
endif()
endforeach(_DIR)
set(_TR_385_DIR ${CMAKE_CURRENT_SOURCE_DIR}/BBF/TR-385/${_TR_385_VERSION}/standard)
set(_TR_385_COMMON_DIR ${_TR_385_DIR}/common)
set(_TR_385_EQUIPMENT_DIR ${_TR_385_DIR}/equipment)
set(_TR_385_NETWORKING_DIR ${_TR_385_DIR}/networking)
set(_TR_385_INTERFACE_DIR ${_TR_385_DIR}/interface)
if("${_TR_385_VERSION}" STREQUAL "issue2")
set(TR385_ISSUE2 y CACHE BOOL "TR-385 Issue 2" FORCE)
endif()
endif()
set(_IETF_IANA_DIR ${CMAKE_CURRENT_SOURCE_DIR}/IETF_IANA)
set(_TR_451_DIR ${CMAKE_CURRENT_SOURCE_DIR}/TR-451)
# Import YANG models to sysrepo
if (USE_OBBAA_YANG_MODELS)
if("${OBBAA_DEVICE_ADAPTER_VERSION}" STREQUAL "1.0")
set(_IMPORT_MODELS
${_OB_BAA_MODEL_DIR}/ietf-interfaces@2018-02-20.yang
${_OB_BAA_MODEL_DIR}/iana-if-type@2017-01-19.yang
${_OB_BAA_MODEL_DIR}/iana-hardware@2018-03-13.yang
${_OB_BAA_MODEL_DIR}/ietf-hardware.yang
${_OB_BAA_MODEL_DIR}/ietf-ipfix-psamp@2012-09-05.yang
${_OB_BAA_MODEL_DIR}/ietf-pseudowires@2018-10-22.yang
${_OB_BAA_MODEL_DIR}/ietf-alarms@2019-09-11.yang
${_OB_BAA_MODEL_DIR}/ietf-system.yang
${_OB_BAA_MODEL_DIR}/ieee802-dot1x.yang
${_OB_BAA_MODEL_DIR}/bbf-hardware-types.yang
${_OB_BAA_MODEL_DIR}/bbf-hardware-extension.yang
${_OB_BAA_MODEL_DIR}/bbf-sub-interfaces.yang
${_OB_BAA_MODEL_DIR}/bbf-sub-interface-tagging.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-policing-types.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-classifiers.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-policies-sub-interfaces.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-shaping.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-traffic-mngt.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-enhanced-scheduling.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-policer-envelope-profiles.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-policies.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-filters.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-policing.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-types.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-rate-control.yang
${_OB_BAA_MODEL_DIR}/bbf-interface-port-reference.yang
${_OB_BAA_MODEL_DIR}/bbf-l2-forwarding.yang
${_OB_BAA_MODEL_DIR}/bbf-yang-types.yang
${_OB_BAA_MODEL_DIR}/bbf-dot1q-types.yang
${_OB_BAA_MODEL_DIR}/bbf-if-type.yang
${_OB_BAA_MODEL_DIR}/bbf-frame-classification.yang
${_OB_BAA_MODEL_DIR}/bbf-xpon-types.yang
${_OB_BAA_MODEL_DIR}/bbf-xpon-if-type.yang
${_OB_BAA_MODEL_DIR}/bbf-xpon.yang
${_OB_BAA_MODEL_DIR}/bbf-xponvani.yang
${_OB_BAA_MODEL_DIR}/bbf-xponani.yang
${_OB_BAA_MODEL_DIR}/bbf-xpon-onu-states.yang
${_OB_BAA_MODEL_DIR}/bbf-link-table.yang
${_OB_BAA_MODEL_DIR}/bbf-xpongemtcont.yang
${_OB_BAA_MODEL_DIR}/bbf-xpon-onu-types.yang
${_OB_BAA_MODEL_DIR}/bbf-interface-usage.yang
${_OB_BAA_MODEL_DIR}/bbf-ghn.yang
${_OB_BAA_MODEL_DIR}/bbf-ghs.yang
${_OB_BAA_MODEL_DIR}/bbf-vdsl.yang
${_OB_BAA_MODEL_DIR}/bbf-selt.yang
${_OB_BAA_MODEL_DIR}/bbf-l2-dhcpv4-relay.yang
${_OB_BAA_MODEL_DIR}/bbf-hardware-rpf-dpu.yang
${_OB_BAA_MODEL_DIR}/bbf-pppoe-intermediate-agent.yang
${_OB_BAA_MODEL_DIR}/bbf-fast.yang
${_OB_BAA_MODEL_DIR}/bbf-mgmd.yang
${_OB_BAA_MODEL_DIR}/bbf-melt.yang
${_OB_BAA_MODEL_DIR}/bbf-subscriber-profiles.yang
${_OB_BAA_MODEL_DIR}/bbf-ldra.yang
${_OB_BAA_MODEL_DIR}/bbf-obbaa-mfc-conf.yang
${_OB_BAA_MODEL_DIR}/bbf-vomci-entity.yang
${_OB_BAA_MODEL_DIR}/bbf-omci-message-retransmission.yang
${_OB_BAA_MODEL_DIR}/bbf-network-function-endpoint-filter.yang
${_OB_BAA_MODEL_DIR}/bbf-device-types.yang
${_OB_BAA_MODEL_DIR}/bbf-network-function-types.yang
${_OB_BAA_MODEL_DIR}/bbf-grpc-client.yang
${_OB_BAA_MODEL_DIR}/bbf-network-function-server.yang
${_OB_BAA_MODEL_DIR}/bbf-network-function-client.yang
${_OB_BAA_MODEL_DIR}/bbf-vomci-types.yang
${_OB_BAA_MODEL_DIR}/bbf-olt-vomci.yang
)
set(ietf-hardware-features entity-mib hardware-state hardware-sensor hardware-config)
set(bbf-obbaa-mfc-conf-features control-relay nf-client-supported nf-server-supported)
list(APPEND _DIRS ${_TR_451_DIR}/common ${_TR_451_DIR}/types ${_TR_451_DIR}/wt-383-common)
else("${OBBAA_DEVICE_ADAPTER_VERSION}" STREQUAL "1.0")
set(_IMPORT_MODELS
${_OB_BAA_MODEL_DIR}/ietf-pseudowires@2018-10-22.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-composite-filters.yang
${_OB_BAA_MODEL_DIR}/bbf-hardware-rpf-dpu-state.yang
${_OB_BAA_MODEL_DIR}/ieee802-dot1x.yang
${_OB_BAA_MODEL_DIR}/bbf-alarm-types.yang
${_OB_BAA_MODEL_DIR}/bbf-xpon-power-management.yang
${_OB_BAA_MODEL_DIR}/bbf-l2-forwarding-shared-fdb.yang
${_OB_BAA_MODEL_DIR}/bbf-hardware-cpu.yang
${_OB_BAA_MODEL_DIR}/iana-hardware.yang
${_OB_BAA_MODEL_DIR}/ietf-yang-types.yang
${_OB_BAA_MODEL_DIR}/bbf-network-function-client.yang
${_OB_BAA_MODEL_DIR}/ietf-ethertypes.yang
${_OB_BAA_MODEL_DIR}/ietf-packet-fields.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-enhanced-scheduling.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-enhanced-scheduling-state.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-types.yang
${_OB_BAA_MODEL_DIR}/bbf-ancp-interfaces.yang
${_OB_BAA_MODEL_DIR}/bbf-xpon-defects.yang
${_OB_BAA_MODEL_DIR}/bbf-ptm.yang
${_OB_BAA_MODEL_DIR}/bbf-pppoe-intermediate-agent.yang
${_OB_BAA_MODEL_DIR}/bbf-link-table.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-filters.yang
${_OB_BAA_MODEL_DIR}/bbf-if-type.yang
${_OB_BAA_MODEL_DIR}/bbf-hardware-types.yang
${_OB_BAA_MODEL_DIR}/bbf-l2-terminations.yang
${_OB_BAA_MODEL_DIR}/bbf-availability.yang
${_OB_BAA_MODEL_DIR}/bbf-inet-types.yang
${_OB_BAA_MODEL_DIR}/bbf-vomci-types.yang
${_OB_BAA_MODEL_DIR}/bbf-xpon-if-type.yang
${_OB_BAA_MODEL_DIR}/bbf-hardware-rpf-dpu.yang
${_OB_BAA_MODEL_DIR}/ietf-ipfix-psamp.yang
${_OB_BAA_MODEL_DIR}/bbf-mgmd.yang
${_OB_BAA_MODEL_DIR}/bbf-ethernet-performance-management.yang
${_OB_BAA_MODEL_DIR}/bbf-ancp-fastdsl-access-extensions.yang
${_OB_BAA_MODEL_DIR}/ietf-hardware.yang
${_OB_BAA_MODEL_DIR}/ieee802-dot1x-types.yang
${_OB_BAA_MODEL_DIR}/bbf-gbond.yang
${_OB_BAA_MODEL_DIR}/bbf-hardware.yang
${_OB_BAA_MODEL_DIR}/bbf-interface-usage.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-traffic-mngt.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-traffic-mngt-state.yang
${_OB_BAA_MODEL_DIR}/bbf-device-types.yang
${_OB_BAA_MODEL_DIR}/bbf-l2-dhcpv4-relay.yang
${_OB_BAA_MODEL_DIR}/bbf-vdsl-alarm-types.yang
${_OB_BAA_MODEL_DIR}/bbf-interfaces-performance-management.yang
${_OB_BAA_MODEL_DIR}/bbf-hardware-transceivers.yang
${_OB_BAA_MODEL_DIR}/bbf-olt-vomci.yang
${_OB_BAA_MODEL_DIR}/bbf-ancp-fastdsl-threshold.yang
${_OB_BAA_MODEL_DIR}/bbf-vdsl.yang
${_OB_BAA_MODEL_DIR}/bbf-xpon-types.yang
${_OB_BAA_MODEL_DIR}/bbf-xpon-onu-types.yang
${_OB_BAA_MODEL_DIR}/bbf-subscriber-types.yang
${_OB_BAA_MODEL_DIR}/bbf-fast-alarm-types.yang
${_OB_BAA_MODEL_DIR}/bbf-sub-interface-tagging.yang
${_OB_BAA_MODEL_DIR}/ietf-hardware-state.yang
${_OB_BAA_MODEL_DIR}/bbf-xponani.yang
${_OB_BAA_MODEL_DIR}/bbf-network-function-types.yang
${_OB_BAA_MODEL_DIR}/bbf-l2-dhcpv4-relay-forwarding.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-classifiers.yang
${_OB_BAA_MODEL_DIR}/bbf-ghs.yang
${_OB_BAA_MODEL_DIR}/bbf-ghn.yang
${_OB_BAA_MODEL_DIR}/bbf-frame-classification.yang
${_OB_BAA_MODEL_DIR}/bbf-frame-processing-profiles.yang
${_OB_BAA_MODEL_DIR}/bbf-interfaces-statistics-management.yang
${_OB_BAA_MODEL_DIR}/ietf-inet-types.yang
${_OB_BAA_MODEL_DIR}/bbf-hardware-rpf-dpu-alarm-types.yang
${_OB_BAA_MODEL_DIR}/bbf-l2-forwarding.yang
${_OB_BAA_MODEL_DIR}/iana-if-type.yang
${_OB_BAA_MODEL_DIR}/bbf-xpongemtcont-qos.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-rate-control.yang
${_OB_BAA_MODEL_DIR}/bbf-sub-interfaces.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-policies-sub-interfaces.yang
${_OB_BAA_MODEL_DIR}/ietf-interfaces.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-shaping.yang
${_OB_BAA_MODEL_DIR}/bbf-hardware-transceivers-xpon.yang
${_OB_BAA_MODEL_DIR}/bbf-vomci-entity.yang
${_OB_BAA_MODEL_DIR}/ietf-system.yang
${_OB_BAA_MODEL_DIR}/bbf-network-function-server.yang
${_OB_BAA_MODEL_DIR}/ieee802-types.yang
${_OB_BAA_MODEL_DIR}/bbf-xponani-power-management.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-policies-sub-interface-rewrite.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-policer-envelope-profiles.yang
${_OB_BAA_MODEL_DIR}/bbf-network-function-endpoint-filter.yang
${_OB_BAA_MODEL_DIR}/bbf-yang-types.yang
${_OB_BAA_MODEL_DIR}/bbf-xpon.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-policies.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-policies-state.yang
${_OB_BAA_MODEL_DIR}/bbf-subscriber-profiles.yang
${_OB_BAA_MODEL_DIR}/bbf-melt.yang
${_OB_BAA_MODEL_DIR}/bbf-kafka-agent.yang
${_OB_BAA_MODEL_DIR}/bbf-fastdsl.yang
${_OB_BAA_MODEL_DIR}/bbf-hardware-storage-drives.yang
${_OB_BAA_MODEL_DIR}/ietf-alarms-x733.yang
${_OB_BAA_MODEL_DIR}/bbf-grpc-client.yang
${_OB_BAA_MODEL_DIR}/bbf-gbond-state.yang
${_OB_BAA_MODEL_DIR}/ietf-http-server.yang
${_OB_BAA_MODEL_DIR}/bbf-dot1q-types.yang
${_OB_BAA_MODEL_DIR}/ietf-yang-library.yang
${_OB_BAA_MODEL_DIR}/bbf-xpon-onu-state.yang
${_OB_BAA_MODEL_DIR}/bbf-mgmd-mrd.yang
${_OB_BAA_MODEL_DIR}/bbf-xponvani-power-management.yang
${_OB_BAA_MODEL_DIR}/bbf-ldra.yang
${_OB_BAA_MODEL_DIR}/bbf-xpongemtcont-gemport-performance-management.yang
${_OB_BAA_MODEL_DIR}/bbf-xpongemtcont.yang
${_OB_BAA_MODEL_DIR}/bbf-ancp.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-policing-types.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-policing.yang
${_OB_BAA_MODEL_DIR}/bbf-qos-policing-state.yang
${_OB_BAA_MODEL_DIR}/bbf-mgmd-types.yang
${_OB_BAA_MODEL_DIR}/ietf-routing-types@2017-12-04.yang
${_OB_BAA_MODEL_DIR}/bbf-xpon-performance-management.yang
${_OB_BAA_MODEL_DIR}/ietf-http-client.yang
${_OB_BAA_MODEL_DIR}/bbf-xponvani.yang
${_OB_BAA_MODEL_DIR}/bbf-fast.yang
${_OB_BAA_MODEL_DIR}/bbf-selt.yang
${_OB_BAA_MODEL_DIR}/ietf-alarms.yang
${_OB_BAA_MODEL_DIR}/bbf-omci-message-retransmission.yang
${_OB_BAA_MODEL_DIR}/ieee802-ethernet-interface.yang
${_OB_BAA_MODEL_DIR}/bbf-obbaa-mfc-conf.yang
)
set(ietf-hardware-features entity-mib hardware-state hardware-sensor)
set(bbf-hardware-features interface-hardware-management)
set(bbf-xpon-power-management-features xpon-power-management)
endif("${OBBAA_DEVICE_ADAPTER_VERSION}" STREQUAL "1.0")
set(bbf-olt-vomci-features nf-client-supported nf-server-supported)
set(bbf-network-function-client-features grpc-client-supported)
set(bbf-obbaa-mfc-conf-features control-relay nf-client-supported nf-server-supported)
list(APPEND _DIRS ${_IETF_IANA_DIR})
else()
set(_IMPORT_MODELS
${_IETF_IANA_DIR}/ietf-interfaces.yang
${_IETF_IANA_DIR}/iana-if-type.yang
${_IETF_IANA_DIR}/iana-hardware.yang
${_IETF_IANA_DIR}/ietf-hardware.yang
${_TR_385_EQUIPMENT_DIR}/bbf-hardware-types.yang
${_TR_385_EQUIPMENT_DIR}/bbf-hardware.yang
${_TR_385_EQUIPMENT_DIR}/bbf-hardware-transceivers.yang
${_TR_385_INTERFACE_DIR}/bbf-sub-interfaces.yang
${_TR_385_INTERFACE_DIR}/bbf-sub-interface-tagging.yang
${_TR_385_NETWORKING_DIR}/bbf-qos-policing-types.yang
${_TR_385_NETWORKING_DIR}/bbf-qos-classifiers.yang
${_TR_385_NETWORKING_DIR}/bbf-qos-policies-sub-interfaces.yang
${_TR_385_NETWORKING_DIR}/bbf-qos-enhanced-scheduling.yang
${_TR_385_NETWORKING_DIR}/bbf-qos-policer-envelope-profiles.yang
${_TR_385_NETWORKING_DIR}/bbf-qos-policies.yang
${_TR_385_NETWORKING_DIR}/bbf-qos-filters.yang
${_TR_385_NETWORKING_DIR}/bbf-qos-policing.yang
${_TR_385_NETWORKING_DIR}/bbf-qos-types.yang
${_TR_385_NETWORKING_DIR}/bbf-qos-shaping.yang
${_TR_385_NETWORKING_DIR}/bbf-qos-rate-control.yang
${_TR_385_NETWORKING_DIR}/bbf-qos-traffic-mngt.yang
${_TR_385_NETWORKING_DIR}/bbf-l2-forwarding.yang
${_TR_385_COMMON_DIR}/bbf-yang-types.yang
${_TR_385_COMMON_DIR}/bbf-dot1q-types.yang
${_TR_385_INTERFACE_DIR}/bbf-if-type.yang
${_TR_385_INTERFACE_DIR}/bbf-frame-classification.yang
${_TR_385_INTERFACE_DIR}/bbf-xpon-types.yang
${_TR_385_INTERFACE_DIR}/bbf-xpon-if-type.yang
${_TR_385_INTERFACE_DIR}/bbf-xpon.yang
${_TR_385_INTERFACE_DIR}/bbf-xponvani.yang
${_TR_385_INTERFACE_DIR}/bbf-xponani.yang
${_TR_385_INTERFACE_DIR}/bbf-link-table.yang
${_TR_385_INTERFACE_DIR}/bbf-xpongemtcont.yang
${_TR_385_INTERFACE_DIR}/bbf-xpon-onu-types.yang
${_TR_385_INTERFACE_DIR}/bbf-interface-usage.yang)
set(ietf-hardware-features entity-mib hardware-state)
if(TR385_ISSUE2)
list(APPEND _IMPORT_MODELS
${_TR_385_EQUIPMENT_DIR}/bbf-hardware-transceivers-xpon.yang
${_TR_385_INTERFACE_DIR}/bbf-xpon-onu-state.yang
${_TR_385_INTERFACE_DIR}/bbf-xpon-defects.yang
${_TR_385_INTERFACE_DIR}/bbf-xpon-performance-management.yang
${_TR_385_INTERFACE_DIR}/bbf-xpon-power-management.yang)
set(bbf-xpon-power-management-features xpon-power-management)
else()
list(APPEND _IMPORT_MODELS
${_TR_385_INTERFACE_DIR}/bbf-xpon-onu-states.yang)
endif()
endif()
list(APPEND bbf-hardware-features additional-hardware-configuration model-name-configuration interface-hardware-reference hardware-component-reset)
set(ietf-interfaces-features arbitrary-names pre-provisioning if-mib)
set(bbf-xpongemtcont-features configurable-gemport-id configurable-alloc-id)
set(bbf-xponvani-features configurable-v-ani-onu-id configurable-v-ani-management-gem-port-id)
set(bbf-xponani-features configurable-ani-onu-id configurable-ani-management-gem-port-id)
set(bbf-xpon-features pon-pools)
set(bbf-sub-interfaces-features tag-rewrites)
set(bbf-sub-interface-tagging-features write-pbit-value-in-vlan-tag copy-vlan-id-from-tag-index)
set(bbf-l2-forwarding-features forwarding-databases shared-forwarding-databases mac-learning split-horizon-profiles)
# Import modules required for netopeer2 server
list(APPEND _IMPORT_MODELS
${_IETF_IANA_DIR}/iana-crypt-hash.yang
${_IETF_IANA_DIR}/ietf-crypto-types.yang
${_IETF_IANA_DIR}/ietf-x509-cert-to-name.yang
${_IETF_IANA_DIR}/ietf-datastores.yang
${_IETF_IANA_DIR}/ietf-keystore.yang
${_IETF_IANA_DIR}/ietf-truststore.yang
${_IETF_IANA_DIR}/ietf-tcp-common.yang
${_IETF_IANA_DIR}/ietf-tcp-client.yang
${_IETF_IANA_DIR}/ietf-tcp-server.yang
${_IETF_IANA_DIR}/ietf-tls-common.yang
${_IETF_IANA_DIR}/ietf-tls-server.yang
${_IETF_IANA_DIR}/ietf-tls-client.yang
${_IETF_IANA_DIR}/ietf-netconf-notifications.yang
${_IETF_IANA_DIR}/ietf-ssh-common.yang
${_IETF_IANA_DIR}/ietf-ssh-client.yang
${_IETF_IANA_DIR}/ietf-ssh-server.yang
${_IETF_IANA_DIR}/ietf-netconf.yang
${_IETF_IANA_DIR}/ietf-netconf-server.yang
${_IETF_IANA_DIR}/ietf-netconf-nmda.yang
${_IETF_IANA_DIR}/ietf-netconf-acm.yang
${_IETF_IANA_DIR}/ietf-netconf-monitoring.yang
${_IETF_IANA_DIR}/notifications.yang
${_IETF_IANA_DIR}/nc-notifications.yang)
set(ietf-tcp-client-features local-binding-supported)
set(ietf-netconf-nmda-features origin with-defaults)
set(ietf-netconf-features candidate writable-running rollback-on-error validate startup url xpath)
set(ietf-keystore-features keystore-supported)
set(ietf-truststore-features truststore-supported)
set(ietf-tcp-common-features keepalives-supported)
set(ietf-ssh-server-features ssh-server-transport-params-config client-auth-config-supported client-auth-publickey client-auth-password)
set(ietf-tls-server-features client-auth-config-supported psk-auth)
set(ietf-netconf-server-features ssh-listen tls-listen ssh-call-home tls-call-home)
# Import WT-451 models
if (NOT USE_OBBAA_YANG_MODELS)
list(APPEND _IMPORT_MODELS
${_TR_451_DIR}/common/bbf-vomci-entity.yang
${_TR_451_DIR}/common/bbf-omci-message-retransmission.yang
${_TR_451_DIR}/common/bbf-network-function-endpoint-filter.yang
${_TR_451_DIR}/wt-383-common/bbf-device-types.yang
${_TR_451_DIR}/wt-383-common/bbf-network-function-types.yang
${_TR_451_DIR}/wt-383-common/bbf-grpc-client.yang
${_TR_451_DIR}/wt-383-common/bbf-network-function-server.yang
${_TR_451_DIR}/wt-383-common/bbf-network-function-client.yang
${_TR_451_DIR}/types/bbf-vomci-types.yang
${_TR_451_DIR}/olt/bbf-olt-vomci.yang)
set(bbf-olt-vomci-features nf-client-supported nf-server-supported)
set(bbf-network-function-client-features grpc-client-supported)
endif()
unset(_SEARCH_DIRS)
foreach(_DIR ${_DIRS})
if(_SEARCH_DIRS)
set(_SEARCH_DIRS "${_SEARCH_DIRS}:${_DIR}")
else()
set(_SEARCH_DIRS "--search-dirs ${_DIR}")
endif()
endforeach(_DIR)
# Import models
unset(_FEATURES_OPT)
unset(_FEATURES_OPT_CMD)
unset(_FEATURES_OPT_CMD_ECHO)
unset(_IMPORT_INSTALLED)
unset(_IMPORT_INSTALLED_PREV)
foreach(_IMPORT ${_IMPORT_MODELS})
get_filename_component(_IMPORT_NAME ${_IMPORT} NAME_WE)
string(REGEX REPLACE "(.*)@(.*)" "\\1" _IMPORT_NAME_UNVERSIONED "${_IMPORT_NAME}")
get_filename_component(_IMPORT_DIR ${_IMPORT} DIRECTORY)
set(_IMPORT_INSTALLED_PREV ${_IMPORT_INSTALLED})
set(_IMPORT_INSTALLED ${CMAKE_CURRENT_BINARY_DIR}/.${_IMPORT_NAME}.installed)
set(_FEATURES ${_IMPORT_NAME_UNVERSIONED}-features)
if(${_FEATURES})
foreach(_FEATURE ${${_FEATURES}})
list(APPEND _FEATURES_OPT --enable-feature ${_FEATURE})
endforeach(_FEATURE)
endif()
if(_FEATURES_OPT)
set(_FEATURES_OPT_CMD COMMAND ${_SYSREPOTOOL_WRAPPER} ${_SYSREPOCTL} --change ${_IMPORT_NAME_UNVERSIONED} -a ${_FEATURES_OPT})
set(_FEATURES_OPT_CMD_ECHO COMMAND echo ${_SYSREPOTOOL_WRAPPER} ${_SYSREPOCTL} --change ${_IMPORT_NAME_UNVERSIONED} ${_FEATURES_OPT})
endif()
add_custom_command(OUTPUT ${_IMPORT_INSTALLED}
COMMAND mkdir -p ${CMAKE_CURRENT_BINARY_DIR}
COMMAND echo ${_SYSREPOTOOL_WRAPPER} ${_SYSREPOCTL} --install ${_IMPORT} ${_SEARCH_DIRS}
COMMAND ${_SYSREPOTOOL_WRAPPER} ${_SYSREPOCTL} --install ${_IMPORT} -a ${_SEARCH_DIRS}
${_FEATURES_OPT_CMD_ECHO}
${_FEATURES_OPT_CMD}
COMMAND echo ${_IMPORT} imported to sysrepo
COMMAND touch ${_IMPORT_INSTALLED}
DEPENDS sysrepo ${_IMPORT_INSTALLED_PREV}
WORKING_DIRECTORY ${_IMPORT_DIR})
unset(_FEATURES_OPT)
unset(_FEATURES_OPT_CMD)
unset(_FEATURES_OPT_CMD_ECHO)
endforeach(_IMPORT)
add_custom_target(yang-models-push-scheduled-changes
COMMAND ${_SYSREPOTOOL_WRAPPER} ${_SYSREPOCTL} -l > /dev/null
DEPENDS ${_IMPORT_INSTALLED}
WORKING_DIRECTORY ${_IMPORT_DIR})
bcm_3rdparty_add_dependencies(yang-models-push-scheduled-changes)
bcm_3rdparty_build_dummy()
bcm_3rdparty_export()
<file_sep>bcm_module_name(host_config)
bcm_module_header_paths(PUBLIC .)
bcm_create_lib_target()
# Add files to the GitHub part of the release tree.
bcm_github_install(./* RELEASE github/config EXCLUDE_FROM_RELEASE TODO.REVIEW.txt)
# Install the bal_config.ini when building for release
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/bal_config.ini)
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/bal_config.ini DESTINATION fs)
endif()
<file_sep># Google protobuf
#
include(third_party)
bcm_3rdparty_module_name(protobuf "3.11.0")
bcm_3rdparty_download_wget("https://github.com/protocolbuffers/protobuf/releases/download/v${PROTOBUF_VERSION}" "protobuf-cpp-${PROTOBUF_VERSION}.tar.gz")
bcm_3rdparty_add_dependencies(zlib)
bcm_3rdparty_add_build_options(--enable-silent-rules --enable-shared --enable-static)
bcm_3rdparty_add_build_options(--with-zlib --with-zlib-include=${_${_MOD_NAME_UPPER}_INSTALL_TOP}/include --with-zlib-lib=${_${_MOD_NAME_UPPER}_INSTALL_TOP}/lib)
if(NOT ("${BOARD}" STREQUAL "sim"))
bcm_3rdparty_add_build_options(--with-protoc=${PROTOC})
endif()
bcm_3rdparty_build_automake()
bcm_3rdparty_export()
<file_sep>/*
<:copyright-BRCM:2016-2019:Apache:standard
Copyright (c) 2016-2019 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
* :>
*/
#ifndef BCMOS_ERRNO_H_
#define BCMOS_ERRNO_H_
/** \defgroup system_errno Error Codes
* @{
*/
/** Error codes */
typedef enum
{
BCM_ERR_OK = 0, /**< OK */
BCM_ERR_IN_PROGRESS = -1, /**< Operation is in progress */
BCM_ERR_PARM = -2, /**< Error in parameters */
BCM_ERR_NOMEM = -3, /**< No memory */
BCM_ERR_NORES = -4, /**< No resources */
BCM_ERR_INTERNAL = -5, /**< Internal error */
BCM_ERR_NOENT = -6, /**< Entry doesn't exist */
BCM_ERR_NODEV = -7, /**< Device doesn't exist */
BCM_ERR_ALREADY = -8, /**< Entry already exists */
BCM_ERR_RANGE = -9, /**< Out of range */
BCM_ERR_PERM = -10, /**< No permission to perform an operation */
BCM_ERR_NOT_SUPPORTED = -11, /**< Operation is not supported */
BCM_ERR_PARSE = -12, /**< Parsing error */
BCM_ERR_INVALID_OP = -13, /**< Invalid operation */
BCM_ERR_IO = -14, /**< I/O error */
BCM_ERR_STATE = -15, /**< Object is in bad state */
BCM_ERR_DELETED = -16, /**< Object is deleted */
BCM_ERR_TOO_MANY = -17, /**< Too many objects */
BCM_ERR_NO_MORE = -18, /**< No more entries */
BCM_ERR_OVERFLOW = -19, /**< Buffer overflow */
BCM_ERR_COMM_FAIL = -20, /**< Communication failure */
BCM_ERR_NOT_CONNECTED = -21, /**< No connection with the target system */
BCM_ERR_SYSCALL_ERR = -22, /**< System call returned error */
BCM_ERR_MSG_ERROR = -23, /**< Received message is insane */
BCM_ERR_TOO_MANY_REQS = -24, /**< Too many outstanding requests */
BCM_ERR_TIMEOUT = -25, /**< Operation timed out */
BCM_ERR_TOO_MANY_FRAGS = -26, /**< Too many fragments */
BCM_ERR_NULL = -27, /**< Got NULL pointer */
BCM_ERR_READ_ONLY = -28, /**< Attempt to set read-only parameter */
BCM_ERR_ONU_ERR_RESP = -29, /**< ONU returned an error response */
BCM_ERR_MANDATORY_PARM_IS_MISSING = -30, /**< Mandatory parameter is missing */
BCM_ERR_KEY_RANGE = -31, /**< Key field was out of range */
BCM_ERR_QUEUE_EMPTY = -32, /**< Rx PCIe queue empty */
BCM_ERR_QUEUE_FULL = -33, /**< Tx PCIe queue full */
BCM_ERR_TOO_LONG = -34, /**< Processing is taking too long, but will finish eventually */
BCM_ERR_INSUFFICIENT_LIST_MEM = -35, /**< Not enough memory was provided for variable-length lists */
BCM_ERR_OUT_OF_SYNC = -36, /**< Sequence number or operation step was out of sync. */
BCM_ERR_CHECKSUM = -37, /**< Checksum error */
BCM_ERR_IMAGE_TYPE = -38, /**< Unsupported file/image type */
BCM_ERR_INCOMPLETE_TERMINATION = -39, /**< Incomplete premature termination */
BCM_ERR_MISMATCH = -40, /**< Parameters mismatch */
BCM_ERR_DEPRECATED = -41, /**< Parameters is deprecated */
} bcmos_errno;
/** Map error code to error string
* \param[in] err Error code
* \returns Error string
*/
const char *bcmos_strerror(bcmos_errno err);
/** @} system_errno */
#endif /* BCMOS_ERRNO_H_ */
<file_sep># libev - high performance event loop
#
include(third_party)
bcm_3rdparty_module_name(libev "4.31")
bcm_3rdparty_download_wget("https://distfiles.macports.org/libev" "libev-${LIBEV_VERSION}.tar.gz")
if("${BOARD}" STREQUAL "asfvolt16" OR "${BOARD}" STREQUAL "asgvolt64")
set(LIBEV-DO_NOT_RECONF true)
endif()
bcm_3rdparty_build_automake()
bcm_3rdparty_export()
<file_sep># TR-451 pOLT vendor interface
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/bcm)
bcm_add_subdirectory(bcm)
else()
bcm_add_subdirectory(sim)
endif()
<file_sep># Make option for enabling/disabling logger
bcm_make_normal_option(LOG BOOL "Enable host side logger" y)
bcm_module_name(dev_log)
bcm_module_header_paths(PUBLIC .)
# ENABLE_LOG is always set in embedded side.
if("${SUBSYSTEM}" STREQUAL "embedded")
bcm_module_definitions(PUBLIC -DENABLE_LOG)
set(LOG "y" PARENT_SCOPE)
set(LOG "y")
endif()
if(${LOG})
bcm_module_dependencies(PUBLIC os cli utils)
bcm_make_debug_option(LOG_DEBUG BOOL "Enable Dev Log Debugging" n)
bcm_make_debug_option(LOG_TRIGGER BOOL "Enable Dev Log Trigger Feature" n)
if("${OS}" STREQUAL "posix")
bcm_make_normal_option(LOG_SYSLOG BOOL "Enable logging to syslog" y)
if(${LOG_SYSLOG})
bcm_module_definitions(PUBLIC -DDEV_LOG_SYSLOG)
endif()
endif()
bcm_module_definitions(PUBLIC -DENABLE_LOG)
if(${LOG_DEBUG})
bcm_module_definitions(PRIVATE -DDEV_LOG_DEBUG)
endif()
if(${LOG_TRIGGER})
bcm_module_definitions(PRIVATE -DTRIGGER_LOGGER_FEATURE)
endif()
bcm_module_srcs(bcm_dev_log.c bcm_dev_log_task.c)
if(${CLI})
bcm_module_srcs(bcm_dev_log_cli.c)
endif()
if("${TOOLCHAIN}" STREQUAL "gcc")
bcm_module_cflags(PRIVATE -Wno-format-security)
endif()
endif()
bcm_create_lib_target()
# Add files to the GitHub part of the release tree.
bcm_github_install(./* RELEASE github/dev_log)
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#ifndef __BCM_DEV_LOG_TASK_INTERNAL_H_
#define __BCM_DEV_LOG_TASK_INTERNAL_H_
#ifdef ENABLE_LOG
#include <bcmos_system.h>
#define LOG_NAME_NO_INSTANCE 0xff
#define LOG_NAME_LENGTH (MAX_DEV_LOG_ID_NAME + 1)
typedef enum
{
BCM_DEV_LOG_STATE_UNINITIALIZED,
BCM_DEV_LOG_STATE_DISABLED,
BCM_DEV_LOG_STATE_ENABLED,
} bcm_dev_log_state;
typedef struct
{
bcm_dev_log_parm dev_log_parm;
bcm_dev_log_file files[DEV_LOG_MAX_FILES]; /* log files */
uint32_t msg_count; /* Message counter */
dev_log_id_parm ids[DEV_LOG_MAX_IDS]; /* dev_log IDS array */
bcm_dev_log_state state;
bcmos_msg_queue save_queue; /* Log messages to be saved to RAM (first stage of pipeline) */
bcmos_msg_queue print_queue; /* Log messages to be printed (second stage of pipeline) */
bcmos_task save_task;
bcmos_task print_task;
bcmos_sem save_task_is_terminated;
bcmos_sem print_task_is_terminated;
bcmos_msg_pool pool;
bcm_dev_log_flags flags; /* General flags applied on the entire feature (unlike file flags which reside in 'files' sub-structure). */
} bcm_dev_log;
typedef struct
{
dev_log_id_parm *log_id;
uint32_t time_stamp;
bcm_dev_log_level msg_level;
uint32_t flags;
union
{
struct
{
const char *fmt;
/* Room for MAX + 1 arguments since the argument list needs to start on an 8-byte boundary - the first
* entry may be unused if the array doesn't naturally start on an 8-byte boundary. */
const void *args[DEV_LOG_MAX_ARGS + 1];
} fmt_args; /* Relevant in default mode - when not using BCM_LOG_FLAG_CALLER_FMT */
char str[MAX_DEV_LOG_STRING_SIZE]; /* Relevant only if using BCM_LOG_FLAG_CALLER_FMT */
} u;
} dev_log_queue_msg;
typedef struct
{
char name[LOG_NAME_LENGTH];
uint8_t first_instance;
uint8_t last_instance;
} log_name_table;
extern bcm_dev_log dev_log;
extern const char *log_level_str;
extern log_name_table logs_names[DEV_LOG_MAX_IDS];
extern uint8_t log_name_table_index;
bcmos_errno _bcm_dev_log_file_clear_no_lock(uint32_t file_index);
/* Internal init function */
void bcm_dev_log_frontend_init(void);
#endif /* ENABLE_LOG */
#endif /* __BCM_DEV_LOG_TASK_INTERNAL_H_ */
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
/*******************************************************************
* bcmcli_session.h
*
* BCM CLI engine - session management
*
*******************************************************************/
#ifndef BCMCLI_SESSION_H
#define BCMCLI_SESSION_H
#include <bcmos_system.h>
#include <stdarg.h>
#include "bcmolt_string.h"
/** \defgroup bcmcli_session Management Session Control
*
* APIs in this header file allow to create/destroy management sessions.
* Management session is characterized by its access level and also
* input/output functions.
* Management sessions allow managed entities in the system to communicate
* with local or remote managers (e.g., local or remote shell or NMS)
* @{
*/
/** Access rights */
typedef enum
{
BCMCLI_ACCESS_GUEST, /**< Guest. Doesn't have access to commands and directories registered with ADMIN rights */
BCMCLI_ACCESS_ADMIN, /**< Administrator: full access */
BCMCLI_ACCESS_DEBUG, /**< Administrator: full access + extended debug features */
} bcmcli_access_right;
/** Line edit mode */
typedef enum
{
BCMCLI_LINE_EDIT_DEFAULT,/**< Enable line editing and history if CONFIG_EDITLINE is defined, disable otherwise */
BCMCLI_LINE_EDIT_ENABLE, /**< Enable line editing. Requires CONFIG_EDITLINE define and libedit-dev library */
BCMCLI_LINE_EDIT_DISABLE,/**< Disable line editing and history */
} bcmcli_line_edit_mode;
/** Management session handle
*/
typedef struct bcmcli_session bcmcli_session;
/** Session parameters structure.
* See \ref bcmcli_session_open
*/
typedef struct bcmcli_session_parm
{
const char *name; /**< Session name */
void *user_priv; /**< Private user's data */
/** Session's output function. NULL=use write(stdout)
* returns the number of bytes written or <0 if error
*/
int (*write)(bcmcli_session *session, const char *buf, uint32_t size);
/** Session line input function. NULL=use default(stdin[+line edit) */
char *(*gets)(bcmcli_session *session, char *buf, uint32_t size);
/** Session char input function. NULL=use bcmos_getchar() */
int (*get_char)(bcmcli_session *session);
/** Fill the specified buffer with the prompt for this session (NULL-terminated). NULL = no prompt. */
void (*get_prompt)(bcmcli_session *session, char *buf, uint32_t max_len);
/** Access rights */
bcmcli_access_right access_right;
/** Line editing mode */
bcmcli_line_edit_mode line_edit_mode;
/** Stack size for per-session dynamic memory allocation. */
uint32_t stack_size;
#define BCMCLI_SESSION_MIN_STACK_SIZE (128 * 1024)
/** Extra data size to be allocated along with session control block.
* The extra data is accessible using bcmcli_session_data().
* Please note that if session is created using bcmcli_session_open(),
* extra_size is reserved.
* It can only be used for user context allocation if session is created
* using bcmcli_session_open_user()
*/
uint32_t extra_size;
} bcmcli_session_parm;
/** Open monitor session
*
* Monitor supports multiple simultaneous sessions with different
* access rights.
* Note that there already is a default session with full administrative rights,
* that takes input from stdin and outputs to stdout.
*
* Please don't use parm.extra_size. This field is reserved.
*
* \param[in] parm Session parameters. Must not be allocated on the stack.
* \param[out] p_session Session handle
* \return
* 0 =OK\n
* <0 =error code
*/
bcmos_errno bcmcli_session_open(const bcmcli_session_parm *parm, bcmcli_session **p_session);
/** Close monitor session.
* \param[in] session Session handle
*/
void bcmcli_session_close(bcmcli_session *session);
/** Write function.
* Write buffer to the current session.
* \param[in] session Session handle. NULL=use stdout
* \param[in] buf output buffer
* \param[in] size number of bytes to be written
* \return
* >=0 - number of bytes written\n
* <0 - output error
*/
int bcmcli_session_write(bcmcli_session *session, const char *buf, uint32_t size);
/** Read line
* \param[in] session Session handle. NULL=use default
* \param[in,out] buf input buffer
* \param[in] size buf size
* \return
* buf if successful
* NULL if EOF or error
*/
char *bcmcli_session_gets(bcmcli_session *session, char *buf, uint32_t size);
/** Print function.
* Prints in the context of current session.
* \param[in] session Session handle. NULL=use stdout
* \param[in] format print format - as in printf
*/
void bcmcli_session_print(bcmcli_session *session, const char *format, ...)
#ifndef BCMCLI_SESSION_DISABLE_FORMAT_CHECK
__attribute__((format(printf, 2, 3)))
#endif
;
/** Print function.
* Prints in the context of current session.
* \param[in] session Session handle. NULL=use stdout
* \param[in] format print format - as in printf
* \param[in] ap parameters list. Undefined after the call
*/
void bcmcli_session_vprint(bcmcli_session *session, const char *format, va_list ap);
/** Print buffer in hexadecimal format
* \param[in] session Session handle. NULL=use stdout
* \param[in] buffer Buffer address
* \param[in] offset Start offset in the buffer
* \param[in] count Number of bytes to dump
* \param[in] indent Optional indentation string
*/
void bcmcli_session_hexdump(bcmcli_session *session, const void *buffer, uint32_t offset, uint32_t count, const char *indent);
/** Get extra data associated with the session
* \param[in] session Session handle. NULL=default session
* \return extra_data pointer or NULL if there is no extra data
*/
void *bcmcli_session_data(bcmcli_session *session);
/** Get user_priv provided in session parameters when it was registered
* \param[in] session Session handle. NULL=default session
* \return usr_priv value
*/
void *bcmcli_session_user_priv(bcmcli_session *session);
/** Get session name
* \param[in] session Session handle. NULL=use stdin
* \return session name
*/
const char *bcmcli_session_name(bcmcli_session *session);
/** Get session access rights
* \param[in] session Session handle. NULL=default debug session
* \return session access right
*/
bcmcli_access_right bcmcli_session_access_right(bcmcli_session *session);
/** @} end of bcmcli_session group */
/** Low-level interface for when session is used outside CLI
*
* \param[in] parm Session parameters. Must not be allocated on the stack.
* \param[out] p_session Session handle
* \return
* 0 =OK\n
* <0 =error code
*/
bcmos_errno bcmcli_session_open_user(const bcmcli_session_parm *parm, bcmcli_session **p_session);
/** Open a session that prints to the specified string
*/
bcmos_errno bcmcli_session_open_string(bcmcli_session **session, bcmolt_string *str);
/** Allocate memory from session stack
*
* \param[in] session Session handle
* \param[in] size Size of memory block to be allocated
* \return address of memory block or NULL
*/
void *bcmcli_session_stack_calloc(bcmcli_session *session, uint32_t size);
/** Reset session stack
*
* \param[in] session Session handle
*/
void bcmcli_session_stack_reset(bcmcli_session *session);
/** Configure RAW input mode
*
* \param[in] session Session handle
* \param[in] is_raw TRUE=enable raw mode, FALSE=disable raw mode
* \return
* =0 - OK \n
* BCM_ERR_NOT_SUPPORTED - raw mode is not supported\n
*/
bcmos_errno bcmcli_session_raw_mode_set(bcmcli_session *session, bcmos_bool is_raw);
/** Context extension
*
* - if no command - display list of command or extend command
* - if prev char is " "
* - if positional and next parm is enum - show/extends list of matching values
* - else - show/extend list of unused parameters
* else
* - if entering value and enum - show/extends list of matching values
* - else - show/extend list of matching unused parameters
*
* \param[in] session Session handle
* \param[in] input_string String to be parsed
* \param[out] insert_str String to insert at cursor position
* \param[in] insert_size Insert buffer size
* \return
* =0 - OK \n
* BCM_ERR_PARM - parsing error\n
*/
bcmos_errno bcmcli_extend(bcmcli_session *session, char *input_string,
char *insert_str, uint32_t insert_size);
/** Acquire session write lock.
* This function is useful to print block of data uninterruptible
* in multi-thread context
*/
void bcmcli_session_lock(bcmcli_session *session);
/** Release session write lock.
*/
void bcmcli_session_unlock(bcmcli_session *session);
#ifdef BCMCLI_INTERNAL
#define BCMCLI_SESSION_OUTBUF_LEN 4096
#define BCMCLI_SESSION_TAB_COMPLETE_BUF_LEN 4096
#define BCMCLI_SESSION_TAB_COMPLETE_HELP_BUF_LEN (16*1024)
#define BCMCLI_MAX_PROMPT_LEN 10
/* editline functionality */
/* If libedit is included - it takes precedence */
#ifdef CONFIG_LIBEDIT
#include <histedit.h>
#undef CONFIG_LINENOISE
#endif /* #ifdef CONFIG_LIBEDIT */
#ifdef CONFIG_LINENOISE
#include <linenoise.h>
#endif
/* Management session structure */
struct bcmcli_session
{
bcmcli_session *next;
bcmcli_session_parm parms;
uint32_t magic;
#define BCMCLI_SESSION_MAGIC (('s'<<24)|('e'<<16)|('s'<<8)|'s')
#define BCMCLI_SESSION_MAGIC_DEL (('s'<<24)|('e'<<16)|('s'<<8)|'~')
/* Line editing and history support */
#ifdef CONFIG_LIBEDIT
EditLine *el;
History *history;
HistEvent histevent;
#endif
#ifdef CONFIG_LINENOISE
linenoiseSession *ln_session;
#endif
struct
{
char *start;
uint32_t size;
uint32_t allocated;
} stack;
char outbuf[BCMCLI_SESSION_OUTBUF_LEN];
char prompt_buf[BCMCLI_MAX_PROMPT_LEN];
char tab_complete_buf[BCMCLI_SESSION_TAB_COMPLETE_BUF_LEN];
char tab_complete_help_buf[BCMCLI_SESSION_TAB_COMPLETE_HELP_BUF_LEN];
bcmolt_string tab_complete_help_string;
bcmos_bool tab_complete_mode; /* In tab-complete mode bcmcli_session_print() "prints" to tab_complete_help_buf */
bcmos_mutex write_lock;
/* Followed by session data */
};
#endif
#ifndef ENABLE_CLI
#define bcmcli_session_print(session, format, ...) \
do \
{ \
} \
while (0)
#define bcmcli_session_open_user(parm, p_session) BCM_ERR_OK;
#define bcmcli_session_close(s_session) \
do \
{ \
} \
while (0)
#endif
#ifndef ENABLE_CLI
#define bcmcli_session_vprint(session, format, ap) \
do \
{ \
} \
while (0)
#define bcmcli_session_open_user(parm, p_session) BCM_ERR_OK;
#define bcmcli_session_close(s_session) \
do \
{ \
} \
while (0)
#endif
#endif /* #ifndef BCMCLI_SESSION_H */
<file_sep># Top level CMakeLists.txt defining the build project for the BCM68620 products
#====
# Indicate the minimum version of CMake required
#====
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)
#====
# Identify where to find the modules
#====
set(CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules)
#====
# Set a project version. Really doesn't matter what we use here, but it could be release related if we want
#====
set(PROJECT_VERSION 3.0.0)
#====
# Define the project we are building for
#====
project(bcm686xx
VERSION ${PROJECT_VERSION}
LANGUAGES CXX C ASM)
#====
# Set global variables used here
#====
set(SOURCE_TOP ${CMAKE_CURRENT_SOURCE_DIR})
set(BUILD_TOP ${CMAKE_CURRENT_BINARY_DIR})
set(CMAKE_INSTALL_PREFIX ${BUILD_TOP})
set(OPEN_SOURCE_SIM y CACHE BOOL "Open Source Simulation Build" FORCE)
#====
# Add the CMake modules we use here
#====
include(utils)
include(common_definitions)
include(build_macros)
include(protoc_codegen_macros) # Macros supporting code generation from .proto and building the generation files
include(optional_macros) # Include any optional macros used for internal testing
include(third_party) # Macros for downloading & building third-party libraries
#====
# Add the top level subdirectories we need to add
#====
bcm_add_subdirectory(os_abstraction)
bcm_add_subdirectory(config)
bcm_add_subdirectory(utils)
bcm_add_subdirectory(daemon)
bcm_add_subdirectory(cli)
bcm_add_subdirectory(dev_log)
bcm_add_subdirectory(third_party)
bcm_add_subdirectory(tr451_vomci_polt)
bcm_add_subdirectory(netconf_server)
#====
# Post processing support to make the custom properties transitive
#====
include(post_process)
bcm_flatten_transitive_dependencies()
add_custom_target(github_install_include)
<file_sep>/*
* <:copyright-BRCM:2016-2020:Apache:standard
*
* Copyright (c) 2016-2020 Broadcom. All Rights Reserved
*
* The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* :>
*
*****************************************************************************/
/*
* netconf_module_utils.h
*
* Created on: 31 Aug 2017
* Author: igort
*/
#ifndef _NETCONF2_MODULE_UTILS_H_
#define _NETCONF2_MODULE_UTILS_H_
#include <bcmos_system.h>
#include <sysrepo.h>
#include <libyang/libyang.h>
#include <b64.h>
#include <bcmolt_netconf_module_init.h>
#ifdef ENABLE_LOG
#include <bcm_dev_log.h>
extern dev_log_id log_id_netconf;
#endif
#define NC_LOG_ERR(fmt, args...) BCM_LOG(ERROR, log_id_netconf, fmt, ##args);
#define NC_LOG_INFO(fmt, args...) BCM_LOG(INFO, log_id_netconf, fmt, ##args);
#define NC_LOG_WARN(fmt, args...) BCM_LOG(WARNING, log_id_netconf, fmt, ##args);
#define NC_LOG_DBG(fmt, args...) BCM_LOG(DEBUG, log_id_netconf, fmt, ##args);
/*
* Serialization primitives. Lock/unlock configuration
*/
void nc_config_lock(void);
void nc_config_unlock(void);
/* Datastore type */
typedef enum
{
NC_DATASTORE_RUNNING, /* Running configuration */
NC_DATASTORE_STARTUP, /* Startup configuration */
NC_DATASTORE_CANDIDATE, /* Candidate configuration */
NC_DATASTORE_PENDING, /* Pending configuration - to be applied when some preconditions are met */
} nc_datastore_type;
/*
* Transaction support.
* It is used to copy aside a list of nodes when dat apath modification callback is called.
*/
/* Sysrepo transaction data. Operation and linked list of old and new node values */
typedef struct nc_transact_elem nc_transact_elem;
struct nc_transact_elem
{
sr_val_t *old_val;
sr_val_t *new_val;
STAILQ_ENTRY(nc_transact_elem) next;
};
typedef struct nc_transact
{
sr_event_t event;
int plugin_elem_type; /* Plugin-specific element type (ie, iftype) */
#define NC_TRANSACT_PLUGIN_ELEM_TYPE_INVALID (-1)
STAILQ_HEAD(trans_elems, nc_transact_elem) elems;
bcmos_bool do_not_free_values;
} nc_transact;
void nc_transact_init(nc_transact *tr, sr_event_t event);
bcmos_errno nc_transact_add(nc_transact *tr, sr_val_t **p_old_val, sr_val_t **p_new_val);
void nc_transact_free(nc_transact *tr);
/* Get leaf node name in the xpath.
* It is the node that follows the last /
*/
const char *nc_xpath_leaf_get(const char *xpath, char *leaf, uint32_t leaf_size);
/* Get the key value from xpath
*
* xpath = node/node[keyname='keyvalue']/node/node
*
* Returns
* - BCM_ERR_OK
* - BCM_ERR_NOENT - no key in []
* - BCM_ERR_OVERFLOW - key value parameter is too short
*/
bcmos_errno nc_xpath_key_get(const char *xpath, const char *keyname, char *value, uint32_t value_size);
/* Copy configuration */
void nc_cfg_copy(sr_session_ctx_t *srs, const char *model, nc_datastore_type from, nc_datastore_type to);
/* Copy running configuration to startup */
static inline void nc_cfg_running_to_startup(sr_session_ctx_t *srs, const char *model)
{
nc_cfg_copy(srs, model, NC_DATASTORE_RUNNING, NC_DATASTORE_STARTUP);
}
/* Reset configuration */
void nc_cfg_reset(sr_session_ctx_t *srs, const char *model, nc_datastore_type ds);
/* Reset startup configuration */
static inline void nc_cfg_reset_startup(sr_session_ctx_t *srs, const char *model)
{
nc_cfg_reset(srs, model, NC_DATASTORE_STARTUP);
}
/* Map BAL error code to sysrepo */
int nc_bcmos_errno_to_sr_errno(bcmos_errno err);
/* Map sysrepo errno to BAL */
bcmos_errno nc_sr_errno_to_bcmos_errno(int sr_rc);
/* Error log */
void nc_error_reply(sr_session_ctx_t *srs, const char *xpath, const char *format, ...);
#define NC_ERROR_REPLY(_srs, _xpath, _format, _args...) \
do { \
if (_srs != NULL) \
nc_error_reply(_srs, _xpath, _format, ##_args); \
NC_LOG_ERR(_format "\n", ##_args); \
} while (0)
/* Add value to array of values.
* Return SR_SRR_...
*/
int nc_sr_value_add(
const char *xpath,
sr_type_t type,
const char *string_val,
sr_val_t **values,
size_t *values_cnt);
/* Add sub-value to the list of values.
* The difference from nc_sr_value_add is that xpath is built internally
* from 2 components: xpath_base and value_name
*/
int nc_sr_sub_value_add(
const char *xpath_base,
const char *value_name,
sr_type_t type,
const char *string_val,
sr_val_t **values,
size_t *values_cnt);
/* Add sub-value to the libyang context.
* The difference from nc_sr_value_add is that xpath is built internally
* from 2 components: xpath_base and value_name
*/
struct lyd_node *nc_ly_sub_value_add(
const struct ly_ctx *ctx,
struct lyd_node *parent,
const char *xpath_base,
const char *value_name,
const char *string_val);
/* Set values in datastore from sr_val_t array */
/* Add value to array of values.
* Return SR_SRR_...
*/
int nc_sr_values_set(sr_session_ctx_t *srs, sr_val_t *values, size_t values_cnt);
/* Free value pair
* Variables *p_val1 and *p_val2 are released.
* *p_val1 and *p_val2 are set =NULL
*/
void nc_sr_free_value_pair(sr_val_t **p_val1, sr_val_t **p_val2);
/* Translate binary data to hexadecimal string.
* hex buffer size must be at least (len*2 + 1)
*/
void nc_bin_to_hex(const uint8_t *bin, uint32_t bin_len, char *hex);
/* Translate binary data from hexadecimal string to binary.
* Returns the length of converted buffer >= 0
* or BCM_ERR_PARM or BCM_ERR_OVERFLOW
*/
int nc_hex_to_bin(const char *hex, uint8_t *bin, uint32_t bin_len);
/* sysrepo operation name */
const char *sr_op_name(sr_change_oper_t op);
/* find a sibling node by name */
const struct lyd_node *nc_ly_get_sibling_node(const struct lyd_node *node, const char *name);
/* find a sibling or a parent+siblings node by name */
const struct lyd_node *nc_ly_get_sibling_or_parent_node(const struct lyd_node *node, const char *name);
/*
* Save / restore transaction error
*/
void nc_sr_error_save(sr_session_ctx_t *srs, char **xpath, char **message);
void nc_sr_error_restore(sr_session_ctx_t *srs, char *xpath, char *message);
#endif /* _NETCONF2_MODULE_UTILS_H_ */
<file_sep>/*
<:copyright-BRCM:2016-2019:Apache:standard
Copyright (c) 2016-2019 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
* :>
*/
#ifndef BCMOS_ENDIAN_H_
#define BCMOS_ENDIAN_H_
#ifndef BCMOS_SYSTEM_H_
#error Please do not include bcmos_endian.h directly. Include bcmos_system.h
#endif
/** \addtogroup system_endian
* @{
*/
#ifndef BCMOS_ARCH_ENDIAN_SWAP
/** Swaps the endianness of a 16-bit integer
* \param[in] n the original number
* \return number with swapped endianness
*/
static inline uint16_t bcmos_endian_swap_u16(uint16_t n)
{
return ((n << 8 ) & 0xFF00U)|((n >> 8) & 0x00FFU);
}
/** Swaps the endianness of a 24-bit integer
* \param[in] n the original number
* \return number with swapped endianness
*/
static inline uint24_t bcmos_endian_swap_u24(uint24_t n)
{
uint24_t u8;
u8.u8[0] = n.u8[2];
u8.u8[1] = n.u8[1];
u8.u8[2] = n.u8[0];
return u8;
}
/** Swaps the endianness of a 32-bit integer
* \param[in] n the original number
* \return number with swapped endianness
*/
static inline uint32_t bcmos_endian_swap_u32(uint32_t n)
{
return ((n << 24) & 0xFF000000U)|((n << 8 ) & 0x00FF0000U)|((n >> 8) & 0x0000FF00U)|((n >> 24) & 0x000000FFU);
}
/** Swaps the endianness of a 64-bit integer
* \param[in] n the original number
* \return number with swapped endianness
*/
static inline uint64_t bcmos_endian_swap_u64(uint64_t n)
{
return (((uint64_t)bcmos_endian_swap_u32(n & 0xFFFFFFFFU) << 32) | bcmos_endian_swap_u32((n >> 32) & 0xFFFFFFFFU));
}
#endif /* BCMOS_ARCH_ENDIAN_SWAP */
#if (BCM_CPU_ENDIAN == BCMOS_ENDIAN_BIG)
#define BCMOS_ENDIAN_CPU_TO_BIG_U16(n) (n)
#define BCMOS_ENDIAN_CPU_TO_BIG_U24(n) (n)
#define BCMOS_ENDIAN_CPU_TO_BIG_U32(n) (n)
#define BCMOS_ENDIAN_CPU_TO_BIG_U64(n) (n)
#define BCMOS_ENDIAN_BIG_TO_CPU_U16(n) (n)
#define BCMOS_ENDIAN_BIG_TO_CPU_U24(n) (n)
#define BCMOS_ENDIAN_BIG_TO_CPU_U32(n) (n)
#define BCMOS_ENDIAN_BIG_TO_CPU_U64(n) (n)
#define BCMOS_ENDIAN_CPU_TO_LITTLE_U16(n) (bcmos_endian_swap_u16(n))
#define BCMOS_ENDIAN_CPU_TO_LITTLE_U24(n) (bcmos_endian_swap_u24(n))
#define BCMOS_ENDIAN_CPU_TO_LITTLE_U32(n) (bcmos_endian_swap_u32(n))
#define BCMOS_ENDIAN_CPU_TO_LITTLE_U64(n) (bcmos_endian_swap_u64(n))
#define BCMOS_ENDIAN_LITTLE_TO_CPU_U16(n) (bcmos_endian_swap_u16(n))
#define BCMOS_ENDIAN_LITTLE_TO_CPU_U24(n) (bcmos_endian_swap_u24(n))
#define BCMOS_ENDIAN_LITTLE_TO_CPU_U32(n) (bcmos_endian_swap_u32(n))
#define BCMOS_ENDIAN_LITTLE_TO_CPU_U64(n) (bcmos_endian_swap_u64(n))
#elif (BCM_CPU_ENDIAN == BCMOS_ENDIAN_LITTLE)
#define BCMOS_ENDIAN_CPU_TO_BIG_U16(n) (bcmos_endian_swap_u16(n))
#define BCMOS_ENDIAN_CPU_TO_BIG_U24(n) (bcmos_endian_swap_u24(n))
#define BCMOS_ENDIAN_CPU_TO_BIG_U32(n) (bcmos_endian_swap_u32(n))
#define BCMOS_ENDIAN_CPU_TO_BIG_U64(n) (bcmos_endian_swap_u64(n))
#define BCMOS_ENDIAN_BIG_TO_CPU_U16(n) (bcmos_endian_swap_u16(n))
#define BCMOS_ENDIAN_BIG_TO_CPU_U24(n) (bcmos_endian_swap_u24(n))
#define BCMOS_ENDIAN_BIG_TO_CPU_U32(n) (bcmos_endian_swap_u32(n))
#define BCMOS_ENDIAN_BIG_TO_CPU_U64(n) (bcmos_endian_swap_u64(n))
#define BCMOS_ENDIAN_CPU_TO_LITTLE_U16(n) (n)
#define BCMOS_ENDIAN_CPU_TO_LITTLE_U24(n) (n)
#define BCMOS_ENDIAN_CPU_TO_LITTLE_U32(n) (n)
#define BCMOS_ENDIAN_CPU_TO_LITTLE_U64(n) (n)
#define BCMOS_ENDIAN_LITTLE_TO_CPU_U16(n) (n)
#define BCMOS_ENDIAN_LITTLE_TO_CPU_U24(n) (n)
#define BCMOS_ENDIAN_LITTLE_TO_CPU_U32(n) (n)
#define BCMOS_ENDIAN_LITTLE_TO_CPU_U64(n) (n)
#else
#error BCM_CPU_ENDIAN must be BCMOS_ENDIAN_BIG or _LITTLE
#endif
/** @} system_endian */
#endif /* BCMOS_COMMON2_H_ */
<file_sep>/*
<:copyright-BRCM:2016-2019:Apache:standard
Copyright (c) 2016-2019 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
* :>
*/
#ifndef _BCMOLT_STRING_H_
#define _BCMOLT_STRING_H_
#include "bcmos_system.h"
typedef struct
{
char *str;
uint32_t max_len;
char *curr;
int32_t remaining;
} bcmolt_string;
int bcmolt_string_copy(bcmolt_string *str, const char *buf, uint32_t size);
int bcmolt_string_append(bcmolt_string *str, const char *fmt, ...);
const char *bcmolt_string_get(bcmolt_string *str);
void bcmolt_string_reset(bcmolt_string *str);
void bcmolt_string_rewind(bcmolt_string *str, int len);
void bcmolt_string_init(bcmolt_string *str, char *buf, uint32_t max_len);
/** strncpy flavour that always add 0 terminator
* \param[in] dst Destination string
* \param[in] src Source string
* \param[in] dst_size Destination buffer size
* \return dst
*/
static inline char *bcmolt_strncpy(char *dst, const char *src, uint32_t dst_size)
{
strncpy(dst, src, dst_size - 1);
dst[dst_size - 1] = 0;
return dst;
}
/** strncat flavour that limits size of destination buffer
* \param[in] dst Destination string
* \param[in] src Source string
* \param[in] dst_size Destination buffer size
* \return dst
*/
static inline char *bcmolt_strncat(char *dst, const char *src, uint32_t dst_size)
{
uint32_t dst_len = strlen(dst);
return strncat(dst, src, dst_size - dst_len - 1);
}
/** Construct a string for indentation, given a specific indentation level
* \param[in] dst Destination string
* \param[in] dst_size Destination buffer size
* \param[in] indent_level Indentation level
* \return dst
*/
char *bcmolt_string_indent(char *dst, uint32_t dst_size, uint32_t indent_level);
#endif /* _BCMOLT_STRING_H_ */
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#include <bcm_tr451_polt_internal.h>
#include <fstream>
extern "C"
{
#include <bcmos_hash_table.h>
}
dev_log_id bcm_polt_log_id;
static bool subsystem_enabled[2];
//
// bcmos_errno to Status translation
//
grpc::Status tr451_bcm_errno_grpc_status(bcmos_errno err, const char *fmt, ...)
{
const char *err_text;
if (err == BCM_ERR_OK)
return Status::OK;
StatusCode code;
switch(err)
{
case BCM_ERR_ALREADY:
code = StatusCode::ALREADY_EXISTS;
break;
case BCM_ERR_NOENT:
code = StatusCode::NOT_FOUND;
break;
case BCM_ERR_PARM:
code = StatusCode::INVALID_ARGUMENT;
break;
case BCM_ERR_NORES:
code = StatusCode::UNAVAILABLE;
break;
case BCM_ERR_IN_PROGRESS:
code = StatusCode::ABORTED;
break;
case BCM_ERR_NOT_SUPPORTED:
code = StatusCode::UNIMPLEMENTED;
break;
case BCM_ERR_RANGE:
code = StatusCode::OUT_OF_RANGE;
break;
case BCM_ERR_INTERNAL:
code = StatusCode::INTERNAL;
break;
case BCM_ERR_NOT_CONNECTED:
code = StatusCode::FAILED_PRECONDITION;
break;
default:
code = StatusCode::UNKNOWN;
break;
}
char err_buff[256];
if (fmt == nullptr || !strlen(fmt))
{
err_text = bcmos_strerror(err);
}
else
{
va_list ap;
va_start(ap, fmt);
vsnprintf(err_buff, sizeof(err_buff)-1, fmt, ap);
va_end(ap);
err_buff[sizeof(err_buff)-1] = 0;
err_text = err_buff;
}
return grpc::Status(code, string(err_text));
}
//
// Filter service declaration
//
class OnuFilterSet
{
public:
class FilterEntry
{
public:
FilterEntry(const tr451_polt_filter *flt, const char *endpoint_name) :
name_(flt->name), endpoint_name_(endpoint_name)
{
filter = *flt;
}
bool isMatch(const tr451_polt_onu_serial_number *serial_number)
{
if (filter.type == TR451_FILTER_TYPE_ANY)
{
BCM_POLT_LOG(DEBUG, "isMatch ANY : %c%c%c%c%02X%02X%02X%02X\n",
serial_number->data[0], serial_number->data[1], serial_number->data[2], serial_number->data[3],
serial_number->data[4], serial_number->data[5], serial_number->data[6], serial_number->data[7]);
return true;
}
if (filter.type == TR451_FILTER_TYPE_VENDOR_ID)
{
BCM_POLT_LOG(DEBUG, "isMatch VENDOR %c%c%c%c : %c%c%c%c%02X%02X%02X%02X\n",
filter.serial_number[0], filter.serial_number[1], filter.serial_number[2], filter.serial_number[3],
serial_number->data[0], serial_number->data[1], serial_number->data[2], serial_number->data[3],
serial_number->data[4], serial_number->data[5], serial_number->data[6], serial_number->data[7]);
return (memcmp(&serial_number->data[0], &filter.serial_number[0], 4) == 0);
}
if (filter.type == TR451_FILTER_TYPE_SERIAL_NUMBER)
{
BCM_POLT_LOG(DEBUG, "isMatch SERIAL %c%c%c%c%02X%02X%02X%02X : %c%c%c%c%02X%02X%02X%02X\n",
filter.serial_number[0], filter.serial_number[1], filter.serial_number[2], filter.serial_number[3],
filter.serial_number[4], filter.serial_number[5], filter.serial_number[6], filter.serial_number[7],
serial_number->data[0], serial_number->data[1], serial_number->data[2], serial_number->data[3],
serial_number->data[4], serial_number->data[5], serial_number->data[6], serial_number->data[7]);
return (memcmp(&serial_number->data[0], &filter.serial_number[0], sizeof(serial_number->data)) == 0);
}
return false;
}
const char *name() { return name_.c_str(); }
const char *endpoint_name() { return endpoint_name_.length() ? endpoint_name_.c_str() : nullptr; }
tr451_polt_filter filter;
STAILQ_ENTRY(FilterEntry) next;
private:
string name_;
string endpoint_name_;
};
private:
void FilterInsert_(FilterEntry *entry)
{
FilterEntry *prev = NULL;
FilterEntry *tmp;
tmp = STAILQ_FIRST(&filter_list_);
while (tmp && tmp->filter.priority <= entry->filter.priority)
{
prev = tmp;
tmp = STAILQ_NEXT(tmp, next);
}
if (prev != nullptr)
STAILQ_INSERT_AFTER(&filter_list_, prev, entry, next);
else
STAILQ_INSERT_HEAD(&filter_list_, entry, next);
}
STAILQ_HEAD(, FilterEntry) filter_list_;
public:
OnuFilterSet()
{
STAILQ_INIT(&filter_list_);
}
// Add filter entry
void FilterSet(const tr451_polt_filter *filter, const char *endpoint_name);
FilterEntry *FilterGet(const char *name)
{
FilterEntry *entry, *tmp;
STAILQ_FOREACH_SAFE(entry, &filter_list_, next, tmp)
{
if (!strcmp(entry->name(), name))
break;
}
return entry;
}
void FilterDelete(FilterEntry *entry);
// Find vOMCI client/server by ONU serial number
bool FindConnectedFilter(const tr451_polt_onu_serial_number *serial_number,
FilterEntry **p_filter, VomciConnection **p_conn);
bool UpdateOnuAssignmentsFilterAdded(FilterEntry *entry);
bool UpdateOnuAssignmentsFilterRemoved(FilterEntry *entry);
FilterEntry *GetNextByEndpoint(FilterEntry *entry, const char *endpoint)
{
entry = (entry != nullptr) ? STAILQ_NEXT(entry, next) : STAILQ_FIRST(&filter_list_);
while (entry != nullptr && entry->endpoint_name() != nullptr && strcmp(endpoint, entry->endpoint_name()))
entry = STAILQ_NEXT(entry, next);
return entry;
}
};
// Endpoint filters set
static OnuFilterSet filter_set;
// Add server filter
bcmos_errno bcm_tr451_polt_filter_set(const tr451_polt_filter *filter, const char *endpoint_name)
{
// Look up filter. Update if exists, add if doesn't
filter_set.FilterSet(filter, endpoint_name);
return BCM_ERR_OK;
}
// Get filter
bcmos_errno bcm_tr451_polt_filter_get(const char *filter_name, tr451_polt_filter *filter)
{
if (filter_name == nullptr)
return BCM_ERR_PARM;
OnuFilterSet::FilterEntry *entry = filter_set.FilterGet(filter_name);
if (entry == nullptr)
return BCM_ERR_NOENT;
if (filter != nullptr)
*filter = entry->filter;
return BCM_ERR_OK;
}
// Delete filter
bcmos_errno bcm_tr451_polt_filter_delete(const char *filter_name)
{
if (filter_name == nullptr)
return BCM_ERR_PARM;
OnuFilterSet::FilterEntry *entry = filter_set.FilterGet(filter_name);
if (entry == nullptr)
return BCM_ERR_NOENT;
filter_set.FilterDelete(entry);
return BCM_ERR_OK;
}
//
// Active ONU data base
//
static hash_table *onu_info_table;
typedef struct
{
#define TR451_POLT_MAX_CTERM_NAME_LENGTH 30
char cterm_name[TR451_POLT_MAX_CTERM_NAME_LENGTH];
uint16_t onu_id;
} onu_info_key;
static void onu_info_make_key(const char *cterm_name, uint16_t onu_id, onu_info_key *key)
{
memset(&key->cterm_name[0], 0, sizeof(key->cterm_name));
strncpy(&key->cterm_name[0], cterm_name, sizeof(key->cterm_name));
key->onu_id = onu_id;
}
class OnuInfo
{
public:
OnuInfo(const char *cterm_name,
uint16_t onu_id,
const tr451_polt_onu_serial_number *serial_number) :
vomci(nullptr), filter(nullptr),
cterm_name_(cterm_name), onu_id_(onu_id), _endpoint_name()
{
onu_info_key key;
onu_info_make_key(cterm_name, onu_id, &key);
OnuInfo *obj = this;
hash_table_put(onu_info_table, (uint8_t *)&key, &obj);
if (serial_number != nullptr)
serial_number_ = *serial_number;
else
memset(&serial_number_, 0, sizeof(serial_number_));
reset_counters();
BCM_POLT_LOG(DEBUG, "Added onu %s.%u\n", cterm_name, onu_id);
}
~OnuInfo()
{
onu_info_key key;
onu_info_make_key(cterm_name_.c_str(), onu_id_, &key);
hash_table_remove(onu_info_table, (uint8_t *)&key);
BCM_POLT_LOG(DEBUG, "Deleted onu %s.%u\n", cterm_name_.c_str(), onu_id_);
}
void AssignEndpoint(VomciConnection *conn, OnuFilterSet::FilterEntry *filt)
{
filter = filt;
if (conn != vomci)
{
BCM_POLT_LOG(INFO, "ONU %s:%u is assigned to remote endpoint %s using filter '%s'\n",
cterm_name(), onu_id(), (conn != nullptr) ? conn->name() : "<none>",
(filt != nullptr) ? filt->name() : "<none>");
}
vomci = conn;
}
const tr451_polt_onu_serial_number *serial_number() const { return &serial_number_; }
const char *cterm_name() const { return cterm_name_.c_str(); }
uint16_t onu_id() const { return onu_id_; }
void endpoint_name_set(const char *endpoint_name) { _endpoint_name = endpoint_name; }
const char *endpoint_name() { return (_endpoint_name.length() > 0) ? _endpoint_name.c_str() : nullptr; }
void reset_counters() {
in_messages = out_messages = message_errors = 0;
}
bool isConnected() {
return vomci != nullptr && vomci->isConnected();
}
VomciConnection *vomci;
OnuFilterSet::FilterEntry *filter;
uint64_t in_messages;
uint64_t out_messages;
uint64_t message_errors;
private:
string cterm_name_;
uint16_t onu_id_;
tr451_polt_onu_serial_number serial_number_;
string _endpoint_name;
};
static OnuInfo *onu_info_get(const char *cterm_name, uint16_t onu_id)
{
onu_info_key key;
OnuInfo **pp_onu_info;
if (cterm_name == nullptr || onu_id >= TR451_POLT_MAX_ONUS_PER_PON)
return NULL;
onu_info_make_key(cterm_name, onu_id, &key);
pp_onu_info = (OnuInfo **)hash_table_get(onu_info_table, (uint8_t *)&key);
if (pp_onu_info == nullptr)
return nullptr;
return *pp_onu_info;
}
static void onu_info_set(const char *cterm_name,
uint16_t onu_id,
const tr451_polt_onu_serial_number *serial_number,
OnuFilterSet::FilterEntry *filter,
VomciConnection *vomci)
{
BUG_ON(cterm_name == nullptr || onu_id >= TR451_POLT_MAX_ONUS_PER_PON);
OnuInfo *onu_info = onu_info_get(cterm_name, onu_id);
if (onu_info == nullptr)
{
onu_info = new OnuInfo(cterm_name, onu_id, serial_number);
}
onu_info->AssignEndpoint(vomci, filter);
}
static OnuInfo *onu_info_get_next(ht_iterator *iter)
{
if (!ht_iterator_next(iter))
return nullptr;
uint8_t *key;
OnuInfo **pp_info;
ht_iterator_deref(iter, &key, (void **)&pp_info);
return (pp_info != nullptr) ? *pp_info : nullptr;
}
// Create an explicit association between v-ani and vomci-endpoint */
bcmos_errno xpon_v_ani_vomci_endpoint_set(const char *cterm_name, uint16_t onu_id, const char *endpoint_name)
{
BUG_ON(cterm_name == nullptr || onu_id >= TR451_POLT_MAX_ONUS_PER_PON);
OnuInfo *onu_info = onu_info_get(cterm_name, onu_id);
if (onu_info == nullptr)
{
onu_info = new OnuInfo(cterm_name, onu_id, nullptr);
}
onu_info->endpoint_name_set(endpoint_name);
return BCM_ERR_OK;
}
// Clear an explicit association between v-ani and vomci-endpoint */
bcmos_errno xpon_v_ani_vomci_endpoint_clear(const char *cterm_name, uint16_t onu_id)
{
return xpon_v_ani_vomci_endpoint_set(cterm_name, onu_id, nullptr);
}
//
// Filter Service implementation
//
// Find channel assignment
static bool find_channel_assignment(const tr451_polt_onu_serial_number *serial_number,
OnuFilterSet::FilterEntry **p_filter, VomciConnection **p_vomci)
{
*p_filter = nullptr;
*p_vomci = nullptr;
bool assigned = filter_set.FindConnectedFilter(serial_number, p_filter, p_vomci);
return assigned;
}
void OnuFilterSet::FilterSet(const tr451_polt_filter *filter, const char *endpoint_name)
{
FilterEntry *entry = FilterGet(filter->name);
if (entry != nullptr)
{
FilterDelete(entry);
}
entry = new FilterEntry(filter, endpoint_name);
FilterInsert_(entry);
BCM_POLT_LOG(DEBUG, "Added filter %s --> %s\n", entry->name(), endpoint_name);
// Update ONU assignments
if (entry->endpoint_name() != nullptr)
UpdateOnuAssignmentsFilterAdded(entry);
}
void OnuFilterSet::FilterDelete(FilterEntry *entry)
{
BCM_POLT_LOG(DEBUG, "Deleted filter %s\n", entry->name());
STAILQ_REMOVE_SAFE(&filter_list_, entry, FilterEntry, next);
UpdateOnuAssignmentsFilterRemoved(entry);
delete entry;
}
// Find vOMCI client/server by ONU serial number
bool OnuFilterSet::FindConnectedFilter(const tr451_polt_onu_serial_number *serial_number,
FilterEntry **p_filter, VomciConnection **p_conn)
{
FilterEntry *entry, *tmp;
VomciConnection *conn = nullptr;
STAILQ_FOREACH_SAFE(entry, &filter_list_, next, tmp)
{
BCM_POLT_LOG(DEBUG, "Checking filter %s: %s\n",
entry->name(), entry->isMatch(serial_number) ? "match" : "mismatch");
if (!entry->isMatch(serial_number))
continue;
conn = vomci_connection_get_by_name(entry->endpoint_name());
if (conn != nullptr && conn->isConnected())
break;
conn = nullptr;
}
*p_conn = conn;
*p_filter = entry;
return (conn != nullptr);
}
bool OnuFilterSet::UpdateOnuAssignmentsFilterAdded(FilterEntry *entry)
{
bool updated = false;
if (entry->endpoint_name() == nullptr)
return false;
VomciConnection *conn = vomci_connection_get_by_name(entry->endpoint_name());
if (conn == nullptr || !conn->isConnected())
return false;
// Added active filter. Update matching ONUs
ht_iterator iter = ht_iterator_get(onu_info_table);
OnuInfo *info = onu_info_get_next(&iter);
while (info != nullptr)
{
// Skip ONUs for which endpoint name is set explictly in v-ani
if (info->endpoint_name() != nullptr)
{
info = onu_info_get_next(&iter);
continue;
}
if (entry->isMatch(info->serial_number()) &&
(info->filter == nullptr || entry->filter.priority < info->filter->filter.priority))
{
info->AssignEndpoint(conn, entry);
updated = true;
}
info = onu_info_get_next(&iter);
}
return updated;
}
bool OnuFilterSet::UpdateOnuAssignmentsFilterRemoved(FilterEntry *entry)
{
bool updated = false;
// Removed filter. Update matching ONUs
ht_iterator iter = ht_iterator_get(onu_info_table);
OnuInfo *info = onu_info_get_next(&iter);
while (info != nullptr)
{
// Skip ONUs for which endpoint name is set explictly in v-ani
if (info->endpoint_name() != nullptr)
{
info = onu_info_get_next(&iter);
continue;
}
const VomciConnection *old_conn = info->vomci;
if (info->filter == entry)
{
updated |= find_channel_assignment(info->serial_number(), &info->filter, &info->vomci);
}
if (old_conn != info->vomci)
{
info->AssignEndpoint(info->vomci, info->filter);
}
info = onu_info_get_next(&iter);
}
return updated;
}
//
// common Client/Server handling
//
static STAILQ_HEAD(, VomciConnection) connection_list;
static STAILQ_HEAD(, GrpcProcessor) client_server_list;
/* Find connection by name, whereas name is
- endpoint name for client connection
- remote endpoint name for server connection
*/
VomciConnection *vomci_connection_get_by_name(const char *name, const GrpcProcessor *owner)
{
VomciConnection *conn, *tmp;
BCM_POLT_LOG(DEBUG, "Looking for connection with remote-endpoint name '%s'. Owner: '%s'\n",
name, owner ? owner->name() : "<null>");
STAILQ_FOREACH_SAFE(conn, &connection_list, next, tmp)
{
const char *remote_endpoint_name = conn->remote_endpoint_name();
BCM_POLT_LOG(DEBUG, "..checking connection '%s': remote-endpoint='%s' parent='%s'\n",
conn->name(), remote_endpoint_name, conn->parent()->name());
if ((owner == nullptr || conn->parent() == owner) && !strcmp(name, remote_endpoint_name))
break;
}
BCM_POLT_LOG(DEBUG, "Found connection '%s'. Connected=%d\n",
conn ? conn->name() : "<null>", conn ? conn->isConnected() : false);
return conn;
}
VomciConnection *vomci_connection_get_by_peer(const char *peer, const GrpcProcessor *owner)
{
VomciConnection *conn, *tmp;
STAILQ_FOREACH_SAFE(conn, &connection_list, next, tmp)
{
if ((owner == nullptr || conn->parent() == owner) && !strcmp(peer, conn->peer()))
break;
}
return conn;
}
VomciConnection *vomci_connection_get_next(VomciConnection *prev, const GrpcProcessor *owner)
{
VomciConnection *conn = (prev != nullptr) ? STAILQ_NEXT(prev, next) : STAILQ_FIRST(&connection_list);
while (conn != nullptr && (owner != nullptr && conn->parent() != owner))
conn = STAILQ_NEXT(conn, next);
return conn;
}
static int grpc_processor_task_handler(long data)
{
GrpcProcessor *client_server = (GrpcProcessor *)data;
BCM_POLT_LOG(INFO, "pOLT %s %s started\n",
client_server->type_name(), client_server->name());
// Start client/server. Never returns until the client/server is terminated
client_server->Start();
return 0;
}
GrpcProcessor *bcm_grpc_processor_get_by_name(const char *name, GrpcProcessor::processor_type type)
{
GrpcProcessor *entry, *tmp;
STAILQ_FOREACH_SAFE(entry, &client_server_list, next, tmp)
{
if (!strcmp(name, entry->name()) && entry->type() == type)
break;
}
return entry;
}
static bcm_tr451_polt_grpc_server_connect_disconnect_cb vomci_server_conn_discon_cb;
static void *vomci_server_conn_discon_cb_data;
static bcm_tr451_polt_grpc_client_connect_disconnect_cb vomci_client_conn_discon_cb;
static void *vomci_client_conn_discon_cb_data;
bcmos_errno bcm_tr451_polt_grpc_server_connect_disconnect_cb_register(
bcm_tr451_polt_grpc_server_connect_disconnect_cb cb, void *data)
{
vomci_server_conn_discon_cb = cb;
vomci_server_conn_discon_cb_data = data;
return BCM_ERR_OK;
}
bcmos_errno bcm_tr451_polt_grpc_client_connect_disconnect_cb_register(
bcm_tr451_polt_grpc_client_connect_disconnect_cb cb, void *data)
{
vomci_client_conn_discon_cb = cb;
vomci_client_conn_discon_cb_data = data;
return BCM_ERR_OK;
}
void vomci_notify_connect_disconnect(VomciConnection *conn, bool is_connected)
{
// Notify only for server endpoints
if (conn->parent()->type() == GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_SERVER &&
vomci_server_conn_discon_cb != nullptr)
{
vomci_server_conn_discon_cb(vomci_server_conn_discon_cb_data,
conn->parent()->name(), conn->name(), is_connected);
}
if (conn->parent()->type() == GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_CLIENT &&
vomci_client_conn_discon_cb != nullptr)
{
vomci_client_conn_discon_cb(vomci_client_conn_discon_cb_data,
conn->parent()->name(), conn->endpoint(), is_connected);
}
}
static OnuInfo *vomci_get_by_omci_packet(const OmciPacket &grpc_omci_packet)
{
uint16_t onu_id;
onu_id = (uint16_t)grpc_omci_packet.header().onu_id();
if (onu_id >= TR451_POLT_MAX_ONUS_PER_PON)
{
BCM_POLT_LOG(ERROR, "onu_id %u is insane\n", onu_id);
return nullptr;
}
// Identify OnuInfo record
return onu_info_get(grpc_omci_packet.header().chnl_term_name().c_str(), onu_id);
}
/*
* GrpcProcessor class - the base class of both BcmPoltServer and BcmPoltClient
*/
GrpcProcessor::GrpcProcessor(processor_type type, const char *ep_name) :
type_(type), endpoint_name_(ep_name), started_(false)
{
STAILQ_INSERT_TAIL(&client_server_list, this, next);
stopping = false;
}
// Create client/server task and start client/server
bcmos_errno GrpcProcessor::CreateTaskAndStart()
{
bcmos_task_parm tp = {};
bcmos_errno err;
stopping = false;
// Create task that will handle this endpoint
tp.name = "polt_client_server";
tp.priority = TASK_PRIORITY_VOMCI_DOLT_CLIENT;
tp.handler = grpc_processor_task_handler;
tp.data = (long)this;
err = bcmos_task_create(&this->task_, &tp);
if (err != BCM_ERR_OK)
{
return err;
}
started_ = true;
return BCM_ERR_OK;
}
void GrpcProcessor::Stop()
{
if (!started_)
return;
bcmos_task_destroy(&this->task_);
started_ = false;
}
GrpcProcessor::~GrpcProcessor()
{
Stop();
STAILQ_REMOVE_SAFE(&client_server_list, this, GrpcProcessor, next);
}
Status GrpcProcessor::OmciTxToOnu(const OmciPacket &grpc_omci_packet, const char *peer)
{
bcmos_errno err;
OnuInfo *onu = vomci_get_by_omci_packet(grpc_omci_packet);
VomciConnection *conn = (onu != nullptr) ? onu->vomci : nullptr;
if (conn==nullptr)
{
grpc::Status status = tr451_bcm_errno_grpc_status(BCM_ERR_NOENT,
"%s: Can't send OMCI message to vOMCI. No connection. ONU %s:%u\n",
name(), grpc_omci_packet.header().chnl_term_name().c_str(), grpc_omci_packet.header().onu_id());
BCM_POLT_LOG(ERROR, "%s:\n", status.error_message().c_str());
return status;
}
++conn->stats.packets_vomci_to_onu_recv;
++onu->in_messages;
err = tr451_vendor_omci_send_to_onu(grpc_omci_packet);
if (err != BCM_ERR_OK)
{
grpc::Status status = tr451_bcm_errno_grpc_status(err,
"Failed to send OMCI message to ONU %s:%u. Error '%s'",
grpc_omci_packet.header().chnl_term_name().c_str(), grpc_omci_packet.header().onu_id(),
bcmos_strerror(err));
++conn->stats.packets_vomci_to_onu_disc;
++onu->message_errors;
BCM_POLT_LOG(ERROR, "%s:\n", status.error_message().c_str());
return status;
}
BCM_POLT_LOG(DEBUG, "Sent OMCI message to ONU %s:%u. %lu bytes\n",
grpc_omci_packet.header().chnl_term_name().c_str(), grpc_omci_packet.header().onu_id(),
grpc_omci_packet.payload().length());
++conn->stats.packets_vomci_to_onu_sent;
return Status::OK;
}
//
// VomciConnection
//
VomciConnection::VomciConnection(GrpcProcessor *parent,
const string &endpoint,
const string &local_name,
const string &vomci_name,
const string &vomci_address) :
parent_(parent) , name_(vomci_name), peer_(vomci_address),
endpoint_(endpoint), local_name_(local_name), connected_(false)
{
memset(&stats, 0, sizeof(stats));
bcmos_mutex_create(&conn_lock_, 0, "vomci");
bcmos_mutex_create(&omci_ind_lock, 0, "omci_ind");
bcmos_sem_create(&omci_ind_sem, 0, 0, "omci_ind");
STAILQ_INIT(&omci_ind_list);
STAILQ_INSERT_TAIL(&connection_list, this, next);
}
VomciConnection::~VomciConnection()
{
STAILQ_REMOVE_SAFE(&connection_list, this, VomciConnection, next);
if (connected_)
{
setConnected(false);
bcmos_sem_post(&omci_ind_sem);
}
OmciPacketEntry *omci_packet;
bcmos_mutex_lock(&omci_ind_lock);
while ((omci_packet = STAILQ_FIRST(&omci_ind_list)))
{
STAILQ_REMOVE_HEAD(&omci_ind_list, next);
delete omci_packet;
}
bcmos_mutex_unlock(&omci_ind_lock);
bcmos_sem_destroy(&omci_ind_sem);
bcmos_mutex_destroy(&omci_ind_lock);
bcmos_mutex_destroy(&conn_lock_);
}
void VomciConnection::setConnected(bool connected)
{
if (connected == connected_)
return;
bcmos_mutex_lock(&conn_lock_);
connected_ = connected;
bcmos_mutex_unlock(&conn_lock_);
vomci_notify_connect_disconnect(this, connected);
if (connected)
UpdateOnuAssignmentsConnected();
else
UpdateOnuAssignmentsDisconnected();
}
// Enque packet received from ONU.
// Eventually it will be popped using PopPacketFromOnuFromTxQueue and transmitted to vOMCI peer
bool VomciConnection::OmciRxFromOnu(OmciPacketEntry *omci_packet)
{
bool ret;
bcmos_mutex_lock(&conn_lock_);
if (connected_)
{
bcmos_mutex_lock(&omci_ind_lock);
STAILQ_INSERT_TAIL(&omci_ind_list, omci_packet, next);
// Kick thread that unwinds the queue if the queue was empty
if (STAILQ_FIRST(&omci_ind_list) == omci_packet)
bcmos_sem_post(&omci_ind_sem);
bcmos_mutex_unlock(&omci_ind_lock);
++stats.packets_onu_to_vomci_recv;
ret = true;
}
else
{
BCM_POLT_LOG(DEBUG, "vOMCI %s: Failed to send OMCI RX message from %s:%u. Not connected\n",
name_.c_str(), omci_packet->header().chnl_term_name().c_str(), omci_packet->header().onu_id());
delete omci_packet;
++stats.packets_onu_to_vomci_disc;
ret = false;
}
bcmos_mutex_unlock(&conn_lock_);
return ret;
}
// Pop packet received from ONU from vomci connection's TX queue
OmciPacketEntry *VomciConnection::PopPacketFromOnuFromTxQueue(void)
{
OmciPacketEntry *omci_packet;
bcmos_mutex_lock(&omci_ind_lock);
omci_packet = STAILQ_FIRST(&omci_ind_list);
if (omci_packet != nullptr)
{
STAILQ_REMOVE_HEAD(&omci_ind_list, next);
}
bcmos_mutex_unlock(&omci_ind_lock);
return omci_packet;
}
// Connected. It might affect ONU channel assignment
void VomciConnection::UpdateOnuAssignmentsConnected()
{
const char *remote_endpoint_name = this->remote_endpoint_name();
// Assign ONUs with vomci-endpoint explicitly assigned in v-ani
ht_iterator iter = ht_iterator_get(onu_info_table);
OnuInfo *info = onu_info_get_next(&iter);
while (info != nullptr)
{
if (info->endpoint_name() != nullptr && remote_endpoint_name != nullptr &&
!strcmp(info->endpoint_name(), remote_endpoint_name))
{
info->AssignEndpoint(this, nullptr);
}
info = onu_info_get_next(&iter);
}
// Assign by filter
OnuFilterSet::FilterEntry *filter = nullptr;
while ((filter = filter_set.GetNextByEndpoint(filter, remote_endpoint_name)) != nullptr)
filter_set.UpdateOnuAssignmentsFilterAdded(filter);
}
// Disconnected. It might affect ONU channel assignment
void VomciConnection::UpdateOnuAssignmentsDisconnected()
{
const char *remote_endpoint_name = this->remote_endpoint_name();
// Assign ONUs with vomci-endpoint explicitly assigned in v-ani
ht_iterator iter = ht_iterator_get(onu_info_table);
OnuInfo *info = onu_info_get_next(&iter);
while (info != nullptr)
{
if (info->endpoint_name() != nullptr && remote_endpoint_name != nullptr &&
!strcmp(info->endpoint_name(), remote_endpoint_name))
{
info->AssignEndpoint(nullptr, nullptr);
}
info = onu_info_get_next(&iter);
}
// Assign by filter
OnuFilterSet::FilterEntry *filter = nullptr;
while ((filter = filter_set.GetNextByEndpoint(filter, remote_endpoint_name)) != nullptr)
filter_set.UpdateOnuAssignmentsFilterRemoved(filter);
}
//
// External services
//
// Enable server subsystem
bcmos_errno bcm_grpc_processor_enable_disable(bool enable, GrpcProcessor::processor_type type)
{
GrpcProcessor *entry, *tmp;
BCM_POLT_LOG(INFO, "%s %s subsystem..\n",
enable ? "Enabling" : "Disabling",
(type == GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_SERVER) ? "server" : "client");
STAILQ_FOREACH_SAFE(entry, &client_server_list, next, tmp)
{
if (entry->type() == type)
{
if (enable)
{
if (!entry->isStarted())
entry->CreateTaskAndStart();
}
else
{
entry->Stop();
}
}
}
subsystem_enabled[(int)type] = enable;
return BCM_ERR_OK;;
}
bool bcm_grpc_processor_is_enabled(GrpcProcessor::processor_type type)
{
return subsystem_enabled[(int)type];
}
//
// Debug functions
//
void bcm_tr451_stats_get(const char **endpoint_name, const char **peer_name, VomciConnectionStats *stats)
{
const char *prev_name=*endpoint_name;
VomciConnection *conn = nullptr;
memset(stats, 0, sizeof(*stats));
*endpoint_name = nullptr;
*peer_name = nullptr;
if (prev_name != nullptr)
{
conn = vomci_connection_get_by_name(prev_name, nullptr);
if (conn == nullptr)
return;
}
conn = vomci_connection_get_next(conn, nullptr);
if (conn == nullptr)
return;
*stats = conn->stats;
*endpoint_name = conn->endpoint();
*peer_name = conn->name();
}
//
// ONU status change notification
//
static xpon_v_ani_state_change_report_cb tr451_onu_status_change_cb;
bcmos_errno bcm_tr451_onu_state_change_notify_cb_register(xpon_v_ani_state_change_report_cb cb)
{
tr451_onu_status_change_cb = cb;
return BCM_ERR_OK;
}
//
// Vendor event callbacks
//
// OMCI packet received from ONU callback.
// It is the responsibility of this callback to release packet when no longer needed
static void tr451_polt_omci_rx_cb(void *user_handle, OmciPacketEntry *packet)
{
// Find vomci connection
OnuInfo *onu = vomci_get_by_omci_packet(*packet);
VomciConnection *conn = (onu != nullptr ) ? onu->vomci : nullptr;
bool is_sent;
if (conn == nullptr)
{
BCM_POLT_LOG(ERROR, "Can't forward OMCI packet from ONU %s:%u to vOMCI. No connection\n",
packet->header().chnl_term_name().c_str(), packet->header().onu_id());
++onu->message_errors;
delete packet;
return;
}
packet->mutable_header()->set_olt_name(conn->local_name());
// Push to vOMCI connection tranmsit queue
is_sent = conn->OmciRxFromOnu(packet);
if (is_sent)
++onu->out_messages;
else
++onu->message_errors;
}
/**
* @brief Callback function to be called upon ONU state change
*/
static void tr451_polt_onu_state_change_cb(void *user_handle, const tr451_polt_onu_info *vendor_onu_info)
{
if (vendor_onu_info->cterm_name == nullptr)
{
BCM_POLT_LOG(ERROR, "cterm_name must be set. tr451_onu_state_change_cb event is ignored\n");
return;
}
if (vendor_onu_info->onu_id >= TR451_POLT_MAX_ONUS_PER_PON)
{
BCM_POLT_LOG(ERROR, "onu_id %u is > %u. tr451_onu_state_change_cb event is ignored\n",
vendor_onu_info->onu_id, TR451_POLT_MAX_ONUS_PER_PON);
return;
}
OnuInfo *onu_info = onu_info_get(vendor_onu_info->cterm_name, vendor_onu_info->onu_id);
// Removed ?
if ((vendor_onu_info->presence_flags & XPON_ONU_PRESENCE_FLAG_ONU) == 0)
{
if (onu_info != nullptr)
delete onu_info;
return;
}
OnuFilterSet::FilterEntry *filter;
VomciConnection *vomci;
find_channel_assignment(&vendor_onu_info->serial_number, &filter, &vomci);
// Register in onu_info
onu_info_set(vendor_onu_info->cterm_name, vendor_onu_info->onu_id,
&vendor_onu_info->serial_number, filter, vomci);
}
// Report ONU state change to NETCONF server.
// Usually it is only needed when adding ONU via CLI for debugging
static bcmos_errno tr451_polt_onu_state_change_notify_cb(void *user_handle, const tr451_polt_onu_info *onu_info)
{
if (tr451_onu_status_change_cb == nullptr)
return BCM_ERR_OK;
bcmos_errno err;
err = tr451_onu_status_change_cb(
onu_info->cterm_name, onu_info->onu_id,
onu_info->serial_number.data, onu_info->presence_flags);
return err;
}
//
// Initialization
//
static bool polt_initialized;
bcmos_errno bcm_tr451_polt_init(const tr451_polt_init_parms *init_parms)
{
bcmos_errno err;
if (polt_initialized)
return BCM_ERR_ALREADY;
bcm_polt_log_id = bcm_dev_log_id_register("POLT", init_parms->log_level, DEV_LOG_ID_TYPE_BOTH);
bcm_tr451_polt_cli_init();
// Create ONU info hash
onu_info_table = hash_table_create(
TR451_POLT_MAX_PONS_PER_OLT * TR451_POLT_MAX_ONUS_PER_PON,
sizeof(OnuInfo),
sizeof(onu_info_key),
(char *)"active_onu_table");
if (onu_info_table == nullptr)
return BCM_ERR_NOMEM;
// Initialize vendor interface
err = tr451_vendor_init();
// Register for vendor events
tr451_vendor_event_cfg vendor_event_cfg = {};
vendor_event_cfg.tr451_omci_rx_cb = tr451_polt_omci_rx_cb;
vendor_event_cfg.tr451_onu_state_change_cb = tr451_polt_onu_state_change_cb;
vendor_event_cfg.tr451_onu_state_change_notify_cb = tr451_polt_onu_state_change_notify_cb;
tr451_vendor_event_register(&vendor_event_cfg);
// Initialize client and server
STAILQ_INIT(&connection_list);
STAILQ_INIT(&client_server_list);
err = err ? err : bcm_tr451_polt_grpc_server_init();
err = err ? err : bcm_tr451_polt_grpc_client_init();
polt_initialized = true;
return err;
}
//
// client endpoints helper functions
//
tr451_client_endpoint *bcm_tr451_client_endpoint_alloc(const char *name)
{
tr451_client_endpoint *ep;
char *name_copy;
if (name == nullptr)
return nullptr;
ep = (tr451_client_endpoint *)bcmos_calloc(sizeof(tr451_client_endpoint) + strlen(name) + 1);
if (ep == nullptr)
return nullptr;
STAILQ_INIT(&ep->entry_list);
ep->name = name_copy = (char *)(ep + 1);
strcpy(name_copy, name);
BCM_POLT_LOG(DEBUG, "Allocated client endpoint %s\n", name);
return ep;
}
bcmos_errno bcm_tr451_client_endpoint_add_entry(tr451_client_endpoint *ep, const tr451_endpoint *entry)
{
uint32_t alloc_len = sizeof(tr451_endpoint);
tr451_endpoint *e;
char *name_copy;
if (ep == nullptr || entry == nullptr)
return BCM_ERR_PARM;
if (entry->name != nullptr)
alloc_len += strlen(entry->name) + 1;
if (entry->host_name != nullptr)
alloc_len += strlen(entry->host_name) + 1;
e = (tr451_endpoint *)bcmos_calloc(alloc_len);
if (e == nullptr)
return BCM_ERR_NOMEM;
name_copy = (char *)(e + 1);
if (entry->name != nullptr)
{
e->name = name_copy;
strcpy(name_copy, entry->name);
name_copy += strlen(entry->name) + 1;
}
if (entry->host_name != nullptr)
{
e->host_name = name_copy;
strcpy(name_copy, entry->host_name);
}
e->port = entry->port;
STAILQ_INSERT_TAIL(&ep->entry_list, e, next);
BCM_POLT_LOG(DEBUG, "Edded entry to client endpoint %s: %s host-name=%s port=%u\n",
ep->name, entry->name, entry->host_name, entry->port);
return BCM_ERR_OK;
}
void bcm_tr451_client_endpoint_free(tr451_client_endpoint *ep)
{
tr451_endpoint *e;
if (ep == nullptr)
return;
BCM_POLT_LOG(DEBUG, "Released client endpoint %s\n", ep->name);
while ((e = STAILQ_FIRST(&ep->entry_list)) != nullptr)
{
STAILQ_REMOVE_HEAD(&ep->entry_list, next);
bcmos_free(e);
}
bcmos_free(ep);
}
bcmos_errno bcm_tr451_onu_status_get(const char *cterm_name, uint16_t onu_id,
bbf_vomci_communication_status *status, const char **remote_endpoint,
uint64_t *in_messages, uint64_t *out_messages, uint64_t *message_errors)
{
OnuInfo *onu_info = onu_info_get(cterm_name, onu_id);
if (onu_info == nullptr)
return BCM_ERR_NOENT;
const char *onu_endpoint = onu_info->endpoint_name();
if (remote_endpoint != nullptr)
*remote_endpoint = onu_endpoint;
if (status != nullptr)
{
VomciConnection *conn = onu_info->vomci;
if (conn != nullptr)
{
*status = conn->isConnected() ?
BBF_VOMCI_COMMUNICATION_STATUS_CONNECTION_ACTIVE :
BBF_VOMCI_COMMUNICATION_STATUS_CONNECTION_INACTIVE;
}
else if (onu_endpoint && *onu_endpoint)
{
*status = BBF_VOMCI_COMMUNICATION_STATUS_CONNECTION_INACTIVE;
}
else
{
*status = BBF_VOMCI_COMMUNICATION_STATUS_REMOTE_ENDPOINT_IS_NOT_ASSIGNED;
}
}
if (in_messages)
*in_messages = onu_info->in_messages;
if (out_messages)
*out_messages = onu_info->out_messages;
if (message_errors)
*message_errors = onu_info->message_errors;
return BCM_ERR_OK;
}
/*
* Authentication parameters
*/
#define MAX_FILE_NAME_LENGTH 256
static char priv_key_file_name[MAX_FILE_NAME_LENGTH];
static char my_cert_file_name[MAX_FILE_NAME_LENGTH];
static char peer_cert_file_name[MAX_FILE_NAME_LENGTH];
static bool file_exists(const char *filename)
{
FILE *f;
if ((f=fopen(filename, "r"))== nullptr)
{
BCM_POLT_LOG(ERROR, "Can't open file %s for reading\n", filename);
return false;
}
fclose(f);
return true;
}
/* Authentication */
bcmos_errno bcm_tr451_auth_set(const char *priv_key_file, const char *my_cert_file, const char *peer_cert_file)
{
if (!priv_key_file || !priv_key_file[0] || !my_cert_file || !my_cert_file[0] || !peer_cert_file || !peer_cert_file[0])
return BCM_ERR_PARM;
if (!file_exists(priv_key_file) || !file_exists(my_cert_file) || !file_exists(peer_cert_file))
return BCM_ERR_NOENT;
strncpy(priv_key_file_name, priv_key_file, sizeof(priv_key_file_name) - 1);
strncpy(my_cert_file_name, my_cert_file, sizeof(my_cert_file_name) - 1);
strncpy(peer_cert_file_name, peer_cert_file, sizeof(peer_cert_file_name) - 1);
return BCM_ERR_OK;
}
bcmos_errno bcm_tr451_auth_get(const char **p_priv_key_file, const char **p_my_cert_file, const char **p_peer_cert_file)
{
if (!priv_key_file_name[0])
return BCM_ERR_NOENT;
*p_priv_key_file = priv_key_file_name;
*p_my_cert_file = my_cert_file_name;
*p_peer_cert_file = peer_cert_file_name;
return BCM_ERR_OK;
}
static bool _read_file_into_string(const char *filename, string &data)
{
std::ifstream iff(filename);
data.assign((std::istreambuf_iterator<char>(iff)), (std::istreambuf_iterator<char>()) );
return true;
}
bool bcm_tr451_auth_data(string &priv_key, string &my_cert, string &peer_cert)
{
bool res;
if (!priv_key_file_name[0])
return false;
res = _read_file_into_string(priv_key_file_name, priv_key);
res &= _read_file_into_string(my_cert_file_name, my_cert);
res &= _read_file_into_string(peer_cert_file_name, peer_cert);
return res;
}
<file_sep># Dockerfile for obbaa-polt-simulator
ARG FROM_TAG=latest
ARG OBBAA_OLT_ADAPTER_VERSION="1.0"
# image to build the code
FROM ubuntu:$FROM_TAG AS builder
ARG OBBAA_OLT_ADAPTER_VERSION
# install OS and perl packages
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get --yes install \
automake \
ccache \
cmake \
cpanminus \
g++ \
gcc \
git \
libtool \
m4 \
make \
patch \
pkg-config \
wget \
xz-utils \
zip \
python3 \
vim \
openssh-client \
&& cpanm \
FindBin \
&& apt-get clean
# set working directory
WORKDIR /opt/obbaa-polt-simulator
# copy pOLT simulator code
COPY . .
# build pOLT simulator (this installs to build/fs)
RUN echo "Building polt-simulator for OBBAA_OLT_ADAPTER_VERSION=$OBBAA_OLT_ADAPTER_VERSION .."; \
make OBBAA_DEVICE_ADAPTER_VERSION="$OBBAA_OLT_ADAPTER_VERSION"
# image to run the code
FROM ubuntu:$FROM_TAG
ARG PASSWD=<PASSWORD>
ARG DEBUG
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get --yes install \
openssh-client \
openssl \
&& if [ -n "$DEBUG" ] ; \
then DEBIAN_FRONTEND=noninteractive apt-get --yes install \
vim \
gdb \
wget \
net-tools \
iputils-ping \
python3 \
python3-pip \
tshark \
valgrind ; \
else : ; fi \
&& apt-get clean
# copy build/fs subdirs to /usr/local
COPY --from=builder /opt/obbaa-polt-simulator/build/fs/ /usr/local/
COPY certificates/ certificates/
RUN mkdir -p opt/obbaa-polt-simulator/build/fs && cp -Rsf /usr/local/* /opt/obbaa-polt-simulator/build/fs/ && ldconfig && echo root:$PASSWD | chpasswd
# generate RSA key pair
RUN mkdir -p /root/.ssh
RUN openssl genrsa -out /root/.ssh/polt.pem
RUN openssl req -new -x509 -sha256 -key /root/.ssh/polt.pem -out /root/.ssh/polt.cer -days 3650 -config certificates/request.conf
# copy the simulator's certificate and start netopeer2
ENTRYPOINT ["/usr/local/start_netconf_server.sh", "-d"]
<file_sep># zlib
#
include(third_party)
bcm_3rdparty_module_name(zlib "1.2.11")
bcm_3rdparty_download_wget("https://www.zlib.net" "zlib-${ZLIB_VERSION}.tar.gz")
bcm_3rdparty_add_build_options(-DBUILD_SHARED_LIBS=true)
bcm_3rdparty_build_cmake()
bcm_3rdparty_export(z)
<file_sep># Netconf agent
bcm_make_normal_option(NETCONF_SERVER BOOL "Build NETCONF server" n)
if(NETCONF_SERVER)
bcm_module_name(bcmolt_netconf_server)
bcm_module_dependencies(PUBLIC os daemon netconf_modules libyang sysrepo netopeer2)
if(NOT OPEN_SOURCE_SIM)
bcm_module_dependencies(PUBLIC host_api)
endif()
if(NOT OPEN_SOURCE)
bcm_module_dependencies(PUBLIC os_cli onu_mgmt_cli api_cli)
endif()
if(TR451_VOMCI_POLT)
bcm_module_dependencies(PUBLIC netconf_bbf-polt-vomci)
endif()
bcm_module_header_paths(PUBLIC .)
bcm_module_srcs(bcmolt_netconf_server.c)
bcm_create_app_target(fs)
add_dependencies(bcmolt_netconf_server yang-models)
bcm_add_subdirectory(modules)
install(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/start_netconf_server.sh DESTINATION fs
PERMISSIONS OWNER_READ OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE)
bcm_release_install(${CMAKE_INSTALL_PREFIX}/fs/lib RELEASE ${BCM_HOST_IMAGES_RELEASE}/netconf_server)
bcm_release_install(${CMAKE_INSTALL_PREFIX}/fs/bin RELEASE ${BCM_HOST_IMAGES_RELEASE}/netconf_server)
bcm_release_install(${CMAKE_INSTALL_PREFIX}/fs/sysrepo RELEASE ${BCM_HOST_IMAGES_RELEASE}/netconf_server)
bcm_release_install(${CMAKE_INSTALL_PREFIX}/fs/ssl RELEASE ${BCM_HOST_IMAGES_RELEASE}/netconf_server)
bcm_release_install(${CMAKE_INSTALL_PREFIX}/fs/start_netconf_server.sh RELEASE ${BCM_HOST_IMAGES_RELEASE}/netconf_server)
bcm_release_install(${CMAKE_INSTALL_PREFIX}/fs/bcmolt_netconf_server RELEASE ${BCM_HOST_IMAGES_RELEASE}/netconf_server)
bcm_release_install(${CMAKE_CURRENT_SOURCE_DIR}/doc RELEASE ${BCM_HOST_IMAGES_RELEASE}/netconf_server)
endif()
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
/** A write-biased readers-writer lock
* NOTE: DO NOT attempt to obtain a write lock on a thread that is already holding a read lock or vice versa - this
* will result in a deadlock. Multiple read locks from the same thread are safe, multiple write locks are NOT.
*/
#ifndef BCMOS_RW_LOCK_H_
#define BCMOS_RW_LOCK_H_
#include "bcmos_system.h"
typedef struct bcmos_rw_lock bcmos_rw_lock;
/** Initialize a lock
* \param[out] lock the newly created lock
* \return error code
*/
bcmos_errno bcmos_rw_lock_create(bcmos_rw_lock **lock);
/** Obtain a write lock
* \param[in] lock the lock to operate on
*/
void bcmos_rw_write_lock(bcmos_rw_lock* lock);
/** Release a write lock
* \param[in] lock the lock to operate on
*/
void bcmos_rw_write_release(bcmos_rw_lock* lock);
/** Obtain a read lock
* \param[in] lock the lock to operate on
*/
void bcmos_rw_read_lock(bcmos_rw_lock* lock);
/** Release a read lock
* \param[in] lock the lock to operate on
*/
void bcmos_rw_read_release(bcmos_rw_lock* lock);
#endif
<file_sep>/*
* <:copyright-BRCM:2016-2020:Apache:standard
*
* Copyright (c) 2016-2020 Broadcom. All Rights Reserved
*
* The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* :>
*
*****************************************************************************/
/*
* bcmolt_netconf_notifications.h
*/
#ifndef BCMOLT_NETCONF_NOTIFICATIONS_H_
#define BCMOLT_NETCONF_NOTIFICATIONS_H_
#include <bcmos_system.h>
#define XPON_ONU_ID_UNDEFINED 0xffff
#ifndef XPON_ONU_PRESENCE_FLAGS_DEFINED
typedef enum
{
XPON_ONU_PRESENCE_FLAG_NONE = 0,
XPON_ONU_PRESENCE_FLAG_V_ANI = 0x01,
XPON_ONU_PRESENCE_FLAG_ONU = 0x02,
XPON_ONU_PRESENCE_FLAG_ONU_IN_O5 = 0x04,
XPON_ONU_PRESENCE_FLAG_ONU_ACTIVATION_FAILED = 0x08,
} xpon_onu_presence_flags;
#define XPON_ONU_PRESENCE_FLAGS_DEFINED
#endif
/* change onu state change event
serial_number is in 8 byte binary format.
*/
bcmos_errno bcmolt_xpon_v_ani_state_change(const char *cterm_name, uint16_t onu_id,
const uint8_t *serial_number, xpon_onu_presence_flags presence_flags);
#endif
<file_sep># Add any optional cmake macros we use for internal testing
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules/external_import.cmake)
include(external_import)
endif()
<file_sep># TR-451: vOMCI YANG modules
* The project's YANG module development takes place in this Bitbucket repository.
* See the [SDN NFV](https://wiki.broadband-forum.org/display/BBF/SDN+and+NFV) wiki page for general details of the project.
## Sub-directories ##
The repository contains the following sub-directories:
* [standard](standard): YANG modules produced by other SDOs, which is kept here just for convenience
* [types](types): YANG modules containing common data type definitions that are useful in multiple modules
* [common](common): YANG modules which are common to the vOMCI network functions
* [olt](olt): YANG modules that would be implemented on a physical OLT
* [vomci-funcion](vomc-message): YANG modules that would be implemented on a vOMCI function
* [vomci-proxy](vomci-proxy): YANG modules that would be implemented on a vOMCI Proxy
* [voltmf](voltmf): YANG modules that would be implemented on a virtual OLT management function
## Branches ##
The repository contains the following branches:
* `develop` is the default branch and always contains everything that has been merged either directly to it or to one of the `release/xxx` branches
* `release/1.0` is used for developing the TR-451 YANG and its Corrigenda
* `master` will contain public releases, each of which will have a corresponding tag
Any changes that are merged to a `release/1.x` branch are automatically merged to higher (more recent) `release/1.x` branches and to `develop`. For example, a change to `release/1.0` is automatically merged to `develop`
There may also be `feature/xxx` branches that are used for complex features that are not yet ready to be merged into one of the above branches
<file_sep>/*
<:copyright-BRCM:2016-2019:Apache:standard
Copyright (c) 2016-2019 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
* :>
*/
#ifndef BCMOS_COMMON_H_
#define BCMOS_COMMON_H_
#ifndef BCMOS_SYSTEM_H_
#error Please do not include bcmos_common.h directly. Include bcmos_system.h
#endif
#include "bcmos_errno.h"
#include "bcmos_types.h"
#include "bcmos_queue.h"
#include "bcmos_tree.h"
/* Get constants, such as task, module, event id lists */
#include "bcmos_platform.h"
#include "bcmos_pack.h"
#include "bcmos_sysif.h"
#include "bcmos_endian.h"
#define MAX_TASK_NAME_SIZE 32
#define MAX_MODULE_NAME_SIZE 32
#define MAX_MSG_QUEUE_NAME_SIZE 32
#define MAX_TIMER_NAME_SIZE 32
#define MAX_POOL_NAME_SIZE 32
#define MAX_EVENT_NAME_SIZE 32
#define MAX_MUTEX_NAME_SIZE 32
#define MAX_SEM_NAME_SIZE 32
#define BCMOS_MSG_POOL_DEFAULT_SIZE 512
typedef long long_t;
typedef unsigned long ulong_t;
/* Define bcmos_bool - the boolean type for bcmos - based on C99 standard boolean type */
#ifndef BCMOS_BOOLEAN
#ifdef __cplusplus
typedef bool bcmos_bool;
#define BCMOS_FALSE false
#define BCMOS_TRUE true
#else
typedef _Bool bcmos_bool;
#define BCMOS_FALSE 0
#define BCMOS_TRUE 1
#endif
#endif
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
#define BCM_SIZEOFARRAY(arr) (sizeof(arr) / sizeof(*arr))
#define BCM_SIZEOFFIELD(s, f) (sizeof(((s *)NULL)->f))
#define BCM_MEMZERO_STRUCT(ptr) memset(ptr, 0, sizeof(*(ptr)))
#define BCM_MEMCPY_ARRAY(dst, src) memcpy(dst, src, MIN(sizeof(dst), sizeof(src)))
#define BCM_TAB " "
#define BCM_TAB2 BCM_TAB BCM_TAB
#define BCM_TAB3 BCM_TAB2 BCM_TAB
#define BCM_TAB4 BCM_TAB2 BCM_TAB2
#define BCM_ALIGN_PTR(ptr, align_size) ((((unsigned long)ptr) + ((align_size) - 1)) & ~((align_size) - 1))
typedef void (*f_bcmolt_sw_error_handler)(uint8_t pon_ni, const char *file_name, uint32_t line_number);
/* Similar to BUG_ON(), with the following features:
* 1. The condition is checked against BCM_ERR_OK.
* 2. In case on an error, the macro returns from the calling function with the error code. */
#define BUG_ON_ERR_RET(f) \
do \
{ \
bcmos_errno _err; \
_err = f; \
BUG_ON(_err != BCM_ERR_OK); \
return _err; \
} \
while (0)
/** \addtogroup system_init
* @{
*/
/** Initialize system library
* Must be called before any other system function
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_init(void);
/** Cleanup system library
*/
void bcmos_exit(void);
/** @} system_init */
/** \addtogroup system_mem
* @{
*/
#ifndef BCMOS_MALLOC_FREE_INLINE
/** \defgroup system_heap Default Heap
* @{
*/
/** Allocate memory from the main heap
* \param[in] size
* \returns memory block pointer or NULL
*/
#ifndef BCMOS_HEAP_DEBUG
void *bcmos_alloc(uint32_t size);
#else
void *_bcmos_alloc(uint32_t size);
#endif
/** Release memory to the main pool
* \param[in] ptr
*/
#ifndef BCMOS_HEAP_DEBUG
void bcmos_free(void *ptr);
#else
void _bcmos_free(void *ptr);
#endif
/** @} system_heap */
#endif /* #ifndef BCMOS_MALLOC_FREE_INLINE */
typedef void (*bcmos_msg_print_cb)(void *context, const char *fmt, ...);
typedef void (*bcmos_hexdump_cb)(bcmos_msg_print_cb print_cb, void *context, const void *buffer, uint32_t offset, uint32_t count, const char *indent);
#ifdef BCMOS_HEAP_DEBUG
/* Heap debugging feature.
* - Check dynamic memory blocks for corruption
* - Keep track of where each memory block has been allocated to debug memory leaks
* Each memory block is "sandwiched" between bcmos_heap_memblk_hdr and 32 bit magic protecting
* the end of block;
*/
typedef struct bcmos_heap_memblk_hdr bcmos_heap_memblk_hdr;
struct bcmos_heap_memblk_hdr
{
#define BCMOS_HEAP_DEBUG_FNAME_LEN 40
DLIST_ENTRY(bcmos_heap_memblk_hdr) list; /**< Block list pointer */
char fname[BCMOS_HEAP_DEBUG_FNAME_LEN]; /**< Function name */
uint32_t line; /**< Line number */
uint32_t size; /**< Block size */
uint32_t timestamp; /**< Timestamp when the block was allocated/freed */
bcmos_bool is_init_time; /**< Is this initialization time allocation */
uint32_t magic; /**< Start of block magic number */
#define BCMOS_HEAP_DEBUG_ALLOC_MAGIC ('a'<<24 | 'l'<<16 | 'l'<<8 | 'c')
#define BCMOS_HEAP_DEBUG_FREE_MAGIC ('f'<<24 | 'r'<<16 | 'e'<<8 | 'e')
};
#define BCMOS_HEAP_DEBUG_OVERHEAD (sizeof(bcmos_heap_memblk_hdr) + sizeof(uint32_t))
/* Add newly allocated memory block to heap debug list. Returns "user" pointer */
void *bcmos_heap_debug_memblk_add(void *hdr_ptr, uint32_t size, const char *fname, uint32_t line);
/* Check memory block. Returns BCMOS_TRUE if the block is OK */
bcmos_bool bcmos_heap_debug_memblk_check(void *user_ptr);
/* Check memory block before freeing it. Returns BCMOS_TRUE if the block is OK */
bcmos_bool bcmos_heap_debug_memblk_check_and_del(void *user_ptr, const char *fname, uint32_t line);
static inline void *bcmos_heap_debug_hdr_to_user_ptr(bcmos_heap_memblk_hdr *hdr)
{
if (!hdr)
return hdr;
return hdr + 1;
}
static inline bcmos_heap_memblk_hdr *bcmos_heap_user_ptr_to_debug_hdr(void *user_ptr)
{
if (!user_ptr)
return (bcmos_heap_memblk_hdr *)NULL;
return (bcmos_heap_memblk_hdr *)((long)user_ptr - sizeof(bcmos_heap_memblk_hdr));
}
/* Protect heap debug memblk list when traversing it.
* While heap debug is locked, all memory allocation and free requests will stall
*/
void bcmos_heap_debug_lock(void);
void bcmos_heap_debug_unlock(void);
void *bcmos_heap_debug_memblk_get_next(void *prev);
void bcmos_heap_debug_info_get(uint32_t *num_blocks, uint32_t *total_size);
bcmos_errno bcmos_heap_debug_print(bcmos_msg_print_cb print_cb, bcmos_hexdump_cb hexdump_cb, void *context, bcmos_bool exclude_init_time, uint32_t num_skip, uint32_t num_print,
uint32_t data_bytes, uint32_t start_ts, uint32_t end_ts, const char *func);
#define bcmos_alloc(size) bcmos_alloc_debug(size, __FUNCTION__, __LINE__)
#define bcmos_free(ptr) bcmos_free_debug(ptr, __FUNCTION__, __LINE__)
#define bcmos_calloc(size) bcmos_calloc_debug(size, __FUNCTION__, __LINE__)
void *bcmos_alloc_debug(uint32_t size, const char *fname, uint32_t line);
void *bcmos_calloc_debug(uint32_t size, const char *fname, uint32_t line);
void bcmos_free_debug(void *ptr, const char *fname, uint32_t line);
/* Used for temporarily disabling the out of memory heap info print. By default it is enabled*/
extern bcmos_bool bcmos_heap_debug_out_of_memory_print_disabled;
/* Mark that initialization is done, in case we want to exclude initialization time allocations. */
extern bcmos_bool bcmos_heap_debug_init_done;
#endif /* #ifdef BCMOS_HEAP_DEBUG */
/* Copy string.
The copy is allocated using bcmos_alloc() and should be released using bcmos_free()
*/
char *bcmos_strdup(const char *s);
/** \defgroup blk_pool Block Memory Pool
* \ingroup system_mem
* @{
*/
/** Block memory pool parameters */
typedef struct
{
const char *name; /**< Pool name */
uint32_t blk_size; /**< Memory block size > 0 */
uint32_t num_blks; /**< Number of blocks in the pool. If not set - it is derived from pool_size */
void *start; /**< Start address. Can be NULL */
uint32_t pool_size; /**< Total pool size in bytes. Only 1 of pool_size, num_blks must be set */
uint32_t flags; /**< TBD flags */
#define BCMOS_BLK_POOL_FLAG_MSG_POOL 0x80000000 /* Used by message pool */
} bcmos_blk_pool_parm;
/** Block memory pool statistics */
typedef struct bcmos_blk_pool_stat
{
uint32_t allocated; /**< Number of blocks allocated */
uint32_t released; /**< Number of blocks released */
uint32_t free; /**< Number of free blocks in the pool */
uint32_t alloc_failed; /**< Number of allocation failures */
} bcmos_blk_pool_stat;
/** Block memory pool info */
typedef struct bcmos_blk_pool_info
{
bcmos_blk_pool_parm parm; /**< Pool parameters */
bcmos_blk_pool_stat stat; /**< Pool statistics */
} bcmos_blk_pool_info;
/** Block memory pool control block */
typedef struct bcmos_blk_pool bcmos_blk_pool;
/** Create block memory pool
* \param[in,out] pool pool control block
* \param[in] parm pool parameters
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_blk_pool_create(bcmos_blk_pool *pool, const bcmos_blk_pool_parm *parm);
/** Destroy block memory pool
* \param[in] pool pool handle
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_blk_pool_destroy(bcmos_blk_pool *pool);
/** Allocate block from block memory pool
*
* This allocates a single unit (unit_size bytes)
* \param[in] pool Pool handle
* \return memory block pointer or NULL.
* It is guaranteed that the returned pointer is aligned to pointer size
*/
#ifdef BCMOS_BLK_POOL_DEBUG
void *bcmos_blk_pool_alloc_func(bcmos_blk_pool *pool, const char *func, int line);
#define bcmos_blk_pool_alloc(pool) bcmos_blk_pool_alloc_func(pool, __FUNCTION__, __LINE__)
#else
void *bcmos_blk_pool_alloc(bcmos_blk_pool *pool);
#endif
/** Allocate block from block memory pool and zero the block
*
* This allocates a single unit (unit_size bytes)
* \param[in] pool Pool handle
* \return memory block pointer or NULL.
* It is guaranteed that the returned pointer is aligned to pointer size
*/
#ifdef BCMOS_BLK_POOL_DEBUG
void *bcmos_blk_pool_calloc_func(bcmos_blk_pool *pool, const char *func, int line);
#define bcmos_blk_pool_calloc(pool) bcmos_blk_pool_calloc_func(pool, __FUNCTION__, __LINE__)
#else
void *bcmos_blk_pool_calloc(bcmos_blk_pool *pool);
#endif
/** Release memory allocated using bcmos_blk_pool_alloc()
*
* \param[in] ptr pointer
*/
#ifdef BCMOS_BLK_POOL_DEBUG
void bcmos_blk_pool_free_func(void *ptr, const char *func, int line);
#define bcmos_blk_pool_free(ptr) bcmos_blk_pool_free_func(ptr, __FUNCTION__, __LINE__)
#else
void bcmos_blk_pool_free(void *ptr);
#endif
/** Release all blocks in memory pool. Block content is not affected
* This function is useful when application wants to pre-initialize
* some portion of each memory block at init time
*
* \param[in] pool Pool handle
*/
void bcmos_blk_pool_reset(bcmos_blk_pool *pool);
/** Get pool info
*
* The pool must be created using bcmos_blk_pool_create()
* \param[in] pool Block memory pool handle
* \param[out] info Block memory pool info
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_blk_pool_query(const bcmos_blk_pool *pool, bcmos_blk_pool_info *info);
/** Block pool iterator
* \param[in] prev Previous block pool. *prev==NULL - get first
* \return: BCM_ERR_OK, BCM_ERR_NOENT, BCM_ERR_NO_MORE
*/
bcmos_errno bcmos_blk_pool_get_next(const bcmos_blk_pool **prev);
#ifdef BCMOS_BLK_POOL_DEBUG
typedef struct bcmos_memblk bcmos_memblk;
/** Allocated block iterator within a given block pool
* \param[in] pool Block pool
* \param[in] prev Previous allocated block. *prev==NULL - get first
* \param[out] func Function in which the block was allocated
* \param[out] line Line number in which the block was allocated
* \return: BCM_ERR_OK, BCM_ERR_NOENT, BCM_ERR_NO_MORE
*/
bcmos_errno bcmos_blk_pool_allocated_blk_get_next(const bcmos_blk_pool *pool, const bcmos_memblk **prev, const char **func, int *line);
#endif
/** @} blk_pool */
/** \defgroup byte_pool Byte Memory Pool
* \ingroup system_mem
* @{
*/
/** Byte memory pool parameters */
typedef struct
{
const char *name; /**< Pool name */
uint32_t size; /**< Pool size (bytes) */
void *start; /**< Start address. Can be NULL */
} bcmos_byte_pool_parm;
/** Byte memory pool control block */
typedef struct bcmos_byte_pool bcmos_byte_pool;
/** Create byte memory pool
* \param[in,out] pool pool control block
* \param[in] parm pool parameters
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_byte_pool_create(bcmos_byte_pool *pool, const bcmos_byte_pool_parm *parm);
/** Destroy byte memory pool
* \param[in] pool pool handle
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_byte_pool_destroy(bcmos_byte_pool *pool);
#ifndef BCMOS_BYTE_POOL_ALLOC_FREE_INLINE
/** Allocate memory from byte memory pool
*
* This function can only be used with byte memory pools created
* with unit_size==1
* \param[in] pool Pool handle
* \param[in] size Block size (bytes)
* \return memory block pointer or NULL
*/
void *bcmos_byte_pool_alloc(bcmos_byte_pool *pool, uint32_t size);
/** Release memory allocated using bcmos_pool_byte_alloc()
*
* \param[in] ptr pointer
*/
void bcmos_byte_pool_free(void *ptr);
#endif /* BCMOS_BYTE_POOL_ALLOC_FREE_INLINE */
/** @} byte_pool */
/** Lock all dynamic memory allocations. Any attempt to allocate memory from the heap after this is called will cause
* an error if allocation size is smaller than allocation_block_size_threshold.
* This includes bcmos_alloc, bcmos_block_pool_create, etc.
* Dynamic allocations with size >= allocation_block_size_threshold are still allowed.
*
* For embedded applications, runtime dynamic memory allocation is generally undesirable, so this should be called
* after system initialization.
*/
void bcmos_dynamic_memory_allocation_block(uint32_t allocation_block_size_threshold);
/** Unlock all dynamic memory allocations. This should not generally be called at run-time, but sometimes it is
* required for system re-initialization.
*/
void bcmos_dynamic_memory_allocation_unblock(void);
/** Unlock dynamic memory allocation temporarily (for certain cases where dynamic memory allocation is required).
* If bcmos_dynamic_memory_allocation_block() has not been called, this will have no effect. */
void bcmos_dynamic_memory_allocation_blocking_suspend(void);
/** Re-lock dynamic memory allocations that were unlocked with bcmos_dynamic_memory_allocation_blocking_suspend(). */
void bcmos_dynamic_memory_allocation_blocking_resume(void);
/* Allow dynamic allocations bigger than BCMOS_DYNAMIC_MEMORY_ALLOCATION_BLOCK_THRESHOLD
at run time. Big dynamic allocations are used for features like image download.
*/
#define BCMOS_DYNAMIC_MEMORY_ALLOCATION_BLOCK_THRESHOLD (64 * 1024)
/** Produces an error if dynamic memory allocations have been locked via bcmos_lock_dynamic_memory_allocation().
*/
void bcmos_dynamic_memory_allocation_block_check(uint32_t size);
/** @} system_mem */
/** \addtogroup system_task
* @{
*/
#ifndef BCMOS_WAIT_FOREVER
#define BCMOS_WAIT_FOREVER 0xFFFFFFFF /**< Wait timeout. Wait forever */
#endif
#ifndef BCMOS_NO_WAIT
#define BCMOS_NO_WAIT 0 /**< Wait timeout. Don't wait */
#endif
#define BCMOS_MICROSECONDS_IN_SECONDS (1000000)
/** Task priority */
typedef enum
{
BCMOS_TASK_PRIORITY_0, /**< Priority 0 - highest */
BCMOS_TASK_PRIORITY_1, /**< Priority 1 */
BCMOS_TASK_PRIORITY_2, /**< Priority 2 */
BCMOS_TASK_PRIORITY_3, /**< Priority 3 */
BCMOS_TASK_PRIORITY_4, /**< Priority 4 */
BCMOS_TASK_PRIORITY_5, /**< Priority 5 */
BCMOS_TASK_PRIORITY_6, /**< Priority 6 */
BCMOS_TASK_PRIORITY_7, /**< Priority 7 */
BCMOS_TASK_PRIORITY_8, /**< Priority 8 */
BCMOS_TASK_PRIORITY_9, /**< Priority 9 */
BCMOS_TASK_PRIORITY_10,/**< Priority 10 */
BCMOS_TASK_PRIORITY_11,/**< Priority 11 */
BCMOS_TASK_PRIORITY_12,/**< Priority 12 */
BCMOS_TASK_PRIORITY_13,/**< Priority 13 */
BCMOS_TASK_PRIORITY_14,/**< Priority 14 */
BCMOS_TASK_PRIORITY_15,/**< Priority 15 */
BCMOS_TASK_PRIORITY_16,/**< Priority 16 */
BCMOS_TASK_PRIORITY_17,/**< Priority 17 */
BCMOS_TASK_PRIORITY_18,/**< Priority 18 */
BCMOS_TASK_PRIORITY_19,/**< Priority 19 */
BCMOS_TASK_PRIORITY_20,/**< Priority 20 */
BCMOS_TASK_PRIORITY_21,/**< Priority 21 */
BCMOS_TASK_PRIORITY_22,/**< Priority 22 */
BCMOS_TASK_PRIORITY_23,/**< Priority 23 */
BCMOS_TASK_PRIORITY_24,/**< Priority 24 */
BCMOS_TASK_PRIORITY_25,/**< Priority 25 */
BCMOS_TASK_PRIORITY_26,/**< Priority 26 */
BCMOS_TASK_PRIORITY_27,/**< Priority 27 */
BCMOS_TASK_PRIORITY_28,/**< Priority 28 */
BCMOS_TASK_PRIORITY_29,/**< Priority 29 */
BCMOS_TASK_PRIORITY_30,/**< Priority 30 */
BCMOS_TASK_PRIORITY_31,/**< Priority 31 - lowest */
} bcmos_task_priority;
/** Task handler */
typedef int (*F_bcmos_task_handler)(long data);
/* Default task handler */
extern int bcmos_dft_task_handler(long data);
/* This flags determines whether a task is to be suspended upon OOPS condition. */
#define BCMOS_TASK_FLAG_NO_SUSPEND_ON_OOPS (1 << 0)
/** Task parameters */
typedef struct
{
const char *name; /**< Task name */
bcmos_task_priority priority; /**< Task priority */
bcmos_core core; /**< CPU core the task is locked to */
uint32_t stack_size; /**< Task stack size */
void *stack; /**< Stack location. NULL=allocate automatically */
F_bcmos_task_handler init_handler; /**< Optional "init" handler. Called once in the task context when it is created.
This callback is only supported in integration mode (handler==NULL).
init_handler returns bcmos_errno. If it returns value other than BCM_ERR_OK,
the task is destroyed */
F_bcmos_task_handler handler; /**< Task handler. NULL=default (integration mode) */
F_bcmos_task_handler timeout_handler;/**< This function is used only in integration mode (handler==NULL) if
msg_wait_timeout is > 0. It is called if there were no messages for the task
for longer than msg_wait_timeout us.
If timeout handler returns value other than BCM_ERR_OK, task terminates.
*/
uint32_t msg_wait_timeout; /**< This parameter is used only in integration mode (handler==NULL) together with
timeout_handler. If > 0 and there were no messages for longer than
msg_wait_timeout us, timeout_handler is called.
*/
long data; /**< Data passed to the task handler */
uint32_t flags; /**< flags */
} bcmos_task_parm;
/** Task control block */
typedef struct bcmos_task bcmos_task;
/** Create a new task
*
* \param[in,out] task Task control block
* \param[in] parm Task parameters
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_task_create(bcmos_task *task, const bcmos_task_parm *parm);
/** Set task timeout
*
* This function is only used in integration mode (handler==NULL).
* It sets max time the default task handler waits for message directed to one of the
* task's modules.
*
* \param[in,out] task Task control block
* \param[in] timeout Max time (us) to wait for messages. 0=FOREVER
* Changing timeout from infinite to finite only takes effect
* after message is received by any task module.
* \param[in] timeout_handler Handler to be called upon timeout. Must be != NULL if timeout > 0.
* If the handler returns error (!= BCM_ERR_OK), task terminates.
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_task_timeout_set(bcmos_task *task, uint32_t timeout, F_bcmos_task_handler timeout_handler);
/** Destroy task
*
* \param[in] task Task handle
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_task_destroy(bcmos_task *task);
/** Get current task
* \returns task handle or NULL if not in task context
*/
bcmos_task *bcmos_task_current(void);
/** Query task info
* \param[in] task Task control block
* \param[out] parm Task parameters
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_task_query(const bcmos_task *task, bcmos_task_parm *parm);
/** Task iterator
* \param[in] prev Previous task. *prev==NULL - get first
* \return: BCM_ERR_OK, BCM_ERR_NOENT, BCM_ERR_NO_MORE
*/
bcmos_errno bcmos_task_get_next(bcmos_task **prev);
/** @} system_task */
/** \addtogroup system_msg
* @{
*/
/** Message header */
typedef struct bcmos_msg bcmos_msg;
/** Message queue control block */
typedef struct bcmos_msg_queue bcmos_msg_queue;
/** Message queue group control block */
typedef struct bcmos_msg_qgroup bcmos_msg_qgroup;
#if defined(BCMOS_MSG_QUEUE_DOMAIN_SOCKET) || defined(BCMOS_MSG_QUEUE_UDP_SOCKET) || defined(BCMOS_MSG_QUEUE_USER_DEFINED)
#define BCMOS_MSG_QUEUE_REMOTE_SUPPORT
#endif
/** Message queue endpoint type */
typedef enum
{
BCMOS_MSG_QUEUE_EP_LOCAL, /**< Local endpoint (inter-thread communication) */
#ifdef BCMOS_MSG_QUEUE_DOMAIN_SOCKET
BCMOS_MSG_QUEUE_EP_DOMAIN_SOCKET, /**< Domain-socket based endpoint */
#endif
#ifdef BCMOS_MSG_QUEUE_UDP_SOCKET
BCMOS_MSG_QUEUE_EP_UDP_SOCKET, /**< UDP socket-based endpoint */
#endif
#ifdef BCMOS_MSG_QUEUE_USER_DEFINED
BCMOS_MSG_QUEUE_EP_USER_DEFINED /**< User-defined endpoint */
#endif
#ifdef BCMOS_MSG_QUEUE_REMOTE_SUPPORT
BCMOS_MSG_QUEUE_EP_BY_ADDRESS /**< Endpoint type is determined based on the address format */
#endif
} bcmos_msg_queue_ep_type;
/** Message queue parameters */
typedef struct
{
const char *name; /**< Queue name (for logging and debugging) */
uint32_t size; /**< Max queue size. 0=unlimited */
uint32_t high_wm; /**< Optional high water mark. Log is generated when queue occupancy exceeds hwm */
uint32_t low_wm; /**< Optional low water mark. Log is generated when queue occupancy drops below lwm */
uint32_t flags; /**< TBD flags. For example, single-core, m-core */
void (*notify)(bcmos_msg_queue *q, const char *txt); /***< Called when queue congestion state changes */
bcmos_msg_queue_ep_type ep_type; /**< Queue endpoint type */
#ifdef BCMOS_MSG_QUEUE_REMOTE_SUPPORT
/* Remote message queue support allows queue endpoints to be located in
* different processes or even processors.
*/
const char *local_ep_address; /**< Queue local endpoint address */
const char *remote_ep_address; /**< Queue local endpoint address */
uint32_t max_mtu; /**< Max MTU size */
#define BCMOS_MSG_QUEUE_DEFAULT_MAX_MTU (64*1024)
/** Optional "pack" callback. Not needed if 2 processes are on the same core. */
bcmos_errno (*pack)(bcmos_msg_queue *queue, bcmos_msg *msg, uint8_t **buf, uint32_t *buf_length);
/** Optional "unpack" callback. Not needed if 2 processes are on the same core. */
bcmos_errno (*unpack)(bcmos_msg_queue *queue, uint8_t *buf, uint32_t buf_length, bcmos_msg **msg);
/** Optional callback that releases packed buffer */
void (*free_packed)(bcmos_msg_queue *queue, uint8_t *buf);
/** Optional "open" callback. Must be set for user-defined queue, NULL otherwise */
bcmos_errno (*open)(bcmos_msg_queue *queue);
/** Optional "close" callback. Must be set for user-defined queue, NULL otherwise */
bcmos_errno (*close)(bcmos_msg_queue *queue);
/** Optional "send" callback. Must be set for user-defined queue, NULL otherwise */
bcmos_errno (*send)(bcmos_msg_queue *queue, bcmos_msg *msg, uint8_t *buf, uint32_t buf_length);
/** Optional "recv" callback. Must be set for user-defined queue, NULL otherwise */
bcmos_errno (*recv)(bcmos_msg_queue *queue, uint32_t timeout, uint8_t **buf, uint32_t *buf_length);
#endif
} bcmos_msg_queue_parm;
/** Message queue statistics */
typedef struct
{
uint32_t msg_in; /**< Number of messages currently in the queue */
uint32_t msg_sent; /**< Number of messages successfully submitted into the queue */
uint32_t msg_received; /**< Number of messages received from the queue */
uint32_t msg_discarded; /**< Number of messages discarded because of queue overflow */
uint32_t msg_almost_full; /**< Number of messages submitted to queue when it was above high water mark */
bcmos_bool is_congested; /**< True=the queue is currently congested */
} bcmos_msg_queue_stat;
/** Message queue info */
typedef struct
{
bcmos_msg_queue_parm parm; /**< Queue parameters */
bcmos_msg_queue_stat stat; /**< Queue statistics */
} bcmos_msg_queue_info;
/** Message priority in queue group */
typedef uint32_t bcmos_qgroup_prty;
/** Message queue group parameters */
typedef struct
{
const char *name; /**< Queue group name (for logging and debugging) */
bcmos_qgroup_prty nqueues; /**< Number of queues in the group */
uint32_t size; /**< Total number of messages that can be stored in queue group. 0=unlimited */
uint32_t high_wm; /**< Optional high water mark. Log is generated when queue occupancy exceeds hwm */
uint32_t low_wm; /**< Optional low water mark. Log is generated when queue occupancy drops below lwm */
uint32_t flags; /**< TBD flags. For example, single-core, m-core */
void (*notify)(bcmos_msg_qgroup *qgrp, const char *txt); /***< Called when queue group congestion state changes */
} bcmos_msg_qgroup_parm;
/** Message queue group info */
typedef struct
{
bcmos_msg_qgroup_parm parm; /**< Queue group parameters */
bcmos_msg_queue_stat stat; /**< Queue group statistics */
} bcmos_msg_qgroup_info;
/** Message recipient instance (e.g., optical link id) */
typedef uint16_t bcmos_msg_instance;
/** Message send flags */
typedef enum
{
BCMOS_MSG_SEND_AUTO_FREE = 0x00000000, /**< Automatically release message in case of error. This is the default behaviour */
BCMOS_MSG_SEND_NO_FREE_ON_ERROR =0x00000001,/**< Do NOT free message in case of transmit error */
BCMOS_MSG_SEND_URGENT = 0x00000002, /**< Urgent message */
BCMOS_MSG_SEND_NOLIMIT = 0x00000004, /**< Ignore destination queue size limit */
} bcmos_msg_send_flags;
/** Registered message handler */
typedef void (*F_bcmos_msg_handler)(bcmos_module_id module_id, bcmos_msg *msg);
typedef bcmos_errno (*F_bcmos_module_init)(long data);
typedef void (*F_bcmos_module_exit)(long data);
#ifdef BCMOS_MSG_QUEUE_REMOTE_SUPPORT
typedef struct bcmos_msg_addr
{
bcmos_msg_queue_ep_type type; /**< Address type */
uint32_t len; /**< Address length */
void *addr; /**< Address pointer */
} bcmos_msg_addr;
/** Parse remote message address
* \param[in] addr_string String containing address
* \param[in] addr_type Address type
* \param[in,out] addr On input references buffer for address conversion.
* On output addr_len contains the converted address
* \returns BCM_ERR_OK, BCM_ERR_PARM, BCM_ERR_OVERFLOW
*/
bcmos_errno bcmos_msg_address_parse(const char *addr_string, bcmos_msg_queue_ep_type ep_type, bcmos_msg_addr *addr);
#endif /* BCMOS_MSG_QUEUE_REMOTE_SUPPORT */
/** Message header */
struct bcmos_msg
{
bcmos_msg_id type; /**< Message type */
bcmos_msg_instance instance;/**< Message recipient instance (e.g., optical link id) */
bcmos_module_id sender; /**< Sender module */
F_bcmos_msg_handler handler;/**< Message handler. Can be set by the sender or message dispatcher */
STAILQ_ENTRY(bcmos_msg) next; /**< Next message pointer */
void *data; /**< Message data pointer */
void *start; /**< Message data block start (for release) */
void *user_data; /**< User pointer. Opaque for OS abstraction */
uint32_t size; /**< Message data size */
bcmos_msg_send_flags send_flags; /**< Flags the message was sent with */
#define BCMOS_MSG_QUEUE_SIZE_UNLIMITED 0xFFFFFFFF /**< Unlimited queue */
#ifdef BCMOS_MSG_QUEUE_REMOTE_SUPPORT
bcmos_msg_addr addr; /**< Sender address for received message, destination address when sending */
#endif
void (*release)(bcmos_msg *); /**< Release callback */
void (*data_release)(bcmos_msg *); /**< Data release callback. Used when message is released to message pool */
};
/* Helper functions that pack / unpack message header for IPC */
#ifdef BCMOS_MSG_QUEUE_REMOTE_SUPPORT
/** Size of message header on the line for IPC */
#define BCMOS_MSG_HDR_SIZE 8
void bcmos_msg_hdr_pack(const bcmos_msg *msg, uint8_t *buf, uint32_t data_size);
void bcmos_msg_hdr_unpack(const uint8_t *buf, bcmos_msg *msg);
#endif
/** Create message queue.
*
* This function can be called explicitly in "traditional" mode
* or implicitly by bcmos_module_create().
* \param[in,out] queue Queue control block
* \param[in] parm Queue parameters
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_msg_queue_create(bcmos_msg_queue *queue, const bcmos_msg_queue_parm *parm);
/** Destroy queue
*
* \param[in] queue Queue handle
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_msg_queue_destroy(bcmos_msg_queue *queue);
/** Get queue info
*
* \param[in] queue Queue handle
* \param[out] info Queue information
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_msg_queue_query(const bcmos_msg_queue *queue, bcmos_msg_queue_info *info);
/** Message queue iterator
* \param[in] prev Previous queue. *prev==NULL - get first
* \return: BCM_ERR_OK, BCM_ERR_NOENT, BCM_ERR_NO_MORE
*/
bcmos_errno bcmos_msg_queue_get_next(const bcmos_msg_queue **prev);
/** Create message queue group.
*
* Queue group contains configurable number of queues. The queues are drained
* in strict priority. Priority 0 is the highest.
*
* \param[in,out] qgroup Queue group control block
* \param[in] parm Queue group parameters
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_msg_qgroup_create(bcmos_msg_qgroup *qgroup, const bcmos_msg_qgroup_parm *parm);
/** Destroy queue group
*
* \param[in] qgroup Queue group handle
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_msg_qgroup_destroy(bcmos_msg_qgroup *qgroup);
/** Get queue group info
*
* \param[in] qgroup Queue group handle
* \param[out] info Queue group information
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_msg_qgroup_query(const bcmos_msg_qgroup *qgroup, bcmos_msg_qgroup_info *info);
/** Message queue group iterator
* \param[in] prev Previous queue group. *prev==NULL - get first
* \return: BCM_ERR_OK, BCM_ERR_NOENT, BCM_ERR_NO_MORE
*/
bcmos_errno bcmos_msg_qgroup_get_next(const bcmos_msg_qgroup **prev);
/** Send message to queue
*
* \param[in] queue Queue handle
* \param[in] msg Message
* \param[in] flags flags. Combination of \ref bcmos_msg_send_flags bits
*
* msg is released automatically regardless of bcmos_msg_send() outcome, unless
* BCMOS_MSG_SEND_NO_FREE_ON_ERROR flag is set.
*
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_msg_send(bcmos_msg_queue *queue, bcmos_msg *msg, bcmos_msg_send_flags flags);
/** Send message to module
*
* For module to be able to receive the message, it must be registered
* using bcmos_msg_register()
*
* \param[in] module_id Module id
* \param[in] msg Message. msg->handler must be set
* \param[in] flags flags. Combination of \ref bcmos_msg_send_flags bits
*
* msg is released automatically regardless of bcmos_msg_send_to_module() outcome, unless
* BCMOS_MSG_SEND_NO_FREE_ON_ERROR flag is set.
*
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_msg_send_to_module(bcmos_module_id module_id, bcmos_msg *msg, bcmos_msg_send_flags flags);
/** Send message to queue group
*
* \param[in] qgroup Queue group handle
* \param[in] msg Message
* \param[in] prty Message priority in range 0-nqueues_in_group-1.
* 0 priority is the highest. If MAX number of messages are already queues
* in the queue group, sending message can leave to discard of the head message
* queued at lower priority
* \param[in] flags BCMOS_MSG_SEND_AUTO_FREE or BCMOS_MSG_SEND_NO_FREE_ON_ERROR flag
*
*
* msg is released automatically regardless of bcmos_msg_send_to_qgroup() outcome, unless
* BCMOS_MSG_SEND_NO_FREE_ON_ERROR flag is set.
*
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_msg_send_to_qgroup(bcmos_msg_qgroup *qgroup, bcmos_msg *msg, bcmos_qgroup_prty prty,
bcmos_msg_send_flags flags);
/** Get message from the head of message queue
*
* The function can lead to the calling task being suspended for a period
* of time or indefinitely, until message is submitted to the queue.\n
* The function is only used in "traditional tasks" (see \ref system_model).
*
* \param[in] queue Queue handle
* \param[in] timeout timeout. can be 0, time in us or \ref BCMOS_WAIT_FOREVER
* \param[out] msg Message handle
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_msg_recv(bcmos_msg_queue *queue, uint32_t timeout, bcmos_msg **msg);
/** Get highest priority message from queue group
*
* The function can lead to the calling task being suspended for a period
* of time or indefinitely, until message is submitted to the queue group.\n
* The function is only used in "traditional tasks" (see \ref system_model).
*
* \param[in] qgroup Queue group handle
* \param[in] timeout timeout. can be 0, time in us or \ref BCMOS_WAIT_FOREVER
* \param[out] msg Message handle
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_msg_recv_from_qgroup(bcmos_msg_qgroup *qgroup, uint32_t timeout, bcmos_msg **msg);
/** Dispatch message. Send to module that registered for it.
*
* The message must be registered using bcmos_msg_register()
*
* This function should be used if the message sender doesn't know the target module and/or
* message handling callback.
*
* \param[in] msg Message handle
* \param[in] flags flags. Combination of \ref bcmos_msg_send_flags bits
*
* msg is released automatically regardless of bcmos_msg_dispatch() outcome, unless
* BCMOS_MSG_SEND_NO_FREE_ON_ERROR flag is set.
*
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_msg_dispatch(bcmos_msg *msg, bcmos_msg_send_flags flags);
/** Register message for "push-mode" delivery.
*
* When registered message is sent to the target module and
* the module's task wakes up, message handler is called in the module's context.
*
* \param[in] msg_type Message type
* \param[in] instance Message type instance
* \param[in] module_id Target module id
* \param[in] handler Message handler
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_msg_register(bcmos_msg_id msg_type, bcmos_msg_instance instance,
bcmos_module_id module_id, F_bcmos_msg_handler handler);
/** Un-register message registered by bcmos_msg_register()
*
* \param[in] msg_type Message type
* \param[in] instance Message type instance
* \param[in] module_id Target module id
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_msg_unregister(bcmos_msg_id msg_type, bcmos_msg_instance instance,
bcmos_module_id module_id);
/** Put the OS message infrastructure in "shutdown mode".
*
* When in shutdown mode, bcmos_msg_dispatch() will return BCM_ERR_OK instead of BCM_ERR_NOENT when a handler is not
* found for the message. Additionally, bcmos_msg_dispatch() becomes safe to call concurrently with
* bcmos_msg_unregister() (this is not true in normal operation).
*
* \param[in] shutdown_mode Whether or not to enable shutdown mode
*/
void bcmos_msg_shutdown_mode_set(bcmos_bool shutdown_mode);
/** Gets whether or not the OS message infrastructure is currently in "shutdown mode".
* \returns BCMOS_TRUE if we are in shutdown mode, BCMOS_FALSE otherwise
*/
bcmos_bool bcmos_msg_shutdown_mode_get(void);
/** Helper type for storing message types alongside their handlers. */
typedef struct
{
bcmos_msg_id msg_type;
F_bcmos_msg_handler handler;
} bcmos_msg_id2handler;
/** Message pool */
typedef struct bcmos_msg_pool bcmos_msg_pool;
/** Message pool parameters */
typedef struct bcmos_msg_pool_parm
{
const char *name; /**< Pool name */
uint32_t size; /**< Number of messages in the pool */
uint32_t data_size; /**< Message data size */
uint32_t flags; /**< TBD flags */
void (*data_release)(bcmos_msg *msg); /**< Optional data release callback. Called when message is released to the pool */
} bcmos_msg_pool_parm;
/** Message pool statistics */
typedef bcmos_blk_pool_stat bcmos_msg_pool_stat;
/** Message pool info */
typedef struct bcmos_msg_pool_info
{
bcmos_msg_pool_parm parm; /**< Pool parameters */
bcmos_msg_pool_stat stat; /**< Pool statistics */
} bcmos_msg_pool_info;
/** Create message pool
*
* Create pool containing pre-allocated messages with specified data size
* \param[in] pool Message pool handle
* \param[in] parm Message pool parameters
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_msg_pool_create(bcmos_msg_pool *pool, const bcmos_msg_pool_parm *parm);
/** Destroy message pool
*
* All messages must be released to the pool before it can be destroyed.
*
* \param[in] pool Message pool handle
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_msg_pool_destroy(bcmos_msg_pool *pool);
/** Allocate message from pool
*
* The pool must be created using bcmos_pool_create()
* \param[in] pool Message pool handle
* \returns msg pointer or NULL if the pool is empty.
* "data" and "release" fields in the returned message are pre-set
* Once no longer needed, the message must be released using bcmos_msg_free()
*/
#ifdef BCMOS_BLK_POOL_DEBUG
bcmos_msg *bcmos_msg_pool_alloc_func(bcmos_msg_pool *pool, const char *func, int line);
#define bcmos_msg_pool_alloc(pool) bcmos_msg_pool_alloc_func(pool, __FUNCTION__, __LINE__)
#else
bcmos_msg *bcmos_msg_pool_alloc(bcmos_msg_pool *pool);
#endif
/** Allocate message from pool and clear data
*
* The pool must be created using bcmos_pool_create()
* \param[in] pool Message pool handle
* \returns msg pointer or NULL if the pool is empty.
* "data" and "release" fields in the returned message are pre-set
* Once no longer needed, the message must be released using bcmos_msg_free()
*/
#ifdef BCMOS_BLK_POOL_DEBUG
static inline bcmos_msg *bcmos_msg_pool_calloc_func(bcmos_msg_pool *pool, const char *func, int line)
{
bcmos_msg *msg = bcmos_msg_pool_alloc_func(pool, func, line);
if (msg)
{
memset(msg->data, 0, msg->size);
}
return msg;
}
#define bcmos_msg_pool_calloc(pool) bcmos_msg_pool_calloc_func(pool, __FUNCTION__, __LINE__)
#else
static inline bcmos_msg *bcmos_msg_pool_calloc(bcmos_msg_pool *pool)
{
bcmos_msg *msg = bcmos_msg_pool_alloc(pool);
if (msg)
{
memset(msg->data, 0, msg->size);
}
return msg;
}
#endif
/** Get pool info
*
* The pool must be created using bcmos_pool_create()
* \param[in] pool Message pool handle
* \param[out] info Message pool info
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_msg_pool_query(const bcmos_msg_pool *pool, bcmos_msg_pool_info *info);
/** Message pool iterator
* \param[in] prev Previous message pool. *prev==NULL - get first
* \return: BCM_ERR_OK, BCM_ERR_NOENT, BCM_ERR_NO_MORE
*/
bcmos_errno bcmos_msg_pool_get_next(const bcmos_msg_pool **prev);
/** @} system_msg */
/** \addtogroup system_module
* @{
*/
/** Max number of modules per task. Must be <= 32 */
#define BCMOS_MAX_MODULES_PER_TASK 8
/** Module parameters */
typedef struct
{
bcmos_msg_queue_parm qparm; /**< Message queue parameters */
F_bcmos_module_init init; /**< Init callback */
F_bcmos_module_exit exit; /**< Exit callback */
long data; /**< Module context initial value. Also passed to init and exit callbacks */
} bcmos_module_parm;
/** Module control block */
typedef struct bcmos_module bcmos_module;
/** Register module
*
* \param[in] module_id Module id
* \param[in] task Owner task ID
* \param[in] parm Module parameters
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_module_create(bcmos_module_id module_id, bcmos_task *task, bcmos_module_parm *parm);
/** Un-register module
*
* \param[in] module_id Module id
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_module_destroy(bcmos_module_id module_id);
/** Get current module id in the current task
*
* \returns module_id
*/
bcmos_module_id bcmos_module_current(void);
/** Get module context
*
* Module context is initialized as module_parm.data and can be modified using
* bcmos_module_context_set()
*
* \param[in] module_id Module_id
* \returns context pointer set by bcmos_module_context_set() or
*
* NULL if module_id is invalid or context is not set.
*/
void *bcmos_module_context(bcmos_module_id module_id);
/** Set module context
*
* Context is an arbitrary structure used to store module-specific data.
* Usually this function is called from module init() callback
*
* \param[in] module_id Module_id
* \param[in] context Module context pointer
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_module_context_set(bcmos_module_id module_id, void *context);
/* module control blocks */
extern bcmos_module *bcmos_modules[BCMOS_MODULE_ID__NUM_OF];
static inline bcmos_module *_bcmos_module_get(bcmos_module_id module_id)
{
bcmos_module *module = bcmos_modules[module_id];
if ((unsigned)module_id >= BCMOS_MODULE_ID__NUM_OF)
return NULL;
return module;
}
/** Query module
*
* \param[in] module_id Module_id
* \param[out] task Task that owns the module
* \param[out] info Module queue info
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_module_query(bcmos_module_id module_id, const bcmos_task **task, bcmos_msg_queue_info *info);
/** Check that all registered bcmos_modules have a name
* assigned.
*
* \returns 0=OK or error code.
*/
bcmos_errno bcmos_modules_name_check(void);
/** @} system_module */
/** \addtogroup system_event
* @{
*/
/** Registered event handler */
typedef void (*F_bcmos_event_handler)(bcmos_event_id event_id, uint32_t active_bits);
/** Event parameters */
typedef struct
{
const char *name; /**< Event set name */
bcmos_module_id module_id; /**< Module id. The module must be registered */
uint32_t mask; /**< Event bits module is interested in */
F_bcmos_event_handler handler; /**< Event handler. Called in module's context */
uint32_t flags; /**< TBD flags. E.g., inter-core */
} bcmos_event_parm;
/** Event control block */
typedef struct bcmos_event bcmos_event;
/** Create event set
*
* \param[in] event_id Event set id
* \param[in] parm Event parameters. Used in "integration" mode. NULL in "traditional" mode
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_event_create(bcmos_event_id event_id, bcmos_event_parm *parm);
/** Destroy event set created by bcmos_event_create()
*
* \param[in] event_id Event set id
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_event_destroy(bcmos_event_id event_id);
/** Raise event
*
* Raised event is delivered to module(s) that registered for it
* using bcmos_event_register() or to the task waiting for event
* using bcmos_event_recv()
*
* \param[in] event_id Event set id
* \param[in] active_bits Active bit mask
* \returns 0=OK or error code <0. Can only fail if event is not registered
*/
bcmos_errno bcmos_event_raise(bcmos_event_id event_id, uint32_t active_bits);
/** Wait for event
*
* This function is used in "traditional" mode.\n
* The caller can block for a time or indefinitely
*
* \param[in] event_id Event set id
* \param[in] mask Interesting bits. The functions returns when
* - timeout expires
* - event with (active_bits & mask) != 0 is raised
* \param[in] timeout timeout. can be 0, time in us or \ref BCMOS_WAIT_FOREVER
* \param[out] active_bits active bits in the event set. valid only if the function returns 0
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_event_recv(bcmos_event_id event_id, uint32_t mask,
uint32_t timeout, uint32_t *active_bits);
/* Event set array */
extern bcmos_event *bcmos_events[BCMOS_EVENT_ID__NUM_OF];
/* Get event givern the event id */
static inline bcmos_event *_bcmos_event_get(bcmos_event_id event_id)
{
bcmos_event *ev = bcmos_events[event_id];
if ((unsigned)event_id >= BCMOS_EVENT_ID__NUM_OF)
return NULL;
return ev;
}
/** @} system_event */
/** \addtogroup system_timer
* @{
*/
/** Max timer duration (us) */
#define BCMOS_MAX_TIMER_DURATION 0x80000000
/** Timer control block */
typedef struct bcmos_timer bcmos_timer;
/** Timer handler completion code */
typedef enum
{
BCMOS_TIMER_OK, /**< Restart timer if periodic or keep stopped if not */
BCMOS_TIMER_STOP /**< Do not restart periodic timer */
} bcmos_timer_rc;
/** Timer handler
* \param[in] timer Expired timer handle
* \param[in] data User data supplied at timer creation time
* \returns \ref bcmos_timer_rc
*/
typedef bcmos_timer_rc (*F_bcmos_timer_handler)(bcmos_timer *timer, long data);
typedef enum
{
BCMOS_TIMER_PARM_FLAGS_URGENT = 0, /**< Default behavior. If the timer owner is set, timer expiration
will be delivered as an urgent message. */
BCMOS_TIMER_PARM_FLAGS_NON_URGENT = 1 << 0, /**< If the timer owner is set, timer expiration will be delivered as
a normal (non-urgent) message. */
} bcmos_timer_parm_flags;
/** Timer parameters */
typedef struct
{
const char *name; /**< Timer name */
bcmos_module_id owner; /**< Timer owner. If set, timer expiration is delivered to the module
as a message */
bcmos_bool periodic; /**< TRUE=periodic */
F_bcmos_timer_handler handler; /**< Timer handler. Called in context of owner module
if set or timer ISR if owner==BCMOS_MODULE_ID_NONE */
long data; /**< data to pass to the handler */
bcmos_timer_parm_flags flags; /**< Flags to change the behavior of the timer */
} bcmos_timer_parm;
#ifndef BCMOS_TIMESTAMP_INLINE
/** Get current timestamp
* \returns the current system timestamp (us)
*/
uint32_t bcmos_timestamp(void);
/** Get current 64 bit timestamp
* \returns the current system timestamp (us)
* \note There is no guarantee that all 64 bit carry information.
* However, it is guaranteed that the timestamp wraps around
* not oftener than every 50 days (ms resolution)
*/
uint64_t bcmos_timestamp64(void);
#endif /* #ifndef BCMOS_TIMESTAMP_INLINE */
/** Create timer
*
* \param[in,out] timer timer control block
* \param[in] parm timer parameters
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_timer_create(bcmos_timer *timer, bcmos_timer_parm *parm);
/** Destroy timer
* The timer is stopped if running and destroyed
* \param[in] timer timer handle
*/
void bcmos_timer_destroy(bcmos_timer *timer);
/** Set timer handler
*
* \param[in,out] timer timer control block
* \param[in] handler timer handler
* \param[in] data data to be passed to the handler
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_timer_handler_set(bcmos_timer *timer, F_bcmos_timer_handler handler, long data);
/** (Re)start timer
* Stop timer if running and start it.
*
* \param[in] timer timer handle
* \param[in] delay delay in us
*/
void bcmos_timer_start(bcmos_timer *timer, uint32_t delay);
/** Stop timer if running
*
* \param[in] timer timer handle
*/
void bcmos_timer_stop(bcmos_timer *timer);
/** Suspend current task for a time
*
* \param[in] us sleep time (us)
*/
#ifdef BCMOS_TIMER_DEBUG
/** Query timer info
* \param[in] timer Timer control block
* \param[out] parm Timer parameters
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_timer_query(const bcmos_timer *timer, bcmos_timer_parm *parm);
/** Timer iterator
* \param[in] prev Previous timer. *prev==NULL - get first
* \return: BCM_ERR_OK, BCM_ERR_NOENT, BCM_ERR_NO_MORE
*/
bcmos_errno bcmos_timer_get_next(bcmos_timer **prev);
#endif
#ifndef BCMOS_USLEEP_INLINE
void bcmos_usleep(uint32_t us);
#endif /* #ifndef BCMOS_USLEEP_INLINE */
/** @} system_timer */
/** \addtogroup system_fastlock
* @{
*/
/** Fast lock control block */
typedef struct bcmos_fastlock bcmos_fastlock;
#ifndef BCMOS_FASTLOCK_INLINE
/** Init fastlock
* \param[in, out] lock fast lock control block
* \param[in] flags flags - TBD. E.g., single core / SMP
*/
void bcmos_fastlock_init(bcmos_fastlock *lock, uint32_t flags);
/** Take fast lock
* \param[in] lock fast lock
* \returns value of interrupt flags that should be used in unlock
*/
long bcmos_fastlock_lock(bcmos_fastlock *lock);
/** Release fast lock
* \param[in] lock fast lock
* \param[in] flags interrupt flags
*/
void bcmos_fastlock_unlock(bcmos_fastlock *lock, long flags);
#endif /* #ifndef BCMOS_FASTLOCK_INLINE */
/** @} system_fastlock */
/** \addtogroup system_mutex
* @{
*/
/** Mutex control block */
typedef struct bcmos_mutex bcmos_mutex;
#ifdef BCMOS_MUTEX_INLINE
#define BCMOS_MUTEX_CREATE_DESTROY_INLINE
#define BCMOS_MUTEX_LOCK_UNLOCK_INLINE
#endif
#ifndef BCMOS_MUTEX_CREATE_DESTROY_INLINE
/** Create recursive mutex
* \param[in, out] mutex Mutex control block
* \param[in] flags flags - TBD. E.g., single core / SMP
* \param[in] name name of the mutex (if OS supports), NULL means it will be auto-generated
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_mutex_create(bcmos_mutex *mutex, uint32_t flags, const char *name);
/** Destroy mutex
* \param[in] mutex Mutex control block
*/
void bcmos_mutex_destroy(bcmos_mutex *mutex);
#endif /* BCMOS_MUTEX_CREATE_DESTROY_INLINE */
#ifndef BCMOS_MUTEX_LOCK_UNLOCK_INLINE
/** Lock mutex
* \param[in] mutex Mutex control block
*/
void bcmos_mutex_lock(bcmos_mutex *mutex);
/** Release mutex
* \param[in] mutex Mutex control block
*/
void bcmos_mutex_unlock(bcmos_mutex *mutex);
#endif /* #ifndef BCMOS_MUTEX_LOCK_UNLOCK_INLINE */
/** @} system_mutex */
/** \addtogroup system_sem
* @{
*/
/** Semaphore control block */
typedef struct bcmos_sem bcmos_sem;
#ifdef BCMOS_SEM_INLINE
#define BCMOS_SEM_CREATE_DESTROY_INLINE
#define BCMOS_SEM_WAIT_INLINE
#define BCMOS_SEM_POST_INLINE
#endif
#ifndef BCMOS_SEM_CREATE_DESTROY_INLINE
/** Create semaphore
* \param[in, out] sem semaphore control block
* \param[in] count initial value of semaphore counter
* \param[in] flags flags - TBD. E.g., single core / SMP
* \param[in] name name of the semaphore (if OS supports), NULL means it will be auto-generated
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_sem_create(bcmos_sem *sem, uint32_t count, uint32_t flags, const char *name);
/** Destroy semaphore
* \param[in] sem semaphore control block
*/
void bcmos_sem_destroy(bcmos_sem *sem);
#endif /* BCMOS_SEM_CREATE_DESTROY_INLINE */
#ifndef BCMOS_SEM_WAIT_INLINE
/** Decrement semaphore counter. Wait if the counter is 0
*
* \param[in] sem semaphore control block
* \param[in] timeout timeout. can be 0, time in us or \ref BCMOS_WAIT_FOREVER
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_sem_wait(bcmos_sem *sem, uint32_t timeout);
#endif /* #ifndef BCMOS_SEM_WAIT_INLINE */
#ifndef BCMOS_SEM_POST_INLINE
/** Increment semaphore counter
* \param[in] sem semaphore control block
*/
void bcmos_sem_post(bcmos_sem *sem);
#endif /* #ifndef BCMOS_SEM_POST_INLINE */
/** @} system_sem */
/*
* print support
*/
/** Print cloning/redirection mode */
typedef enum
{
BCMOS_PRINT_REDIRECT_MODE_NONE, /**< No cloning, redirection */
BCMOS_PRINT_REDIRECT_MODE_REDIRECT, /**< Redirect console output. Do not print on the serial console */
BCMOS_PRINT_REDIRECT_MODE_CLONE /**< Clone console output to redirection callback */
} bcmos_print_redirect_mode;
/** Print re-direction/cloning callback */
typedef int (*bcmos_print_redirect_cb)(void *data, const char *format, va_list ap);
/** Set up print redirection/cloning
* \param[in] mode redirection/cloning mode
* \param[in] cb redirection callback
* \param[in] data opaque data to be passed to cb
* \returns 0=OK or error <0
*/
bcmos_errno bcmos_print_redirect(bcmos_print_redirect_mode mode, bcmos_print_redirect_cb cb, void *data);
/* Print on the console with optional cloning / redirection
* \param[in] format printf format
* \param[in] ap argument list
* \returns number of characters printed >= 0 or error < 0
*/
int bcmos_vprintf(const char *format, va_list ap);
/* Print on the console with optional cloning / redirection
* \param[in] format printf format
* \returns number of characters printed >= 0 or error < 0
*/
int bcmos_printf(const char *format, ...);
/** \addtogroup system_trace
* @{
*/
/** Trace level */
typedef enum
{
BCMOS_TRACE_LEVEL_NONE, /**< No trace output */
BCMOS_TRACE_LEVEL_ERROR, /**< Trace errors */
BCMOS_TRACE_LEVEL_WARNING, /**< Trace errors + warnings */
BCMOS_TRACE_LEVEL_INFO, /**< Trace errors + warnings + info */
BCMOS_TRACE_LEVEL_VERBOSE, /**< Trace errors + warnings + info + verbose info */
BCMOS_TRACE_LEVEL_DEBUG, /**< Trace everything */
} bcmos_trace_level;
extern bcmos_trace_level bcmos_sys_trace_level;
#ifdef BCMOS_TRACE_PRINTF
#define BCMOS_TRACE_INLINE
#endif
#ifndef BCMOS_TRACE_INLINE
/** Print trace
*
* \param[in] level Record trace at level
* \param[in] format printf-like format
*/
void bcmos_trace(bcmos_trace_level level, const char *format, ...);
#endif
/* Print trace */
#ifdef BCMOS_TRACE_PRINTF
#define bcmos_trace(level, fmt, args...) bcmos_printf(fmt, ## args)
#endif
/** Set current trace level
* \param[in] level New trace level
* \returns old trace level
*/
static inline bcmos_trace_level bcmos_trace_level_set(bcmos_trace_level level)
{
bcmos_trace_level old_level = bcmos_sys_trace_level;
bcmos_sys_trace_level = level;
return old_level;
}
/** Get current trace level
* \returns trace level
*/
static inline bcmos_trace_level bcmos_trace_level_get(void)
{
return bcmos_sys_trace_level;
}
/** Print trace conditionally, depending on the current trace level
* \param[in] level Record trace at level
* \param[in] fmt printf-like format
* \param[in] args printf-like arguments
*/
#define BCMOS_TRACE(level, fmt, args...) \
do \
{ \
if (level <= bcmos_sys_trace_level) \
bcmos_trace(level, "%s#%d> " fmt, __FUNCTION__, __LINE__, ## args); \
} while (0)
/** Print error trace conditionally, depending on the current trace level
* \param[in] fmt printf-like format
* \param[in] args printf-like arguments
*/
extern f_bcmolt_sw_error_handler sw_error_handler;
#define BCMOS_TRACE_ERR(fmt, args...) \
do \
{ \
BCMOS_TRACE(BCMOS_TRACE_LEVEL_ERROR, "ERR: " fmt, ## args); \
if (sw_error_handler != NULL) \
{ \
sw_error_handler(0xff, __FILE__, __LINE__); \
} \
_bcmos_backtrace(); \
} while (0)
/** Print info trace conditionally, depending on the current trace level
* \param[in] fmt printf-like format
* \param[in] args printf-like arguments
*/
#define BCMOS_TRACE_INFO(fmt, args...) \
BCMOS_TRACE(BCMOS_TRACE_LEVEL_INFO, "INF: " fmt, ## args)
/** Print verbose info trace conditionally, depending on the current trace level
* \param[in] fmt printf-like format
* \param[in] args printf-like arguments
*/
#define BCMOS_TRACE_VERBOSE(fmt, args...) \
BCMOS_TRACE(BCMOS_TRACE_LEVEL_VERBOSE, "VRB: " fmt, ## args)
/** Print debug trace conditionally, depending on the current trace level
* \param[in] fmt printf-like format
* \param[in] args printf-like arguments
*/
#define BCMOS_TRACE_DEBUG(fmt, args...) \
BCMOS_TRACE(BCMOS_TRACE_LEVEL_DEBUG, "DBG: " fmt, ## args)
/** Print trace conditionally based on return code and return
* \param[in] rc return code
* \param[in] fmt printf-like format
* \param[in] args printf-like arguments
* \returns rc
*/
#define BCMOS_TRACE_RETURN(rc, fmt, args...) \
do { \
if (rc) \
BCMOS_TRACE_ERR("status:%s :" fmt, bcmos_strerror(rc), ## args); \
else \
BCMOS_TRACE_INFO("success: " fmt, ## args); \
return rc; \
} while (0)
#define BCMOS_TRACE_CHECK_RETURN(cond,rc,fmt,args...) \
do { \
if (cond) \
{\
BCMOS_TRACE_ERR( #cond ": status:%s :" fmt, bcmos_strerror(rc), ## args); \
return rc; \
}\
} while (0)
#define BCMOS_TRACE_CHECK_RETURN_TYPE(cond,err,ret,fmt,args...) \
do { \
if (cond) \
{\
BCMOS_TRACE_ERR( #cond ": status:%s :" fmt, bcmos_strerror(err), ## args); \
return ret; \
}\
} while (0)
#define BCMOS_TRACE_CHECK_RETURN_VOID(cond,err,fmt,args...) \
do { \
if (cond) \
{\
BCMOS_TRACE_ERR( #cond ": status:%s :" fmt, bcmos_strerror(err), ## args); \
return; \
}\
} while (0)
#define BCMOS_CHECK_RETURN(cond,err,ret) \
do { \
if (cond) \
{\
BCMOS_TRACE_ERR( #cond ": status:%s\n", bcmos_strerror(err)); \
return ret; \
}\
} while (0)
#define BCMOS_CHECK_RETURN_ERROR(cond,err) BCMOS_CHECK_RETURN(cond,err,err)
#define BCMOS_RETURN_ON_ERROR(err) BCMOS_CHECK_RETURN(BCM_ERR_OK != err, err, /*this space intentionally left blank*/)
#define BCMOS_RETURN_IF_ERROR(err) BCMOS_CHECK_RETURN_ERROR(BCM_ERR_OK != err, err)
#define BCMOS_BREAK_IF_ERROR(err) if (err != BCM_ERR_OK) break
#define BCMOS_TRACE_IF_ERROR(err) \
do { \
if ((err) != BCM_ERR_OK) \
BCMOS_TRACE_ERR("error %s (%d)\n", bcmos_strerror(err), err); \
} while (0)
/** @} system_trace */
/*
* Low level services
*/
/** \addtogroup system_buf
* @{
*/
/** Transport/network buffer */
typedef struct bcmos_buf bcmos_buf;
/** @} system_buf */
/** Round a number up to the specified power of 2 */
#define BCMOS_ROUND_UP(n, m) (((n) + (m) - 1) & ~((m) - 1))
/** Round a number up to the nearest word multiple */
#define BCMOS_ROUND_TO_WORD(n) BCMOS_ROUND_UP(n, sizeof(size_t))
/* BCMOS_DIVIDE_ROUND_UP(integer_dividend / integer_divisor) == (integer_dividend + integer_divisor - 1) / integer_divisor */
#define BCMOS_DIVIDE_ROUND_UP(n, m) (((n) + (m) - 1) / (m))
#define TAB " "
#define TAB2 TAB TAB
#define TAB3 TAB2 TAB
#define TAB4 TAB2 TAB2
static inline bcmos_bool bcmos_mac_is_zero(bcmos_mac_address *mac)
{
if (mac->u8[0]==0 && mac->u8[1]==0 && mac->u8[2]==0 && mac->u8[3]==0 && mac->u8[4]==0 && mac->u8[5]==0)
return BCMOS_TRUE;
else
return BCMOS_FALSE;
}
/**
* Returns TRUE if module has been active since last periodic check.
* Also returns true if module has not yet been created.
*
* @param period Time in microseconds since last check
* @param module_id Module ID
*
* @return True if healthy
*/
bcmos_bool bcmos_module_is_healthy(uint32_t period, bcmos_module_id module_id);
bcmos_errno bcmos_modules_healthcheck_init(void);
/**
* This function is for debug purposes for the health check feature.
*
* @param module_id
*/
void healthcheck_print(bcmos_module_id module_id);
/* An optional callback to be executed on completion of an oops handling. */
typedef void (*bcmos_oops_complete_cb_t)(void);
extern bcmos_oops_complete_cb_t bcmos_oops_complete_cb;
#endif /* BCMOS_SYSTEM_COMMON_H_ */
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#ifndef BCM_DEV_LOG_CLI_H_
#define BCM_DEV_LOG_CLI_H_
#include <bcmcli.h>
#include <bcmcli_session.h>
#include "bcm_dev_log_task.h"
typedef struct
{
bcmcli_session *session;
dev_log_id log_id;
bcm_dev_log_level log_level;
char str[MAX_DEV_LOG_STRING_NET_SIZE];
uint32_t free_len;
} bcm_dev_log_cli_session;
/* create a CLI session adaptation layer that outputs to a dev log instead of to a CLI shell */
bcmos_errno bcm_dev_log_cli_session_create(
dev_log_id log_id,
bcm_dev_log_level log_level,
bcm_dev_log_cli_session **session);
/** initialize the dev log CLI functions
*
* \param[in] parent Parent directory handle. NULL=root
* \return new directory handle or NULL in case of failure
*/
bcmcli_entry *bcm_dev_log_cli_init(bcmcli_entry *root_dir);
#endif /* BCM_DEV_LOG_CLI_H_ */
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#include "bcmos_rw_lock.h"
struct bcmos_rw_lock
{
/* the actual lock, held by the writer, used by the reader to safely obtain a read lock, but not held to allow
* multiple readers */
bcmos_mutex lock;
/* used by the writer to prevent new readers from obtaining read locks while a writer is waiting */
bcmos_mutex read_lock;
/* used by readers to signal waiting writers that they have finished reading */
bcmos_sem write_lock;
/* current number of readers */
uint32_t readers;
};
bcmos_errno bcmos_rw_lock_create(bcmos_rw_lock **lock)
{
bcmos_errno err;
*lock = (bcmos_rw_lock*)bcmos_calloc(sizeof(bcmos_rw_lock));
if (*lock == NULL)
{
return BCM_ERR_NOMEM;
}
do
{
if (BCM_ERR_OK != (err = bcmos_mutex_create(&(*lock)->lock, 0, "bcmos_rw_lock_create_lock")))
{
break;
}
if (BCM_ERR_OK != (err = bcmos_mutex_create(&(*lock)->read_lock, 0, "bcmos_rw_lock_create_rw_lock")))
{
break;
}
(*lock)->readers = 0;
if (BCM_ERR_OK != (err = bcmos_sem_create(&(*lock)->write_lock, 1, 0, "bcmos_rw_lock_create_write_lock")))
{
break;
}
}while(0);
if(BCM_ERR_OK != err)
{
bcmos_free(lock);
}
return err;
}
/*lint -e{455} suppress "thread mutex has not been locked" */
void bcmos_rw_write_lock(bcmos_rw_lock* lock)
{
/* prevent any new readers from trying to obtain a read lock */
bcmos_mutex_lock(&lock->read_lock);
/* lock the actual lock */
bcmos_mutex_lock(&lock->lock);
while (lock->readers != 0)
{
/* there are still readers holding read locks, release the lock */
bcmos_mutex_unlock(&lock->lock);
/* wait for the signal from the last reader before trying again */
bcmos_sem_wait(&lock->write_lock, BCMOS_WAIT_FOREVER);
/* lock the actual lock and check for readers again */
bcmos_mutex_lock(&lock->lock);
}
/* no more readers, allow new readers to wait on the lock */
bcmos_mutex_unlock(&lock->read_lock);
}
/*lint +e{454} suppress "thread mutex has not been locked" */
void bcmos_rw_write_release(bcmos_rw_lock* lock)
{
/*lint --e{455} suppress "thread mutex has not been locked" */
bcmos_mutex_unlock(&lock->lock);
}
void bcmos_rw_read_lock(bcmos_rw_lock* lock)
{
/* wait for anyone trying to get a write lock */
bcmos_mutex_lock(&lock->read_lock);
/* wait for the lock to be released */
bcmos_mutex_lock(&lock->lock);
lock->readers++;
/* reset the signal to the writers */
bcmos_sem_wait(&lock->write_lock, BCMOS_NO_WAIT);
/* all done, release everything so other readers can get a read lock */
bcmos_mutex_unlock(&lock->lock);
bcmos_mutex_unlock(&lock->read_lock);
}
void bcmos_rw_read_release(bcmos_rw_lock* lock)
{
/* get a lock to prevent interruptions */
bcmos_mutex_lock(&lock->lock);
if (--lock->readers == 0)
{
/* if we're the last reader, signal that the lock is available for a writer */
bcmos_sem_post(&lock->write_lock);
}
bcmos_mutex_unlock(&lock->lock);
}
<file_sep>bcm_add_subdirectory(c-ares)
bcm_add_subdirectory(grpc)
bcm_add_subdirectory(libev)
bcm_add_subdirectory(libgcrypt)
bcm_add_subdirectory(libgpg-error)
bcm_add_subdirectory(libnetconf2)
bcm_add_subdirectory(libredblack)
bcm_add_subdirectory(libssh)
bcm_add_subdirectory(libyang)
bcm_add_subdirectory(linenoise)
bcm_add_subdirectory(netopeer2)
bcm_add_subdirectory(openssl)
bcm_add_subdirectory(pcre)
bcm_add_subdirectory(protobuf)
bcm_add_subdirectory(protobuf-c)
bcm_add_subdirectory(sysrepo)
bcm_add_subdirectory(yang-models)
bcm_add_subdirectory(zlib)
<file_sep># protobuf-c library
#
include(third_party)
bcm_3rdparty_module_name(protobuf-c "1.3.2")
bcm_3rdparty_download_wget("https://github.com/protobuf-c/protobuf-c/releases/download/v${PROTOBUF-C_VERSION}"
"protobuf-c-${PROTOBUF-C_VERSION}.tar.gz")
bcm_3rdparty_add_dependencies(protobuf)
bcm_3rdparty_add_build_options(PKG_CONFIG_PATH=${CMAKE_BINARY_DIR}/fs/lib/pkgconfig)
bcm_3rdparty_build_automake()
bcm_3rdparty_export()
<file_sep>/*
<:copyright-BRCM:2016-2019:Apache:standard
Copyright (c) 2016-2019 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
* :>
*/
#ifndef BCMOLT_BUF_H_
#define BCMOLT_BUF_H_
#include "bcmos_system.h"
/** Generic stream object */
typedef struct bcmolt_buf_io
{
long handle;
int (*read)(long handle, uint32_t offset, uint8_t *data, uint32_t length);
int (*write)(long handle, uint32_t offset, const uint8_t *data, uint32_t length);
} bcmolt_buf_io;
typedef struct bcmolt_buf bcmolt_buf;
struct bcmolt_buf
{
uint8_t *start; /**< Pointer to the start of the buffer */
uint8_t *curr; /**< Pointer to the current position in the buffer */
uint32_t len; /**< Total Length of buffer */
bcmolt_buf_io io;/**< Optional file IO callbacks */
};
/* Serialization buffer endianness */
#define BCMOLT_BUF_ENDIAN_FIXED BCMOS_ENDIAN_BIG
#if BCMOLT_BUF_ENDIAN_FIXED == BCMOS_ENDIAN_BIG
#define BCMOLT_BUF_ENDIAN_BUF_TO_CPU(size, n) BCMOS_ENDIAN_BIG_TO_CPU_##size(n)
#define BCMOLT_BUF_ENDIAN_CPU_TO_BUF(size, n) BCMOS_ENDIAN_CPU_TO_BIG_##size(n)
#else
#define BCMOLT_BUF_ENDIAN_BUF_TO_CPU(size, n) BCMOS_ENDIAN_LITTLE_TO_CPU_##size(n)
#define BCMOLT_BUF_ENDIAN_CPU_TO_BUF(size, n) BCMOS_ENDIAN_CPU_TO_LITTLE_##size(n)
#endif
/** Initalize a bcmolt_buf memory stream
*
* \param buf bcmolt_buf instance
* \param size Total length of the buffer stream in bytes
* \param start Location in memory where the data is located
*/
void bcmolt_buf_init(bcmolt_buf *buf, uint32_t size, uint8_t *start);
/** Initalize a bcmolt_buf file IO stream
*
* \param buf bcmolt_buf instance
* \param size Total length of the buffer stream in bytes
* \param io IO callbacks
*/
void bcmolt_buf_init_io(bcmolt_buf *buf, uint32_t size, const bcmolt_buf_io *io);
/** Set the length of a bcmolt_buf instance
*
* \param buf bcmolt_buf instance
* \param size Total length of the buffer stream in bytes
*/
void bcmolt_buf_set_length(bcmolt_buf *buf, uint32_t size);
/** Read from the buffer
*
* \param buf bcmolt_buf instance
* \param to Where to read to
* \param len Number of bytes to copy
*
* \return BCMOS_TRUE if successfully copied
*/
bcmos_bool bcmolt_buf_read(bcmolt_buf *buf, void *to, size_t len);
/** Transfer bytes from one buf to another
*
* \param *from Source buffer
* \param *to Destination buffer
* \param bytes Number of bytes to transfer
* \return BCMOS_TRUE if successfully transferred
*/
bcmos_bool bcmolt_buf_transfer_bytes(bcmolt_buf *from, bcmolt_buf *to, uint32_t bytes);
/** Write to the buffer
*
* \param buf bcmolt_buf instance
* \param from Source, to copy from
* \param len Number of bytes to copy
*
* \return BCMOS_TRUE if successfully copied
*/
bcmos_bool bcmolt_buf_write(bcmolt_buf *buf, const void *from, size_t len);
/** Move the current pointer to a given position in the buffer
*
* \param pos Byte position in the buffer to move the current pointer to
*
* \param *buf Input buffer
* \return BCMOS_FALSE if len takes us past the end of buffer
*/
bcmos_bool bcmolt_buf_set_pos(bcmolt_buf *buf, uint32_t pos);
/** Move the current pointer ahead by given number of bytes
*
* \param buf bcmolt_buf instance
* \param len Number of bytes to skip
*
* \return BCMOS_FALSE if len takes us past the end of buffer
*/
bcmos_bool bcmolt_buf_skip(bcmolt_buf *buf, uint32_t len);
/** Move the current pointer back by given number of bytes
*
* \param buf bcmolt_buf instance
* \param len Number of bytes to go back
*
* \return BCMOS_FALSE if len takes us past the start of buffer
*/
bcmos_bool bcmolt_buf_rewind(bcmolt_buf *buf, uint32_t len);
/** Get the current buffer pointer
*
* \param buf bcmolt_buf instance
*
* \return the current buffer pointer
*/
static inline uint8_t *bcmolt_buf_snap_get(const bcmolt_buf *buf)
{
BUG_ON(buf->io.read != NULL); /* snap_get and snap_restore are not available with file I/O */
return buf->curr;
}
/** Move the current pointer to a snapped location
*
* \param buf bcmolt_buf instance
* \param snap snapped location
*/
static inline void bcmolt_buf_snap_restore(bcmolt_buf *buf, uint8_t *snap)
{
BUG_ON(buf->io.read != NULL); /* snap_get and snap_restore are not available with file I/O */
buf->curr = snap;
}
/** Get the length of unprocessed bytes in given stream
*
* \param buf Input buffer
*
* \return The number of remaining bytes in the buffer
*/
static inline uint32_t bcmolt_buf_get_remaining_size(const bcmolt_buf *buf)
{
return (uint32_t)((buf->start + buf->len) - buf->curr);
}
/** Get amount of buf that has been read or written so far
*
* \param buf Input buffer
* \return Amount of buffer used
*/
static inline uint32_t bcmolt_buf_get_used(const bcmolt_buf *buf)
{
return (uint32_t)(buf->curr - buf->start);
}
/** Reads a uint8_t from a buffer
*
* \param buf Buffer to read from
* \param val uint8_t to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_u8(bcmolt_buf *buf, uint8_t *val)
{
return bcmolt_buf_read(buf, val, sizeof(*val));
}
/** Writes a uint8_t to a buffer
*
* \param buf Buffer to write to
* \param val uint8_t to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_u8(bcmolt_buf *buf, uint8_t val)
{
return bcmolt_buf_write(buf, &val, sizeof(val));
}
/** Reads a boolean from a buffer
*
* \param *buf
* \param *val
*/
bcmos_bool bcmolt_buf_read_bool(bcmolt_buf *buf, bcmos_bool *val);
/** Writes a bcmos_bool to a buffer
*
* \param buf Buffer to write to
* \param val uint8_t to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_bool(bcmolt_buf *buf, bcmos_bool val)
{
return bcmolt_buf_write_u8(buf, val ? 1 : 0);
}
/** Reads a int8_t from a buffer
*
* \param buf Buffer to read from
* \param val int8_t to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_s8(bcmolt_buf *buf, int8_t *val)
{
return bcmolt_buf_read_u8(buf, (uint8_t *)val);
}
/** Writes a int8_t to a buffer
*
* \param buf Buffer to write to
* \param val int8_t to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_s8(bcmolt_buf *buf, int8_t val)
{
return bcmolt_buf_write_u8(buf, (uint8_t)val);
}
/** Reads a uint16_t from a buffer
*
* \param buf Buffer to read from
* \param val uint16_t to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_u16(bcmolt_buf *buf, uint16_t *val)
{
bcmos_bool res = bcmolt_buf_read(buf, val, sizeof(*val));
*val = BCMOLT_BUF_ENDIAN_BUF_TO_CPU(U16, *val);
return res;
}
/** Reads a uint16_t from a Big Endian buffer
*
* \param buf Buffer to read from
* \param val uint16_t to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_u16_be(bcmolt_buf *buf, uint16_t *val)
{
bcmos_bool res = bcmolt_buf_read(buf, val, sizeof(*val));
*val = BCMOS_ENDIAN_BIG_TO_CPU_U16(*val);
return res;
}
/** Writes a uint16_t to a buffer
*
* \param buf Buffer to write to
* \param val uint16_t to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_u16(bcmolt_buf *buf, uint16_t val)
{
val = BCMOLT_BUF_ENDIAN_CPU_TO_BUF(U16, val);
return bcmolt_buf_write(buf, &val, sizeof(val));
}
/** Writes a uint16_t to a Big Endian buffer
*
* \param buf Buffer to write to
* \param val uint16_t to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_u16_be(bcmolt_buf *buf, uint16_t val)
{
val = BCMOS_ENDIAN_CPU_TO_BIG_U16(val);
return bcmolt_buf_write(buf, &val, sizeof(val));
}
/** Reads a int16_t from a buffer
*
* \param buf Buffer to read from
* \param val int16_t to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_s16(bcmolt_buf *buf, int16_t *val)
{
return bcmolt_buf_read_u16(buf, (uint16_t *)val);
}
/** Reads a int16_t from a Big Endian buffer
*
* \param buf Buffer to read from
* \param val int16_t to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_s16_be(bcmolt_buf *buf, int16_t *val)
{
return bcmolt_buf_read_u16_be(buf, (uint16_t *)val);
}
/** Writes int16_t to a buffer
*
* \param buf Buffer to write to
* \param val int16_t to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_s16(bcmolt_buf *buf, int16_t val)
{
return bcmolt_buf_write_u16(buf, (uint16_t)val);
}
/** Writes int16_t to a Big Endian buffer
*
* \param buf Buffer to write to
* \param val int16_t to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_s16_be(bcmolt_buf *buf, int16_t val)
{
return bcmolt_buf_write_u16_be(buf, (uint16_t)val);
}
/** Reads a bcmos_u24 from a buffer
*
* \param buf Buffer to read from
* \param val bcmos_u24 to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_u24(bcmolt_buf *buf, uint24_t *val)
{
return bcmolt_buf_read_u8(buf, &(val->low_hi.hi)) &&
bcmolt_buf_read_u8(buf, &(val->low_hi.mid)) &&
bcmolt_buf_read_u8(buf, &(val->low_hi.low));
}
/** Writes a bcmos_u24 to a buffer
*
* \param buf Buffer to write to
* \param val bcmos_u24 to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_u24(bcmolt_buf *buf, uint24_t val)
{
return bcmolt_buf_write_u8(buf, val.low_hi.hi) &&
bcmolt_buf_write_u8(buf, val.low_hi.mid) &&
bcmolt_buf_write_u8(buf, val.low_hi.low);
}
/** Reads a uint32_t from a buffer
*
* \param buf Buffer to read from
* \param val uint32_t to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_u32(bcmolt_buf *buf, uint32_t *val)
{
bcmos_bool res = bcmolt_buf_read(buf, val, sizeof(*val));
*val = BCMOLT_BUF_ENDIAN_BUF_TO_CPU(U32, *val);
return res;
}
/** Reads a uint32_t from a Big Endian buffer
*
* \param buf Buffer to read from
* \param val uint32_t to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_u32_be(bcmolt_buf *buf, uint32_t *val)
{
bcmos_bool res = bcmolt_buf_read(buf, val, sizeof(*val));
*val = BCMOS_ENDIAN_BIG_TO_CPU_U32(*val);
return res;
}
/** Writes a uint32_t to a buffer
*
* \param buf Buffer to write to
* \param val uint32_t to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_u32(bcmolt_buf *buf, uint32_t val)
{
val = BCMOLT_BUF_ENDIAN_CPU_TO_BUF(U32, val);
return bcmolt_buf_write(buf, &val, sizeof(val));
}
/** Writes a uint32_t to a Big Endian buffer
*
* \param buf Buffer to write to
* \param val uint32_t to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_u32_be(bcmolt_buf *buf, uint32_t val)
{
val = BCMOS_ENDIAN_CPU_TO_BIG_U32(val);
return bcmolt_buf_write(buf, &val, sizeof(val));
}
/** Reads a int32_t from a buffer
*
* \param buf Buffer to read from
* \param val int32_t to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_s32(bcmolt_buf *buf, int32_t *val)
{
return bcmolt_buf_read_u32(buf, (uint32_t *)val);
}
/** Reads a int32_t from a big endian buffer
*
* \param buf Buffer to read from
* \param val int32_t to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_s32_be(bcmolt_buf *buf, int32_t *val)
{
return bcmolt_buf_read_u32_be(buf, (uint32_t *)val);
}
/** Writes a int32_t to a buffer
*
* \param buf Buffer to write to
* \param val int32_t to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_s32(bcmolt_buf *buf, int32_t val)
{
return bcmolt_buf_write_u32(buf, (uint32_t)val);
}
/** Writes a int32_t to a Big Endian buffer
*
* \param buf Buffer to write to
* \param val int32_t to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_s32_be(bcmolt_buf *buf, int32_t val)
{
return bcmolt_buf_write_u32_be(buf, (uint32_t)val);
}
/** Reads a uint64_t from a buffer
*
* \param buf Buffer to read from
* \param val uint64_t to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_u64(bcmolt_buf *buf, uint64_t *val)
{
bcmos_bool res = bcmolt_buf_read(buf, val, sizeof(*val));
*val = BCMOLT_BUF_ENDIAN_BUF_TO_CPU(U64, *val);
return res;
}
/** Reads a uint64_t from a Big Endian buffer
*
* \param buf Buffer to read from
* \param val uint64_t to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_u64_be(bcmolt_buf *buf, uint64_t *val)
{
bcmos_bool res = bcmolt_buf_read(buf, val, sizeof(*val));
*val = BCMOS_ENDIAN_BIG_TO_CPU_U64(*val);
return res;
}
/** Writes a uint64_t to a buffer
*
* \param buf Buffer to write to
* \param val uint64_t to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_u64(bcmolt_buf *buf, uint64_t val)
{
val = BCMOLT_BUF_ENDIAN_CPU_TO_BUF(U64, val);
return bcmolt_buf_write(buf, &val, sizeof(val));
}
/** Writes a uint64_t to a Big Endian buffer
*
* \param buf Buffer to write to
* \param val uint64_t to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_u64_be(bcmolt_buf *buf, uint64_t val)
{
val = BCMOS_ENDIAN_CPU_TO_BIG_U64(val);
return bcmolt_buf_write(buf, &val, sizeof(val));
}
/** Reads a int64_t from a buffer
*
* \param buf Buffer to read from
* \param val int64_t to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_s64(bcmolt_buf *buf, int64_t *val)
{
return bcmolt_buf_read_u64(buf, (uint64_t *)val);
}
/** Reads a int64_t from a Big Endian buffer
*
* \param buf Buffer to read from
* \param val int64_t to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_s64_be(bcmolt_buf *buf, int64_t *val)
{
return bcmolt_buf_read_u64_be(buf, (uint64_t *)val);
}
/** Writes a int64_t to a buffer
*
* \param buf Buffer to write to
* \param val int64_t to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_s64(bcmolt_buf *buf, int64_t val)
{
return bcmolt_buf_write_u64(buf, (uint64_t)val);
}
/** Writes a int64_t to a Big Endian buffer
*
* \param buf Buffer to write to
* \param val int64_t to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_s64_be(bcmolt_buf *buf, int64_t val)
{
return bcmolt_buf_write_u64_be(buf, (uint64_t)val);
}
/** Reads a float from a buffer
*
* \param buf Buffer to read from
* \param val float to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_float(bcmolt_buf *buf, float *val)
{
return bcmolt_buf_read_u32(buf, (uint32_t *)val);
}
/** Writes a float to a buffer
*
* \param buf Buffer to write to
* \param val float to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_float(bcmolt_buf *buf, float val)
{
uint32_t *num = (uint32_t *)&val;
return bcmolt_buf_write_u32(buf, *num);
}
/** Reads a double from a buffer
*
* \param buf Buffer to read from
* \param val double to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_double(bcmolt_buf *buf, double *val)
{
return bcmolt_buf_read_u64(buf, (uint64_t *)val);
}
/** Writes a double to a buffer
*
* \param buf Buffer to write to
* \param val double to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_double(bcmolt_buf *buf, double val)
{
uint64_t *num = (uint64_t *)&val;
return bcmolt_buf_write_u64(buf, *num);
}
/** Reads a bcmos_vlan_tag from a buffer
*
* \param buf Buffer to read from
* \param val bcmos_vlan_tag to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_vlan_tag(bcmolt_buf *buf, bcmos_vlan_tag *val)
{
return bcmolt_buf_read_u16(buf, (uint16_t *)val);
}
/** Writes a bcmos_vlan_tag to a buffer
*
* \param buf Buffer to write to
* \param val bcmos_vlan_tag to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_vlan_tag(bcmolt_buf *buf, bcmos_vlan_tag val)
{
return bcmolt_buf_write_u16(buf, (uint16_t)val);
}
/** Reads a bcmos_mac_address from a buffer
*
* \param buf Buffer to read from
* \param val bcmos_mac_address to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_mac_address(bcmolt_buf *buf, bcmos_mac_address *val)
{
return bcmolt_buf_read(buf, val, sizeof(bcmos_mac_address));
}
/** Writes a bcmos_mac_address to a buffer
*
* \param buf Buffer to write to
* \param val bcmos_mac_address to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_mac_address(bcmolt_buf *buf, bcmos_mac_address val)
{
return bcmolt_buf_write(buf, &val, sizeof(bcmos_mac_address));
}
/** Reads a bcmos_ipv4_address from a buffer
*
* \param buf Buffer to read from
* \param val bcmos_ipv4_address to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_ipv4_address(bcmolt_buf *buf, bcmos_ipv4_address *val)
{
return bcmolt_buf_read_u32(buf, &val->u32);
}
/** Writes a bcmos_ipv4_address to a buffer
*
* \param buf Buffer to write to
* \param val bcmos_ipv4_address to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_ipv4_address(bcmolt_buf *buf, bcmos_ipv4_address val)
{
return bcmolt_buf_write_u32(buf, val.u32);
}
/** Reads a bcmos_ipv6_address from a buffer
*
* \param buf Buffer to read from
* \param val bcmos_ipv6_address to read
*
* \return BCMOS_TRUE if read successful
*/
static inline bcmos_bool bcmolt_buf_read_ipv6_address(bcmolt_buf *buf, bcmos_ipv6_address *val)
{
return bcmolt_buf_read(buf, val->u8, sizeof(bcmos_ipv6_address));
}
/** Writes a bcmos_ipv6_address to a buffer
*
* \param buf Buffer to write to
* \param val bcmos_ipv6_address to write
*
* \return BCMOS_TRUE if write successful
*/
static inline bcmos_bool bcmolt_buf_write_ipv6_address(bcmolt_buf *buf, bcmos_ipv6_address val)
{
return bcmolt_buf_write(buf, val.u8, sizeof(bcmos_ipv6_address));
}
#endif /* BCMOLT_BUF_H_ */
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#include <bcm_tr451_polt.h>
#include <bcmcli.h>
#include <bcmolt_daemon.h>
#ifndef BCM_OPEN_SOURCE_SIM
#include <bcmolt_host_api.h>
#include <bcmtr_interface.h>
#endif
#ifndef BCM_OPEN_SOURCE
#include <bcmolt_olt_selector.h>
#include <bcmtr_transport_cli.h>
#include <bcmtr_debug_cli.h>
#include <bcmos_cli.h>
#endif
#ifdef ENABLE_LOG
#include <bcm_dev_log_cli.h>
#endif
#define BCM_POLT_LOG_SIZE (10*1000*1000)
static bcmcli_session *current_session;
static bcmos_bool do_not_daemonize;
static int polt_argc;
static char **polt_argv;
static void polt_restart(void);
static int print_help(char *cmd)
{
fprintf(stderr, "Usage:\n"
"%s"
#ifndef BCM_OPEN_SOURCE_SIM
" -device_address IP:port"
#endif
#if defined(DEV_LOG_SYSLOG)
" -syslog"
#endif
" -d"
" -log info|debug"
" -f init_script"
"\n", cmd);
#ifndef BCM_OPEN_SOURCE_SIM
fprintf(stderr, "\t-device_address IP:port\tOLT Device address (for UDP communication)\n");
#endif
#if defined(DEV_LOG_SYSLOG)
fprintf(stderr, "\t-syslog\t\t\tLog to syslog. This is the default if -d is not specified\n");
#endif
fprintf(stderr, "\t-d\t\t\tStay in foreground (debug mode)\n");
fprintf(stderr, "\t-log\t\t\tSet log level. Default is 'info'\n");
fprintf(stderr, "\t-f\t\t\trun CLI script\n");
return -1;
}
#ifndef BCM_OPEN_SOURCE_SIM
/* parse ip:port */
static bcmos_errno _parse_ip_port(const char *s, uint32_t *ip, uint16_t *port)
{
int n;
uint32_t ip1, ip2, ip3, ip4, pp;
n = sscanf(s, "%u.%u.%u.%u:%u", &ip1, &ip2, &ip3, &ip4, &pp);
if (n != 5 || ip1 > 0xff || ip2 > 0xff || ip3 > 0xff || ip4 > 0xff || pp > 0xffff)
{
fprintf(stderr, "Can't parse %s. Must be ip_address:port\n", s);
return BCM_ERR_PARM;
}
*ip = (ip1 << 24) | (ip2 << 16) | (ip3 << 8) | ip4;
*port = pp;
return BCM_ERR_OK;
}
#endif
/* Shut down dolt server */
static void bcm_polt_shutdown(void)
{
#ifndef BCM_OPEN_SOURCE_SIM
bcmtr_exit();
#endif
bcmcli_session_close(current_session);
bcmcli_token_destroy(NULL);
}
/* quit command handler */
static int _cmd_quit(bcmcli_session *sess, const bcmcli_cmd_parm parm[], uint16_t nParms)
{
#define POLT_TERMINATED_MSG "pOLT terminated by 'Quit' command\n"
bcmcli_stop(sess);
BCM_LOG(INFO, def_log_id, POLT_TERMINATED_MSG);
bcmos_usleep(100000);
return 0;
}
/* Run CLI script */
static bcmos_errno _run_cli_script(bcmcli_session *session, const char *fname, bcmos_bool stop_on_error)
{
bcmos_file *script_file;
char line_buf[4096];
int line = 0;
bcmos_errno err = BCM_ERR_OK;
script_file = bcmos_file_open(fname, BCMOS_FILE_FLAG_READ);
if (script_file == NULL)
{
bcmcli_print(session, "Can't open file %s for reading\n", fname);
return BCM_ERR_NOENT;
}
while (bcmos_file_gets(script_file, line_buf, sizeof(line_buf)) != NULL)
{
++line;
/* Echo */
bcmcli_print(session, "%d: %s\n", line, line_buf);
if (line_buf[0] == '#')
continue;
/* Execute */
err = bcmcli_parse(session, line_buf);
if (err != BCM_ERR_OK && stop_on_error)
break;
}
bcmos_file_close(script_file);
return err;
}
/* Run script command handler
BCMCLI_MAKE_PARM("name", "Script file name", BCMCLI_PARM_STRING, 0),
BCMCLI_MAKE_PARM_ENUM_DEFVAL("stop_on_error", "Stop on error", bcmcli_enum_bool_table, 0, "no"));
*/
static int _cmd_run_script(bcmcli_session *sess, const bcmcli_cmd_parm parm[], uint16_t nParms)
{
const char *filename = (const char *)parm[0].value.string;
bcmos_bool stop_on_error = (bcmos_bool)parm[1].value.number;
return _run_cli_script(sess, filename, stop_on_error);
}
static int bcm_polt_start(void)
{
#ifndef BCM_OPEN_SOURCE_SIM
bcmolt_host_init_parms init_parms = {
.transport.type = BCM_HOST_API_CONN_LOCAL
};
dev_log_init_parms *p_log_parms = &init_parms.log;
#else
dev_log_init_parms log_parms = {};
dev_log_init_parms *p_log_parms = &log_parms;
#endif
bcmos_bool log_syslog = BCMOS_FALSE;
tr451_polt_init_parms polt_init_parms = {
.log_level = DEV_LOG_LEVEL_INFO
};
bcmolt_daemon_parms daemon_parms = {
.name = "tr451_polt"
};
const char *init_script_name = NULL;
bcmos_errno rc;
int i;
for (i = 1; i < polt_argc; i++)
{
if (!strcmp(polt_argv[i], "-d"))
{
do_not_daemonize = BCMOS_TRUE;
}
#ifndef BCM_OPEN_SOURCE_SIM
else if (!strcmp(polt_argv[i], "-device_address"))
{
uint32_t remote_ip = 0;
uint16_t remote_port = 0;
++i;
if (_parse_ip_port(polt_argv[i], &remote_ip, &remote_port) != BCM_ERR_OK)
return -1;
init_parms.transport.type = BCM_HOST_API_CONN_REMOTE;
init_parms.transport.addr.ip.u32 = remote_ip;
init_parms.transport.addr.port = remote_port;
}
#endif
#ifdef DEV_LOG_SYSLOG
else if (!strcmp(polt_argv[i], "-syslog"))
{
log_syslog = BCMOS_TRUE;
}
#endif
else if (!strcmp(polt_argv[i], "-log"))
{
++i;
if (i >= polt_argc)
return print_help(polt_argv[0]);
if (!strcmp(polt_argv[i], "debug"))
polt_init_parms.log_level = DEV_LOG_LEVEL_DEBUG;
else if (strcmp(polt_argv[i], "info"))
return print_help(polt_argv[0]);
}
else if (!strcmp(polt_argv[i], "-f"))
{
++i;
if (i >= polt_argc)
return print_help(polt_argv[0]);
init_script_name = polt_argv[i];
}
else
{
return print_help(polt_argv[0]);
}
}
/* Daemonize if necessary */
if (!do_not_daemonize)
{
daemon_parms.is_cli_support = BCMOS_TRUE;
daemon_parms.terminate_cb = bcm_polt_shutdown;
daemon_parms.restart_cb = polt_restart;
rc = bcmolt_daemon_start(&daemon_parms);
BUG_ON(rc);
log_syslog = BCMOS_TRUE;
}
if (!log_syslog)
{
p_log_parms->type = BCM_DEV_LOG_FILE_MEMORY;
p_log_parms->mem_size = BCM_POLT_LOG_SIZE;
}
else
{
p_log_parms->type = BCM_DEV_LOG_FILE_SYSLOG;
}
#ifndef BCM_OPEN_SOURCE_SIM
/* Initialize host application */
rc = bcmolt_host_init(&init_parms);
BUG_ON(rc != BCM_ERR_OK);
#else
bcmos_trace_level_set(BCMOS_TRACE_LEVEL_INFO);
#ifdef ENABLE_LOG
/* Initialize logger */
rc = bcm_log_init(p_log_parms);
BCMOS_TRACE_CHECK_RETURN(rc, rc, "bcmolt_log_init()\n");
#endif
#endif /* #ifndef BCM_OPEN_SOURCE_SIM */
/* Initialize CLI */
bcmcli_session_parm mon_session_parm = {};
/* Create CLI session */
memset(&mon_session_parm, 0, sizeof(mon_session_parm));
mon_session_parm.access_right = BCMCLI_ACCESS_ADMIN;
rc = bcmcli_session_open(&mon_session_parm, ¤t_session);
BUG_ON(rc != BCM_ERR_OK);
#ifndef BCM_OPEN_SOURCE
/* OLT selector */
bcmolt_olt_sel_init(NULL);
/* Transport CLI */
bcmtr_cli_init();
/* CLD directory */
bcmtr_cld_cli_init();
/* os CLI directory */
bcmos_cli_init(NULL);
#endif
#ifdef ENABLE_LOG
/* logger CLI directory */
bcm_dev_log_cli_init(NULL);
#endif
/* Add Execute Script command */
BCMCLI_MAKE_CMD(NULL, "run", "Run CLI script", _cmd_run_script,
BCMCLI_MAKE_PARM("name", "Script file name", BCMCLI_PARM_STRING, 0),
BCMCLI_MAKE_PARM_ENUM_DEFVAL("stop_on_error", "Stop on error", bcmcli_enum_bool_table, 0, "no"));
/* Add quit command */
BCMCLI_MAKE_CMD_NOPARM(NULL, "quit", "Quit", _cmd_quit);
if (!do_not_daemonize)
bcmolt_daemon_init_completed();
/* Init tr451 polt library */
rc = bcm_tr451_polt_init(&polt_init_parms);
BUG_ON(rc != BCM_ERR_OK);
/* Run init script if any */
if (init_script_name)
{
rc = _run_cli_script(current_session, init_script_name, BCMOS_FALSE);
if (rc != BCM_ERR_OK)
return rc;
}
/* CLI loop. In case of daemonized management daemon it is expected that stdin, stdout are redirected */
while (!bcmcli_is_stopped(current_session))
{
/* Process user input until EOF or quit command */
bcmcli_driver(current_session);
if (feof(stdin) && !do_not_daemonize)
{
bcmos_usleep(100000);
clearerr(stdin);
}
}
bcm_polt_shutdown();
if (!do_not_daemonize)
bcmolt_daemon_terminate(0);
return 0;
}
static void polt_restart(void)
{
bcm_polt_shutdown();
bcm_polt_start();
}
int main(int argc, char *argv[])
{
polt_argc = argc;
polt_argv = argv;
return bcm_polt_start();
}
<file_sep># openssl
#
include(third_party)
bcm_3rdparty_module_name(openssl "1.1.1")
bcm_3rdparty_download_wget("https://www.openssl.org/source/old/1.1.1" "openssl-${OPENSSL_VERSION}.tar.gz")
bcm_3rdparty_add_dependencies(zlib)
# openssl uses custom-made configurator. Invoke it directly
set(_CFLAGS_OPTS -I"${BUILD_TOP}"/fs/include ${BCM_ARCHITECTURE_FLAGS} ${_${_MOD_NAME_UPPER}_CFLAGS})
set(_LDFLAGS_OPTS -L"${BUILD_TOP}"/fs/lib ${LINK_FLAGS} ${_${_MOD_NAME_UPPER}_LDFLAGS})
set(_TARGETS ${ARGN})
if(NOT _TARGETS)
set(_TARGETS install_sw install_ssldirs)
endif()
if(NOT DEFINED BCM_CONFIG_HOST)
message(FATAL_ERROR "Need to add support for board ${BOARD}")
endif()
set(_CONFIG_OPTS no-hw no-sse2 no-asm zlib)
if(BCM_CONFIG_HOST MATCHES ".*aarch64.*")
set(_CONFIG_HOST linux-aarch64)
elseif(BCM_CONFIG_HOST MATCHES ".*x86_64.*")
set(_CONFIG_HOST linux-x86_64)
endif()
add_custom_command(OUTPUT ${_${_MOD_NAME_UPPER}_INSTALLED_FILE}
COMMAND echo "Building ${_MOD_NAME}-${${_MOD_NAME_UPPER}_VERSION}.."
COMMAND CC=${CMAKE_C_COMPILER}
./Configure ${_CONFIG_OPTS} --prefix=${_${_MOD_NAME_UPPER}_INSTALL_TOP}
${_CONFIG_HOST} ${_CFLAGS_OPTS} ${_LDFLAGS_OPTS}
# opennsl doesn't seem to support parallel build for install. Build the SW as parallel
# then build the install targets serial.
COMMAND ${BCM_MAKE_PROGRAM} ${_BCM_COMMON_MAKE_FLAGS} &&
${BCM_MAKE_PROGRAM} -j1 ${_BCM_COMMON_MAKE_FLAGS} ${_TARGETS}
COMMAND rm -f ${CMAKE_CURRENT_BINARY_DIR}/.${_MOD_NAME}_*_installed
COMMAND touch ${_${_MOD_NAME_UPPER}_INSTALLED_FILE}
DEPENDS ${_${_MOD_NAME_UPPER}_DEPS} ${_${_MOD_NAME_UPPER}_LOADED_FILE}
WORKING_DIRECTORY ${_${_MOD_NAME_UPPER}_SRC_DIR})
unset(_CFLAGS_OPTS)
unset(_LDFLAGS_OPTS)
unset(_CONFIG_OPTS)
unset(_CONFIG_TARGET)
unset(_TARGETS)
unset(_CONFIG_HOST)
bcm_3rdparty_export(ssl)
<file_sep>/*
<:copyright-BRCM:2016-2019:Apache:standard
Copyright (c) 2016-2019 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
* :>
*/
#ifndef BCMOS_PLATFORM_H_
#define BCMOS_PLATFORM_H_
#ifndef BCMOS_SYSTEM_H_
#error Please do not include bcmos_platform.h directly. Include bcmos_system.h
#endif
typedef enum
{
BCM_MAC_DEVICE_TYPE_UNKNOWN,
BCM_MAC_DEVICE_TYPE_BCM6862X, /* Maple family */
BCM_MAC_DEVICE_TYPE_BCM6865X, /* Aspen family */
} bcm_mac_device_type;
/** BCM68620 CPU core
* \ingroup system_task */
typedef enum
{
BCMOS_CPU_CORE_ANY, /**< Any core */
BCMOS_CPU_CORE__NUM_OF = 1, /**< Number of cores */
} bcmos_core;
#define MAX_NUMBER_OF_PONS_ON_ALL_DEVICES (BCMTR_MAX_DEVICES * BCMTR_MAX_INSTANCES)
/** BCM68620 module
* \ingroup system_module
*/
typedef enum
{
BCMOS_MODULE_ID_NONE, /**< no module */
#ifdef BCMOS_SYS_UNITTEST
BCMOS_MODULE_ID_TEST1,
BCMOS_MODULE_ID_TEST2,
#endif
BCMOS_MODULE_ID_TRANSPORT_IND,
/* Each Device (BCM6862X) must have its own dedicated Device Control Module at the host */
BCMOS_MODULE_ID_DEV_AGENT_DEV0,
/* CLI over PCIe client */
BCMOS_MODULE_ID_CLI_OVER_PCIE = BCMOS_MODULE_ID_DEV_AGENT_DEV0 + BCMTR_MAX_DEVICES,
/* Protection switching user application */
BCMOS_MODULE_ID_USER_APPL_PS,
/* Remote CLI */
BCMOS_MODULE_ID_REMOTE_CLI_DEV0 = BCMOS_MODULE_ID_USER_APPL_PS + BCMTR_MAX_DEVICES,
/* Remote logger application (To support multiple devices we need to add number of devices to previous value) */
BCMOS_MODULE_ID_USER_APPL_REMOTE_LOGGER_DEV0 = BCMOS_MODULE_ID_REMOTE_CLI_DEV0 + BCMTR_MAX_DEVICES,
/* OMCI SW download user application (To support multiple devices we need to add number of devices to previous value) */
BCMOS_MODULE_ID_USER_APPL_OMCI_SWDL_DEV0 = BCMOS_MODULE_ID_USER_APPL_REMOTE_LOGGER_DEV0 + BCMTR_MAX_DEVICES,
/* ITU mac learning / aging user application (To support multiple devices we need to add number of devices to previous value) */
BCMOS_MODULE_ID_USER_APPL_ITU_MAC_LEARNING_DEV0 = BCMOS_MODULE_ID_USER_APPL_OMCI_SWDL_DEV0 + BCMTR_MAX_DEVICES,
/* ITU multi-PON DBA stress user application (To support multiple devices we need to add number of devices multiplied by max PON number to previous value) */
BCMOS_MODULE_ID_USER_APPL_ITU_STRESS_DEV0 = BCMOS_MODULE_ID_USER_APPL_ITU_MAC_LEARNING_DEV0 + MAX_NUMBER_OF_PONS_ON_ALL_DEVICES,
/* ITU DS OMCI packets user application (To support multiple devices we need to add number of devices multiplied by max PON number to previous value) */
BCMOS_MODULE_ID_USER_APPL_ITU_DS_OMCI_DEV0 = BCMOS_MODULE_ID_USER_APPL_ITU_STRESS_DEV0 + MAX_NUMBER_OF_PONS_ON_ALL_DEVICES,
/* ITU SN acquisition (To support multiple devices we need to add number of devices multiplied by max PON number to previous value) */
BCMOS_MODULE_ID_USER_APPL_ITU_SN_DISCOVERY_DEV0 = BCMOS_MODULE_ID_USER_APPL_ITU_DS_OMCI_DEV0 + MAX_NUMBER_OF_PONS_ON_ALL_DEVICES,
/* ITU cooperative DBA example application (To support multiple devices we need to add number of devices multiplied by max PON number to previous value) */
BCMOS_MODULE_ID_USER_APPL_ITU_COOP_DBA_EXAMPLE = BCMOS_MODULE_ID_USER_APPL_ITU_SN_DISCOVERY_DEV0 + MAX_NUMBER_OF_PONS_ON_ALL_DEVICES,
/* ITU statistics */
BCMOS_MODULE_ID_USER_APPL_ITU_STATISTICS_DEV0 = BCMOS_MODULE_ID_USER_APPL_ITU_COOP_DBA_EXAMPLE + MAX_NUMBER_OF_PONS_ON_ALL_DEVICES,
/* ITU RSSI user application (To support multiple devices we need to add number of devices multiplied by max PON number to previous value) */
BCMOS_MODULE_ID_USER_APPL_ITU_RSSI_DEV0 = BCMOS_MODULE_ID_USER_APPL_ITU_STATISTICS_DEV0 + MAX_NUMBER_OF_PONS_ON_ALL_DEVICES,
/* ITU NG-PON2 Wavelength Handover user application */
BCMOS_MODULE_ID_USER_APPL_ITU_ONU_TUNING_OLT0 = BCMOS_MODULE_ID_USER_APPL_ITU_RSSI_DEV0 + BCMTR_MAX_DEVICES,
/* EPON OAM negotiation application (To support multiple devices we need to add number of devices to previous value) */
BCMOS_MODULE_ID_USER_APPL_EON = BCMOS_MODULE_ID_USER_APPL_ITU_ONU_TUNING_OLT0 + BCMTR_MAX_OLTS,
/* EPON optical monitoring application */
BCMOS_MODULE_ID_USER_APPL_OMON = BCMOS_MODULE_ID_USER_APPL_EON + BCMTR_MAX_DEVICES,
/* EPON Host driven encryption application */
BCMOS_MODULE_ID_USER_APPL_EPON_HDE,
BCMOS_MODULE_ID_USER_APPL_EPON_OAM,
BCMOS_MODULE_ID_USER_APPL_DPOE_SEC,
BCMOS_MODULE_ID_USER_APPL_IMAGE_TRANSFER0 = BCMOS_MODULE_ID_USER_APPL_DPOE_SEC + BCMTR_MAX_DEVICES,
BCMOS_MODULE_ID_USER_APPL_ONU_TUNING_DEV0 = BCMOS_MODULE_ID_USER_APPL_IMAGE_TRANSFER0 + BCMTR_MAX_DEVICES,
BCMOS_MODULE_ID_USER_APPL_TOD_DEV0 = BCMOS_MODULE_ID_USER_APPL_ONU_TUNING_DEV0 + BCMTR_MAX_DEVICES,
/* OLT Agent */
BCMOS_MODULE_ID_OLT_AGENT = BCMOS_MODULE_ID_USER_APPL_TOD_DEV0 + BCMTR_MAX_DEVICES,
/* BALIMPORT BEGIN */
BCMOS_MODULE_ID_WORKER_MGMT, /**< Number of modules *//** worker module for MGMT message handling */
BCMOS_MODULE_ID_WORKER_API_IND, /** worker module for BAL API INDICATION message handling */
BCMOS_MODULE_ID_WORKER_BAL_CORE_FOR_AGENT, /** worker module for the BAL CORE when running as an OF agent */
/* BALIMPORT TODO: duplicates */
// BCMOS_MODULE_ID_USER_APPL_EON, /** EON module */
// BCMOS_MODULE_ID_USER_APPL_EPON_OAM, /** EPON OAM module */
BCMOS_MODULE_ID_OFPAL, /** OF-PAL module */
BCMOS_MODULE_ID_OMCI_TRANSPORT, /** OMCI Transport module */
BCMOS_MODULE_ID_OMCI_RX_WORKER0, /** OMCI RX worker module */
#define BCM_OMCI_MAX_RX_WORKER_THREADS 32
BCMOS_MODULE_ID_DPOE2_TRANSPORT = BCMOS_MODULE_ID_OMCI_RX_WORKER0 + BCM_OMCI_MAX_RX_WORKER_THREADS, /** DPoE2 Transport module */
BCMOS_MODULE_ID_API_PROXY, /** API proxy module */
BCMOS_MODULE_ID_VOMCI_SERVER, /** ONU management: VOMCI server module */
BCMOS_MODULE_ID_NETCONF_SERVER, /** WT-385, WT-383 NETCONF server */
/* BALIMPORT END */
BCMOS_MODULE_IS_USER_DDR_DUMP, /* MAC DDR dump utility */
BCMOS_MODULE_ID_ISSU, /** Host ISSU */
BCMOS_MODULE_ID_HOST_REMOTE_LOGGER, /** Host remote logger */
BCMOS_MODULE_ID__NUM_OF, /**< Number of modules */
BCMOS_MODULE_ID_INVALID = BCMOS_MODULE_ID_NONE
} bcmos_module_id;
/** BCM68620 event group. Each group supports up to 32 events.
* \ingroup system_event
*/
typedef enum
{
#ifdef BCMOS_SYS_UNITTEST
BCMOS_EVENT_ID_TEST1,
BCMOS_EVENT_ID_TEST2,
#else
BCMOS_EVENT_ID_DUMMY, /* Currently OS s/w doesn't use events.
Remove this constant when adding real events */
#endif
BCMOS_EVENT_ID__NUM_OF, /**< Number of event groups */
} bcmos_event_id;
/** Message hash size
* \ingroup system_msg
*/
#define BCMOS_MSG_HASH_SIZE 512
/** Maple OS message
* \ingroup system_msg
*/
typedef enum
{
BCMOS_MSG_ID__BEGIN,
/* Internal messages */
BCMOS_MSG_ID_INTERNAL_TIMER = BCMOS_MSG_ID__BEGIN, /**< Internal "timer message" type */
BCMOS_MSG_ID_INTERNAL_EVENT, /**< Internal "event message" type */
BCMOS_MSG_ID_INTERNAL_IPC,
BCMOS_MSG_ID_INITIATE_RX_POWER,
BCMOS_MSG_ID_INITIATE_TRX_STATUS,
BCMOS_MSG_ID_INITIATE_ROGUE_SCAN,
BCMOS_MSG_ID_INITIATE_RSSI_READ,
BCMOS_MSG_ID_ITU_STRESS_START,
BCMOS_MSG_ID_ITU_STRESS_TIMEOUT,
BCMOS_MSG_ID_ITU_STRESS_ONU_TIMEOUT,
BCMOS_MSG_ID_ITU_STRESS_PON_DEACTIVATION_COMPLETED,
BCMOS_MSG_ID_ITU_STRESS_PON_ACTIVATION_COMPLETED,
BCMOS_MSG_ID_ITU_STRESS_PON_ACTIVATE_ALL_ONUS_COMPLETED,
BCMOS_MSG_ID_ITU_STRESS_PON_DEACTIVATE_ALL_ONUS_COMPLETED,
BCMOS_MSG_ID_ITU_STRESS_SN_ACQUISITION_CYCLE_START,
BCMOS_MSG_ID_ITU_STRESS_ONU_DISCOVERED,
BCMOS_MSG_ID_ITU_STRESS_ONU_DEACTIVATION_COMPLETED,
BCMOS_MSG_ID_ITU_STRESS_ONU_ACTIVATION_COMPLETED,
BCMOS_MSG_ID_ITU_DS_OMCI_START,
BCMOS_MSG_ID_ITU_DS_OMCI_TIMEOUT,
BCMOS_MSG_ID_ITU_DS_OMCI_STOP,
BCMOS_MSG_ID_ITU_DS_OMCI_DEVICE_CONNECTED,
BCMOS_MSG_ID_ITU_DS_OMCI_DEVICE_DISCONNECTED,
BCMOS_MSG_ID_ITU_RSSI_START,
BCMOS_MSG_ID_ITU_STATISTICS_START,
BCMOS_MSG_ID_ITU_STATISTICS_TIMEOUT,
BCMOS_MSG_ID_ITU_STATISTICS_STOP,
BCMOS_MSG_ID_EON_START,
BCMOS_MSG_ID_EON_STOP,
BCMOS_MSG_ID_EON_PROXY_RX,
BCMOS_MSG_ID_EPON_OAM_PROXY_RX,
BCMOS_MSG_ID_EPON_OAM_TIMEOUT,
BCMOS_MSG_ID_DPOE_SEC_START,
BCMOS_MSG_ID_DPOE_SEC_RX_OAM,
BCMOS_MSG_ID_DPOE_SEC_RX_EAPOL,
BCMOS_MSG_ID_ONU_TUNING_START,
BCMOS_MSG_ID_ONU_TUNING_STOP,
BCMOS_MSG_ID_OLT_AGENT_BAL_STATE_CHANGED, /* BAL reports state change to OLT Agent */
BCMOS_MSG_ID_SW_UTIL_NNI_STATE_CHANGED,
BCMOS_MSG_ID_SW_UTIL_LAG_NNI_STATE_CHANGED,
/******************************************************************************/
/* BALIMPORT BEGIN */
/* Application messages */
BCMOS_MSG_ID_IPC_PING, /*** Inter-process communication ping */
/* Core/Switch util messages */
BCMBAL_SWITCH_UTIL_MSG,
/* Core/Mac util messages */
BCMBAL_MAC_UTIL_MSG,
/* Core->Public API indication messages (both auto and "normal") */
BCMBAL_MGMT_API_IND_MSG,
BCMOS_MSG_ID_OMCI_TRANSPORT_SEND,
BCMOS_MSG_ID_DPOE2_TRANSPORT_SEND,
/* BALIMPORT END */
/******************************************************************************/
/* Device Agent Internal Messages BEGIN */
BCMOS_MSG_ID_DA_INT_TIMEOUT,
BCMOS_MSG_ID_DA_INT_KA_FAIL,
BCMOS_MSG_ID_DA_INT_CONNECT_REQ,
BCMOS_MSG_ID_DA_INT_DISCONNECT_REQ,
BCMOS_MSG_ID_DA_INT_RESET_REQ,
BCMOS_MSG_ID_DA_INT_DDR_TEST_TIMEOUT,
BCMOS_MSG_ID_DA_INT_DDR_TEST_COMPLETE,
BCMOS_MSG_ID_DA_INT_INBAND_CONN_ESTD,
BCMOS_MSG_ID_DA_IND_DISCONNECT,
BCMOS_MSG_ID_DA_IND_CONN_FAIL,
BCMOS_MSG_ID_DA_IND_DDR_TEST_COMPLETED,
BCMOS_MSG_ID_DA_IND_DDR_TEST_FAILED,
BCMOS_MSG_ID_DA_IND_DDR_TEST_TIMEDOUT,
/* Device Agent Internal Messages END */
/* TOD APPL Messages */
BCMOS_MSG_ID_TOD_APPL_START,
/* PS APPL Messages */
BCMOS_MSG_ID_PS_APPL_START,
BCMOS_MSG_ID__NONE,
BCMOS_MSG_ID__END,
BCMOS_MSG_ID__FORCE16 = 0x7fff
} bcmos_msg_id;
#define BCMOS_MSG_ID__NUM_OF (BCMOS_MSG_ID__END - BCMOS_MSG_ID__BEGIN)
/*
* Task priorities
*/
#define TASK_PRIORITY_COOP_DBA BCMOS_TASK_PRIORITY_1
#define TASK_PRIORITY_TRMUX_RX BCMOS_TASK_PRIORITY_2
#define TASK_PRIORITY_TRANSPORT_RX BCMOS_TASK_PRIORITY_7
#define TASK_PRIORITY_TRANSPORT_TIMEOUT BCMOS_TASK_PRIORITY_8
#define TASK_PRIORITY_TRANSPORT_PROXY BCMOS_TASK_PRIORITY_9
#define TASK_PRIORITY_TRANSPORT_REMOTE_CLI BCMOS_TASK_PRIORITY_9
#define TASK_PRIORITY_DEVICE_CONTROL BCMOS_TASK_PRIORITY_10
#define TASK_PRIORITY_TRANSPORT_IND BCMOS_TASK_PRIORITY_11
#define TASK_PRIORITY_USER_APPL_PS BCMOS_TASK_PRIORITY_12
#define TASK_PRIORITY_USER_APPL_EON BCMOS_TASK_PRIORITY_12
#define TASK_PRIORITY_USER_APPL_OMON BCMOS_TASK_PRIORITY_12
#define TASK_PRIORITY_USER_APPL_OAM BCMOS_TASK_PRIORITY_12
#define TASK_PRIORITY_USER_APPL_EPON_HDE BCMOS_TASK_PRIORITY_12
#define TASK_PRIORITY_USER_APPL_DPOE_SEC BCMOS_TASK_PRIORITY_12
#define TASK_PRIORITY_USER_APPL_ITU_MAC_LEARNING BCMOS_TASK_PRIORITY_12
#define TASK_PRIORITY_USER_APPL_ITU_STRESS BCMOS_TASK_PRIORITY_12
#define TASK_PRIORITY_USER_APPL_ITU_STRESS BCMOS_TASK_PRIORITY_12
#define TASK_PRIORITY_USER_APPL_ITU_SN_DISCOVERY BCMOS_TASK_PRIORITY_12
#define TASK_PRIORITY_USER_APPL_ITU_DS_OMCI BCMOS_TASK_PRIORITY_12
#define TASK_PRIORITY_USER_APPL_ITU_STATISTICS BCMOS_TASK_PRIORITY_12
#define TASK_PRIORITY_USER_APPL_ITU_ONU_TUNING BCMOS_TASK_PRIORITY_12
#define TASK_PRIORITY_USER_APPL_ITU_RSSI BCMOS_TASK_PRIORITY_12
#define TASK_PRIORITY_USER_APPL_ITU_COOP_DBA_EXAMPLE BCMOS_TASK_PRIORITY_12
#define TASK_PRIORITY_USER_APPL_TOD BCMOS_TASK_PRIORITY_12
#define TASK_PRIORITY_CLI BCMOS_TASK_PRIORITY_15
#define TASK_PRIORITY_USER_APPL_OMCI_SWDL BCMOS_TASK_PRIORITY_17
#define TASK_PRIORITY_USER_APPL_IMAGE_TRANSFER BCMOS_TASK_PRIORITY_17
#define TASK_PRIORITY_USER_APPL_STRESS_TEST BCMOS_TASK_PRIORITY_17
#define TASK_PRIORITY_DEV_LOG_KERNEL BCMOS_TASK_PRIORITY_20
#define TASK_PRIORITY_DEV_LOG BCMOS_TASK_PRIORITY_30
#define TASK_PRIORITY_USER_APPL_REMOTE_LOGGER BCMOS_TASK_PRIORITY_30
#define TASK_PRIORITY_REMOTE_LOG BCMOS_TASK_PRIORITY_30
/* BALIMPORT BEGIN */
#define TASK_PRIORITY_KEEP_ALIVE BCMOS_TASK_PRIORITY_2
#define TASK_PRIORITY_IPC_RX BCMOS_TASK_PRIORITY_3
#define TASK_PRIORITY_API_PROXY_RX BCMOS_TASK_PRIORITY_4
#define TASK_PRIORITY_API_PROXY_INVOKE BCMOS_TASK_PRIORITY_5
#define TASK_PRIORITY_CORE_CONN_MGR BCMOS_TASK_PRIORITY_6
#define TASK_PRIORITY_CLI BCMOS_TASK_PRIORITY_15
#define TASK_PRIORITY_OLT_AGENT BCMOS_TASK_PRIORITY_16
#define TASK_PRIORITY_WORKER BCMOS_TASK_PRIORITY_16
#define TASK_PRIORITY_OFPAL BCMOS_TASK_PRIORITY_18
#define TASK_PRIORITY_VOMCI_SERVER BCMOS_TASK_PRIORITY_18
#define TASK_PRIORITY_VOMCI_DOLT_CLIENT BCMOS_TASK_PRIORITY_19
#define TASK_PRIORITY_OMCI_TRANSPORT BCMOS_TASK_PRIORITY_20
#define TASK_PRIORITY_OMCI_RX_WORKER BCMOS_TASK_PRIORITY_20
#define TASK_PRIORITY_DPOE2_TRANSPORT BCMOS_TASK_PRIORITY_20
#define TASK_PRIORITY_ISSU BCMOS_TASK_PRIORITY_29
#define TASK_PRIORITY_DEV_LOG BCMOS_TASK_PRIORITY_30
/* BALIMPORT END */
#endif /* BCMOS_PLATFORM_H_ */
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#ifdef ENABLE_LOG
#include "bcm_dev_log_task.h"
#include "bcm_dev_log_task_internal.h"
#include "bcm_dev_log.h"
#if defined(LINUX_KERNEL_SPACE) && !defined(__KERNEL__)
#include "bcmos_mgmt_type.h"
#include "bcmolt_dev_log_linux.h"
#include "bcmolt_dev_log_linux_ud.h"
#endif
#ifdef DEV_LOG_SYSLOG
#include <syslog.h>
#endif
#define USE_ANSI_ESCAPE_CODES
#ifdef USE_ANSI_ESCAPE_CODES
#define DEV_LOG_STYLE_NORMAL "\033[0m\033#5"
#define DEV_LOG_STYLE_BOLD "\033[1m"
#define DEV_LOG_STYLE_UNDERLINE "\033[4m"
#define DEV_LOG_STYLE_BLINK "\033[5m"
#define DEV_LOG_STYLE_REVERSE_VIDEO "\033[7m"
#else
#define DEV_LOG_STYLE_NORMAL " "
#define DEV_LOG_STYLE_BOLD "*** "
#define DEV_LOG_STYLE_UNDERLINE "___ "
#define DEV_LOG_STYLE_BLINK "o_o "
#define DEV_LOG_STYLE_REVERSE_VIDEO "!!! "
#endif
#define DEV_LOG_MSG_START_CHAR 0x1e /* record separator character */
#define MEM_FILE_HDR_SIZE sizeof(dev_log_mem_file_header)
#define LOG_MIN(a,b) (((int)(a) <= (int)(b)) ? (a) : (b))
dev_log_id def_log_id;
static int default_write_callback_unprotected(bcm_dev_log_file *file, const void *buf, uint32_t length);
static bcm_dev_log_style dev_log_level2style[DEV_LOG_LEVEL_NUM_OF] =
{
[DEV_LOG_LEVEL_FATAL] = BCM_DEV_LOG_STYLE_NORMAL,
[DEV_LOG_LEVEL_ERROR] = BCM_DEV_LOG_STYLE_NORMAL,
[DEV_LOG_LEVEL_WARNING] = BCM_DEV_LOG_STYLE_NORMAL,
[DEV_LOG_LEVEL_INFO] = BCM_DEV_LOG_STYLE_NORMAL,
[DEV_LOG_LEVEL_DEBUG] = BCM_DEV_LOG_STYLE_NORMAL,
};
static const char *dev_log_style_array[] =
{
[BCM_DEV_LOG_STYLE_NORMAL] = DEV_LOG_STYLE_NORMAL,
[BCM_DEV_LOG_STYLE_BOLD] = DEV_LOG_STYLE_BOLD,
[BCM_DEV_LOG_STYLE_UNDERLINE] = DEV_LOG_STYLE_UNDERLINE,
[BCM_DEV_LOG_STYLE_BLINK] = DEV_LOG_STYLE_BLINK,
[BCM_DEV_LOG_STYLE_REVERSE_VIDEO] = DEV_LOG_STYLE_REVERSE_VIDEO,
};
bcm_dev_log dev_log = {{0}};
const char *log_level_str = "?FEWID";
static void bcm_dev_log_shutdown_msg_release(bcmos_msg *m)
{
(void)m; /* do nothing, the message is statically allocated */
}
static bcmos_msg shutdown_msg = { .release = bcm_dev_log_shutdown_msg_release };
static void bcm_dev_log_file_save_msg(bcm_dev_log_file *files, const char *message)
{
uint32_t i;
uint32_t len = strlen(message) + 1; /* including 0 terminator */
for (i = 0; (i < DEV_LOG_MAX_FILES) && (files[i].file_parm.flags & BCM_DEV_LOG_FILE_FLAG_VALID); i++)
{
files[i].file_parm.write_cb(&files[i], message, len);
}
}
static void dev_log_save_task_format_message(dev_log_queue_msg *receive_msg, char *log_string, uint32_t log_string_size, ...)
{
uint32_t length;
char time_str[17];
dev_log_id_parm *log_id = receive_msg->log_id;
bcm_dev_log_level msg_level = receive_msg->msg_level;
/* Build message header */
*log_string = '\0';
if (!(receive_msg->flags & BCM_LOG_FLAG_NO_HEADER))
{
length = sizeof(time_str);
dev_log.dev_log_parm.time_to_str_cb(receive_msg->time_stamp, time_str, length);
snprintf(
log_string,
log_string_size,
"[%s: %c %-20s] ",
time_str,
log_level_str[msg_level],
log_id->name);
}
/* Modify the __FILE__ format so it would print the filename only without the path.
* If using BCM_LOG_FLAG_CALLER_FMT, it is done in caller context, because filename might be long, taking a lot of
* the space of the message itself. */
if ((receive_msg->flags & BCM_LOG_FLAG_FILENAME_IN_FMT) && !(receive_msg->flags & BCM_LOG_FLAG_CALLER_FMT))
{
/* coverity[misra_violation] - cross-assignment under union is OK - they're both in the same union member */
receive_msg->u.fmt_args.fmt = dev_log_basename(receive_msg->u.fmt_args.fmt);
}
if (receive_msg->flags & BCM_LOG_FLAG_CALLER_FMT)
{
/* Copy user string to buffer */
strncat(log_string, receive_msg->u.str, log_string_size - strlen(log_string) - 1);
}
else
{
uint32_t offset = ((long)receive_msg->u.fmt_args.args % 8 == 0) ? 0 : 1; /* start on an 8-byte boundary */
#ifndef COMPILATION_32_BIT
/* NOTE: why do we use so terrible input:
* It is impossible to send va_list structure from bcm_dev_log.c. So we send array of arguments only.
* The va_list maintains pointers to temporary memory on the stack.
* After the function with variable args has returned, this automatic storage is gone and the contents are no longer usable.
* Because of this, we cannot simply keep a copy of the va_list itself - the memory it references will contain unpredictable content.
* In addition internal struct va_list is different in 64-bit and 32-bit, in ARM, in posix etc., so we cannot assume what exactly its fields contain */
snprintf(log_string + strlen(log_string),
log_string_size - strlen(log_string),
receive_msg->u.fmt_args.fmt,
receive_msg->u.fmt_args.args[offset],
receive_msg->u.fmt_args.args[offset+1],
receive_msg->u.fmt_args.args[offset+2],
receive_msg->u.fmt_args.args[offset+3],
receive_msg->u.fmt_args.args[offset+4],
receive_msg->u.fmt_args.args[offset+5],
receive_msg->u.fmt_args.args[offset+6],
receive_msg->u.fmt_args.args[offset+7],
receive_msg->u.fmt_args.args[offset+8],
receive_msg->u.fmt_args.args[offset+9],
receive_msg->u.fmt_args.args[offset+10],
receive_msg->u.fmt_args.args[offset+11],
receive_msg->u.fmt_args.args[offset+12],
receive_msg->u.fmt_args.args[offset+13],
receive_msg->u.fmt_args.args[offset+14],
receive_msg->u.fmt_args.args[offset+15],
receive_msg->u.fmt_args.args[offset+16],
receive_msg->u.fmt_args.args[offset+17],
receive_msg->u.fmt_args.args[offset+18],
receive_msg->u.fmt_args.args[offset+19],
receive_msg->u.fmt_args.args[offset+20],
receive_msg->u.fmt_args.args[offset+21],
receive_msg->u.fmt_args.args[offset+22],
receive_msg->u.fmt_args.args[offset+23],
receive_msg->u.fmt_args.args[offset+24],
receive_msg->u.fmt_args.args[offset+25],
receive_msg->u.fmt_args.args[offset+26],
receive_msg->u.fmt_args.args[offset+27],
receive_msg->u.fmt_args.args[offset+28],
receive_msg->u.fmt_args.args[offset+29],
receive_msg->u.fmt_args.args[offset+30],
receive_msg->u.fmt_args.args[offset+31],
receive_msg->u.fmt_args.args[offset+32],
receive_msg->u.fmt_args.args[offset+33],
receive_msg->u.fmt_args.args[offset+34],
receive_msg->u.fmt_args.args[offset+35]);
#else
va_list ap;
*(void **)&ap = &receive_msg->u.fmt_args.args[offset];
/* Copy user string to buffer */
vsnprintf(log_string + strlen(log_string),
log_string_size - strlen(log_string),
receive_msg->u.fmt_args.fmt,
ap);
#endif
}
/* Force last char to be end of string */
log_string[MAX_DEV_LOG_STRING_SIZE - 1] = '\0';
}
static void dev_log_save_task_handle_message(bcmos_msg *msg)
{
static char log_string[MAX_DEV_LOG_STRING_SIZE];
dev_log_queue_msg *receive_msg = msg->data;
dev_log_id_parm *log_id = receive_msg->log_id;
bcm_dev_log_level msg_level = receive_msg->msg_level;
dev_log_save_task_format_message(receive_msg, log_string, sizeof(log_string));
/* At this point, if the message is going to be sent to the print task, save the formatted string then forward it.
* Otherwise, we can release the message before writing it to RAM. */
if ((log_id->log_type & DEV_LOG_ID_TYPE_PRINT) &&
(msg_level <= log_id->log_level_print))
{
if (!bcm_dev_log_level_is_error(msg_level) &&
(receive_msg->flags & BCM_LOG_FLAG_DONT_SKIP_PRINT) != 0 &&
bcm_dev_log_pool_occupancy_percent_get() >= DEV_LOG_SKIP_PRINT_THRESHOLD_PERCENT)
{
log_id->print_skipped_count++;
bcmos_msg_free(msg);
}
else
{
strcpy(receive_msg->u.str, log_string); /* so the print task doesn't need to re-format it */
bcmos_msg_send(&dev_log.print_queue, msg, BCMOS_MSG_SEND_AUTO_FREE);
}
}
else
{
bcmos_msg_free(msg);
}
/* Save to file */
if ((log_id->log_type & DEV_LOG_ID_TYPE_SAVE) &&
(msg_level <= log_id->log_level_save))
{
bcm_dev_log_file_save_msg(dev_log.files, log_string);
}
}
static void dev_log_print_task_handle_message(bcmos_msg *msg)
{
static char log_string[MAX_DEV_LOG_STRING_SIZE];
dev_log_queue_msg *receive_msg = msg->data;
dev_log_id_parm *log_id = receive_msg->log_id;
bcm_dev_log_level msg_level = receive_msg->msg_level;
/* make a local copy of the pre-formatted string (it was formatted in the save task) */
strcpy(log_string, receive_msg->u.str);
/* free the message ASAP since printing might take some time */
bcmos_msg_free(msg);
if (log_id->style == BCM_DEV_LOG_STYLE_NORMAL &&
dev_log_level2style[msg_level] == BCM_DEV_LOG_STYLE_NORMAL)
{
dev_log.dev_log_parm.print_cb(dev_log.dev_log_parm.print_cb_arg, "%s", log_string);
}
else
{
/* If style was set per log id, then use it. */
if (log_id->style != BCM_DEV_LOG_STYLE_NORMAL)
{
dev_log.dev_log_parm.print_cb(
dev_log.dev_log_parm.print_cb_arg,
"%s%s%s",
dev_log_style_array[log_id->style],
log_string,
dev_log_style_array[BCM_DEV_LOG_STYLE_NORMAL]);
}
else
{
/* Otherwise - style was set per log level. */
dev_log.dev_log_parm.print_cb(
dev_log.dev_log_parm.print_cb_arg,
"%s%s%s",
dev_log_style_array[dev_log_level2style[msg_level]],
log_string,
dev_log_style_array[BCM_DEV_LOG_STYLE_NORMAL]);
}
}
}
static int dev_log_print_task(long data)
{
bcmos_msg *m;
bcmos_errno error;
const char error_str[MAX_DEV_LOG_STRING_SIZE] = "Error: Can't receive from queue - dev_log print task exit\n";
while (1)
{
error = bcmos_msg_recv(&dev_log.print_queue, BCMOS_WAIT_FOREVER, &m);
if (error != BCM_ERR_OK)
{
DEV_LOG_ERROR_PRINTF("%s", error_str);
dev_log.dev_log_parm.print_cb(dev_log.dev_log_parm.print_cb_arg, "%s", error_str);
bcm_dev_log_file_save_msg(dev_log.files, error_str);
return (int)error;
}
if (m == &shutdown_msg)
{
break; /* shut down gracefully */
}
else
{
dev_log_print_task_handle_message(m);
}
}
bcmos_sem_post(&dev_log.print_task_is_terminated);
return 0;
}
static int dev_log_save_task(long data)
{
bcmos_msg *m;
bcmos_errno error;
const char error_str[MAX_DEV_LOG_STRING_SIZE] = "Error: Can't receive from queue - dev_log save task exit\n";
while (1)
{
error = bcmos_msg_recv(&dev_log.save_queue, BCMOS_WAIT_FOREVER, &m);
if (error != BCM_ERR_OK)
{
DEV_LOG_ERROR_PRINTF("%s", error_str);
dev_log.dev_log_parm.print_cb(dev_log.dev_log_parm.print_cb_arg, "%s", error_str);
bcm_dev_log_file_save_msg(dev_log.files, error_str);
return (int)error;
}
if (m == &shutdown_msg)
{
break; /* shut down gracefully */
}
else
{
dev_log_save_task_handle_message(m);
}
}
bcmos_sem_post(&dev_log.save_task_is_terminated);
return 0;
}
extern const char * last_format;
void dev_log_oops_complete_cb(void)
{
bcmos_msg *m;
uint32_t i;
if (last_format)
{
printf("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! last format %s \n ",last_format);
}
/* We start traversing print queue. Those are already formatted messages that were forwarded from the save task.
* Then we proceed to traversing save queue. Those are messages that haven't reached the print task yet.
* We read from queue with timeout=0, meaning non-blocking call (we cannot wait in oops time - all OS services are down). */
while (bcmos_msg_recv(&dev_log.print_queue, 0, &m) == BCM_ERR_OK)
dev_log_print_task_handle_message(m);
for (i = 0; (i < DEV_LOG_MAX_FILES) && (dev_log.files[i].file_parm.flags & BCM_DEV_LOG_FILE_FLAG_VALID); i++)
{
if (dev_log.files[i].file_parm.type == BCM_DEV_LOG_FILE_MEMORY)
dev_log.files[i].file_parm.write_cb = default_write_callback_unprotected; /* Avoid bcmos_mutex_lock()/bcmos_mutex_unlock() in regular (protected) version. */
}
while (bcmos_msg_recv(&dev_log.save_queue, 0, &m) == BCM_ERR_OK)
{
static char log_string[MAX_DEV_LOG_STRING_SIZE];
dev_log_queue_msg *receive_msg;
dev_log_id_parm *log_id;
bcm_dev_log_level msg_level;
receive_msg = m->data;
log_id = receive_msg->log_id;
msg_level = receive_msg->msg_level;
dev_log_save_task_format_message(receive_msg, log_string, sizeof(log_string));
if ((log_id->log_type & DEV_LOG_ID_TYPE_PRINT) &&
(msg_level <= log_id->log_level_print))
{
strcpy(receive_msg->u.str, log_string);
dev_log_print_task_handle_message(m);
}
else
{
bcmos_msg_free(m);
}
/* Save to file */
if ((log_id->log_type & DEV_LOG_ID_TYPE_SAVE) &&
(msg_level <= log_id->log_level_save))
{
bcm_dev_log_file_save_msg(dev_log.files, log_string);
}
}
}
static int default_time_to_str(uint32_t time_stamp, char *time_str, int time_str_size)
{
return snprintf(time_str, time_str_size, "%u", time_stamp);
}
static uint32_t default_get_time(void)
{
return 0;
}
static void default_print(void *arg, const char *format, ...)
{
va_list args;
va_start(args, format);
bcmos_vprintf(format, args);
va_end(args);
}
static bcmos_errno default_open_callback_cond_reset(const bcm_dev_log_file_parm *file_parm, bcm_dev_log_file *file, bcmos_bool is_rewind)
{
bcmos_errno err;
if (!file->file_parm.start_addr || file->file_parm.size <= MEM_FILE_HDR_SIZE)
return BCM_ERR_PARM;
/* Create file mutex */
err = bcmos_mutex_create(&file->u.mem_file.mutex, 0, NULL);
if (err != BCM_ERR_OK)
{
DEV_LOG_ERROR_PRINTF("Error: Can't create mutex (error: %d)\n", (int)err);
return err;
}
/* Check file magic string */
memcpy(&file->u.mem_file.file_header, (uint8_t *)file->file_parm.start_addr, MEM_FILE_HDR_SIZE);
if (memcmp(FILE_MAGIC_STR, file->u.mem_file.file_header.file_magic, FILE_MAGIC_STR_SIZE))
{
DEV_LOG_INFO_PRINTF("No file magic string - file is empty/corrupt\n");
if (!is_rewind || !file->file_parm.rewind_cb)
{
bcmos_mutex_destroy(&file->u.mem_file.mutex);
return BCM_ERR_NOENT;
}
return file->file_parm.rewind_cb(file);
}
DEV_LOG_INFO_PRINTF("Attached to existing file\n");
return BCM_ERR_OK;
}
static bcmos_errno default_open_callback(const bcm_dev_log_file_parm *file_parm, bcm_dev_log_file *file)
{
return default_open_callback_cond_reset(file_parm, file, BCMOS_TRUE);
}
static bcmos_errno default_close_callback(bcm_dev_log_file *file)
{
bcmos_mutex_destroy(&file->u.mem_file.mutex);
return BCM_ERR_OK;
}
/* Look for start of msg character */
static int get_msg_start_offset(bcm_dev_log_file *file, uint32_t offset, uint32_t max_len)
{
uint8_t *buf, *msg;
buf = (uint8_t *)file->file_parm.start_addr + offset + MEM_FILE_HDR_SIZE;
msg = memchr(buf, DEV_LOG_MSG_START_CHAR, max_len);
if (!msg)
return -1;
return (msg - buf + 1);
}
/* Look for 0-terminator */
static int get_msg_end_offset(bcm_dev_log_file *file, uint32_t offset, uint32_t max_len)
{
uint8_t *buf, *end;
buf = (uint8_t *)file->file_parm.start_addr + offset + MEM_FILE_HDR_SIZE;
end = memchr(buf, 0, max_len);
if (!end)
return -1;
return (end - buf + 1);
}
static int default_read_callback(bcm_dev_log_file *log_file, uint32_t *p_offset, void *buf, uint32_t length)
{
uint32_t offset = *p_offset;
uint32_t output_length = 0;
uint32_t scan_length = 0;
int start, end;
bcmos_bool read_wrap = BCMOS_FALSE;
/* If file wrapped around, offset is indeterminate, scan for start from current offset to end of file buffer,
* if start not found, then try again from beginning of buffer up to write ptr */
if (log_file->u.mem_file.file_header.file_wrap_cnt)
{
scan_length = log_file->u.mem_file.file_header.data_size - offset;
if (scan_length <= 0)
{
/* Insane offset passed in from user, reset it */
DEV_LOG_ERROR_PRINTF("%s: reset bad read offset:%d (> size of log buffer)\n", __FUNCTION__, offset);
*p_offset = 0;
return 0;
}
/* Find beginning of the next message */
start = get_msg_start_offset(log_file, offset, scan_length);
if (start < 0)
{
/* Didn't find any up to the end of buffer. Scan again from the start, up to write offset */
offset = 0;
if (!log_file->u.mem_file.file_header.write_offset)
return 0;
start = get_msg_start_offset(log_file, 0, log_file->u.mem_file.file_header.write_offset - 1);
if (start <= 0)
{
return 0;
}
}
}
else
{
/* file not wrapped, scan from current offset up to write ptr */
scan_length = log_file->u.mem_file.file_header.write_offset - offset;
/* Scan for start of message. Without wrap-around it should be between read offset, and the write ptr */
start = get_msg_start_offset(log_file, offset, scan_length);
if (start <= 0)
return 0;
}
offset += start;
/* We have the beginning. Now find the end of message and copy to the user buffer if there is enough room */
if (offset + length > log_file->u.mem_file.file_header.data_size)
{
/* Possible read wrap may occur, scan up to end of file buffer first */
scan_length = log_file->u.mem_file.file_header.data_size - offset;
end = get_msg_end_offset(log_file, offset, scan_length);
if (end >= 0)
{
/* Found end before end of buffer, no read wrap, just copy and return */
memcpy(buf, (uint8_t *)log_file->file_parm.start_addr + MEM_FILE_HDR_SIZE + offset, end);
*p_offset += start + end;
return end;
}
/* Didn't find end of message in the end of file buffer. Copy first part from offset up to end of buffer, then wrap around */
memcpy(buf, (uint8_t *)log_file->file_parm.start_addr + MEM_FILE_HDR_SIZE + offset, scan_length);
output_length = scan_length;
buf = (uint8_t *)buf + scan_length;
length -= scan_length; /* reduce remaining buffer space by size copied */
offset = 0; /* Reset to beginning of buffer for final "end" scan */
read_wrap = BCMOS_TRUE;
scan_length = log_file->u.mem_file.file_header.write_offset - 1; /* Limit wrapped end scan from beginning of buffer up to write ptr */
}
else
{
/* No read wrap, just scan for end from current offset to the end of the file , since the end might be past the buffer length */
scan_length = log_file->u.mem_file.file_header.data_size - offset;
}
end = get_msg_end_offset(log_file, offset, scan_length);
if (end <= 0)
{
/* something is wrong. msg is not terminated */
DEV_LOG_ERROR_PRINTF("%s: no message end found!\n", __FUNCTION__);
return 0;
}
/* If there is no room for the whole message - return overflow */
if (end > length)
return (int)BCM_ERR_OVERFLOW;
/* Copy whole message, or second part for wrapped read */
memcpy(buf, (uint8_t *)log_file->file_parm.start_addr + MEM_FILE_HDR_SIZE + offset, end);
output_length += end;
if (read_wrap)
{
/* Reset wrapped read ptr, and write wrap count */
log_file->u.mem_file.file_header.file_wrap_cnt = 0;
*p_offset = end;
}
else
*p_offset += start + output_length; /* Increment read ptr */
return output_length;
}
static int get_num_of_overwritten_messages(uint8_t *buf, uint32_t length)
{
uint8_t *p;
int n = 0;
do
{
p = memchr(buf, DEV_LOG_MSG_START_CHAR, length);
if (p == NULL)
break;
++n;
length -= (p + 1 - buf);
buf = p + 1;
} while(length);
return n;
}
static int default_write_callback_unprotected(bcm_dev_log_file *file, const void *buf, uint32_t length)
{
uint32_t offset, next_offset;
uint8_t *p;
int n_overwritten = 0;
if ((file->file_parm.flags & BCM_DEV_LOG_FILE_FLAG_STOP_WHEN_FULL) && file->is_full)
return 0;
if (!length)
return 0;
offset = file->u.mem_file.file_header.write_offset;
next_offset = offset + length + 1; /* 1 extra character for record delimiter */
/* Handle overflow */
if (next_offset >= file->u.mem_file.file_header.data_size)
{
uint32_t tail_length;
/* Split buffer in 2 */
tail_length = next_offset - file->u.mem_file.file_header.data_size; /* 2nd segment length */
if ((file->file_parm.flags & BCM_DEV_LOG_FILE_FLAG_STOP_WHEN_FULL) && tail_length)
{
file->is_full = BCMOS_TRUE;
return 0;
}
length -= tail_length;
/* "if (next_offset >= file->u.mem_file.file_header.data_size)" condition
* guarantees that there is room for at least 1 character in the end of file */
p = (uint8_t *)file->file_parm.start_addr + offset + MEM_FILE_HDR_SIZE;
if (file->u.mem_file.file_header.file_wrap_cnt)
n_overwritten += get_num_of_overwritten_messages(p, length + 1);
*p = DEV_LOG_MSG_START_CHAR;
if (length)
{
memcpy(p + 1, buf, length);
buf = (const uint8_t *)buf + length;
}
if (tail_length)
{
p = (uint8_t *)file->file_parm.start_addr + MEM_FILE_HDR_SIZE;
if (file->u.mem_file.file_header.file_wrap_cnt)
n_overwritten += get_num_of_overwritten_messages(p, tail_length);
memcpy(p, buf, tail_length);
++file->u.mem_file.file_header.file_wrap_cnt;
}
next_offset = tail_length;
}
else
{
p = (uint8_t *)file->file_parm.start_addr + MEM_FILE_HDR_SIZE + offset;
if (file->u.mem_file.file_header.file_wrap_cnt)
n_overwritten += get_num_of_overwritten_messages(p, length + 1);
*(p++) = DEV_LOG_MSG_START_CHAR;
memcpy(p, buf, length);
}
file->u.mem_file.file_header.write_offset = next_offset;
file->u.mem_file.file_header.num_msgs += (1 - n_overwritten);
/* update the header */
memcpy((uint8_t *)file->file_parm.start_addr, &file->u.mem_file.file_header, MEM_FILE_HDR_SIZE);
/* send almost full indication if necessary */
if (file->almost_full.send_ind_cb &&
!file->almost_full.ind_sent &&
file->u.mem_file.file_header.write_offset > file->almost_full.threshold)
{
file->almost_full.ind_sent = (file->almost_full.send_ind_cb(file->almost_full.priv) == BCM_ERR_OK);
}
return length;
}
static int default_write_callback(bcm_dev_log_file *file, const void *buf, uint32_t length)
{
bcmos_mutex_lock(&file->u.mem_file.mutex);
length = default_write_callback_unprotected(file, buf, length);
bcmos_mutex_unlock(&file->u.mem_file.mutex);
return length;
}
static bcmos_errno default_rewind_callback(bcm_dev_log_file *file)
{
bcmos_mutex_lock(&file->u.mem_file.mutex);
DEV_LOG_INFO_PRINTF("Clear file\n");
file->u.mem_file.file_header.file_wrap_cnt = 0;
file->u.mem_file.file_header.write_offset = 0;
file->u.mem_file.file_header.data_size = file->file_parm.size - MEM_FILE_HDR_SIZE;
file->u.mem_file.file_header.num_msgs = 0;
strcpy(file->u.mem_file.file_header.file_magic, FILE_MAGIC_STR);
memcpy((uint8_t *)file->file_parm.start_addr, &file->u.mem_file.file_header, MEM_FILE_HDR_SIZE);
file->almost_full.ind_sent = BCMOS_FALSE;
bcmos_mutex_unlock(&file->u.mem_file.mutex);
return BCM_ERR_OK;
}
static void set_default_file_callbacks(bcm_dev_log_file *file)
{
file->file_parm.open_cb = default_open_callback;
file->file_parm.close_cb = default_close_callback;
file->file_parm.read_cb = default_read_callback;
file->file_parm.write_cb = default_write_callback;
file->file_parm.rewind_cb = default_rewind_callback;
}
static inline bcmos_bool bcm_dev_log_is_memory_file(bcm_dev_log_file *file)
{
return (file->file_parm.open_cb == default_open_callback);
}
bcmos_errno bcm_dev_log_file_clear(bcm_dev_log_file *file)
{
if (!file || !(file->file_parm.flags & BCM_DEV_LOG_FILE_FLAG_VALID))
return BCM_ERR_PARM;
if (!file->file_parm.rewind_cb)
return BCM_ERR_NOT_SUPPORTED;
return file->file_parm.rewind_cb(file);
}
/* File index to file handle */
bcm_dev_log_file *bcm_dev_log_file_get(uint32_t file_index)
{
bcm_dev_log_file *file = &dev_log.files[file_index];
if ((file_index >= DEV_LOG_MAX_FILES) || !(file->file_parm.flags & BCM_DEV_LOG_FILE_FLAG_VALID))
return NULL;
return file;
}
/* Read from file */
int bcm_dev_log_file_read(bcm_dev_log_file *file, uint32_t *offset, char *buf, uint32_t buf_len)
{
int len;
if (!file || !buf || !(file->file_parm.flags & BCM_DEV_LOG_FILE_FLAG_VALID))
return (int)BCM_ERR_PARM;
len = file->file_parm.read_cb(file, offset, buf, buf_len);
/* If nothing more to read and CLEAR_AFTER_READ mode, read again under lock and clear if no new records */
if (!len && bcm_dev_log_is_memory_file(file) && (file->file_parm.flags & BCM_DEV_LOG_FILE_FLAG_CLEAR_AFTER_READ))
{
bcmos_mutex_lock(&file->u.mem_file.mutex);
len = file->file_parm.read_cb(file, offset, buf, buf_len);
if (!len)
{
file->file_parm.rewind_cb(file);
*offset = 0; /* Also reset user read ptr when log file is cleared down! */
}
bcmos_mutex_unlock(&file->u.mem_file.mutex);
}
return len;
}
/* Attach file to memory buffer */
bcmos_errno bcm_dev_log_file_attach(void *buf, uint32_t buf_len, bcm_dev_log_file *file)
{
bcmos_errno rc;
dev_log_mem_file_header *hdr = (dev_log_mem_file_header *)buf;
if (!buf || !file || buf_len <= MEM_FILE_HDR_SIZE)
return BCM_ERR_PARM;
if (memcmp(FILE_MAGIC_STR, hdr->file_magic, FILE_MAGIC_STR_SIZE))
return BCM_ERR_NOENT;
#if DEV_LOG_ENDIAN != BCM_CPU_ENDIAN
hdr->file_wrap_cnt = bcmos_endian_swap_u32(hdr->file_wrap_cnt);
hdr->write_offset = bcmos_endian_swap_u32(hdr->write_offset);
hdr->data_size = bcmos_endian_swap_u32(hdr->data_size);
hdr->num_msgs = bcmos_endian_swap_u32(hdr->num_msgs);
#endif
memset(file, 0, sizeof(*file));
file->file_parm.start_addr = buf;
file->file_parm.size = buf_len;
file->file_parm.flags = BCM_DEV_LOG_FILE_FLAG_VALID;
set_default_file_callbacks(file);
rc = default_open_callback_cond_reset(&file->file_parm, file, BCMOS_FALSE);
if (rc)
return rc;
if (!file->u.mem_file.file_header.num_msgs)
return BCM_ERR_NOENT;
return BCM_ERR_OK;
}
/* Detach file handle from memory buffer */
bcmos_errno bcm_dev_log_file_detach(bcm_dev_log_file *file)
{
if (!file || !(file->file_parm.flags & BCM_DEV_LOG_FILE_FLAG_VALID))
return BCM_ERR_PARM;
file->file_parm.flags = BCM_DEV_LOG_FILE_FLAG_VALID;
bcmos_mutex_destroy(&file->u.mem_file.mutex);
return BCM_ERR_OK;
}
#ifdef BCM_OS_POSIX
/* Regular file callbacks */
/****************************************************************************************/
/* OPEN CALLBACK: open memory/file */
/* file_parm - file parameters */
/* file - file */
/****************************************************************************************/
static bcmos_errno _dev_log_reg_file_open(const bcm_dev_log_file_parm *file_parm, bcm_dev_log_file *file)
{
bcmos_errno err = BCM_ERR_OK;
file->file_parm = *file_parm;
file->u.reg_file_handle = fopen((char *)file_parm->udef_parms, "w+");
if (!file->u.reg_file_handle)
{
bcmos_printf("DEV_LOG: can't open file %s for writing\n", (char *)file_parm->udef_parms);
err = BCM_ERR_IO;
}
return err;
}
/****************************************************************************************/
/* CLOSE CALLBACK: close memory/file */
/* file - file handle */
/****************************************************************************************/
static bcmos_errno _dev_log_reg_file_close(bcm_dev_log_file *file)
{
if (file->u.reg_file_handle)
{
fclose(file->u.reg_file_handle);
/* coverity[misra_violation] - we're not "using" the closed file handle, we're invalidating it */
file->u.reg_file_handle = NULL;
}
return BCM_ERR_OK;
}
/****************************************************************************************/
/* REWIND CALLBACK: clears memory/file */
/* file - file handle */
/****************************************************************************************/
static bcmos_errno _dev_log_reg_file_rewind(bcm_dev_log_file *file)
{
bcmos_errno err = BCM_ERR_OK;
FILE *f;
if (file->u.reg_file_handle)
{
f = freopen((const char *)file->file_parm.udef_parms, "w+", file->u.reg_file_handle);
if (NULL != f)
{
file->u.reg_file_handle = f;
}
else
{
err = BCM_ERR_IO;
bcmos_printf("DEV_LOG: can't open file %s for writing\n", (char *)file->file_parm.udef_parms);
}
}
return err;
}
/****************************************************************************************/
/* READ_CALLBACK: read form memory/file */
/* offset - the offset in bytes to read from, output */
/* buf - Where to put the result */
/* length - Buffer length */
/* This function should return the number of bytes actually read from file or 0 if EOF */
/****************************************************************************************/
static int _dev_log_reg_file_read(bcm_dev_log_file *file, uint32_t *offset, void *buf, uint32_t length)
{
int n = 0;
if (file->u.reg_file_handle)
{
if (!fseek(file->u.reg_file_handle, SEEK_SET, *offset))
n = fread(buf, 1, length, file->u.reg_file_handle);
*offset = ftell(file->u.reg_file_handle);
}
return (n < 0) ? 0 : n;
}
/****************************************************************************************/
/* WRITE_CALLBACK: write form memory/file */
/* buf - The buffer that should be written */
/* length - The number of bytes to write */
/* This function should return the number of bytes actually written to file or 0 if EOF */
/****************************************************************************************/
static int _dev_log_reg_file_write(bcm_dev_log_file *file, const void *buf, uint32_t length)
{
const char *cbuf = (const char *)buf;
int n = 0;
if (file->u.reg_file_handle)
{
/* Remove 0 terminator */
if (length && !cbuf[length-1])
--length;
n = fwrite(buf, 1, length, file->u.reg_file_handle);
fflush(file->u.reg_file_handle);
}
return n;
}
static void set_regular_file_callbacks(bcm_dev_log_file *file)
{
file->file_parm.open_cb = _dev_log_reg_file_open;
file->file_parm.close_cb = _dev_log_reg_file_close;
file->file_parm.read_cb = _dev_log_reg_file_read;
file->file_parm.write_cb = _dev_log_reg_file_write;
file->file_parm.rewind_cb = _dev_log_reg_file_rewind;
}
#endif /* #ifdef BCM_OS_POSIX */
#ifdef DEV_LOG_SYSLOG
/* linux syslog integration */
/****************************************************************************************/
/* OPEN CALLBACK: open syslog interface */
/* file_parm->udef_parm contains optional log ident */
/****************************************************************************************/
static bcmos_errno _dev_log_syslog_file_open(const bcm_dev_log_file_parm *file_parm, bcm_dev_log_file *file)
{
file->file_parm = *file_parm;
openlog((const char *)file_parm->udef_parms, 0, LOG_USER);
return BCM_ERR_OK;
}
/****************************************************************************************/
/* CLOSE CALLBACK: close syslog interface */
/****************************************************************************************/
static bcmos_errno _dev_log_syslog_file_close(bcm_dev_log_file *file)
{
closelog();
return BCM_ERR_OK;
}
/****************************************************************************************/
/* REWIND CALLBACK: not supported by syslog. Return OK to prevent request failure */
/****************************************************************************************/
static bcmos_errno _dev_log_syslog_file_rewind(bcm_dev_log_file *file)
{
return BCM_ERR_OK;
}
/****************************************************************************************/
/* READ_CALLBACK: reading from syslog is not supported */
/****************************************************************************************/
static int _dev_log_syslog_file_read(bcm_dev_log_file *file, uint32_t *offset, void *buf, uint32_t length)
{
return 0;
}
/****************************************************************************************/
/* WRITE_CALLBACK: write to syslog */
/* buf - The buffer that should be written */
/* length - The number of bytes to write */
/* This function should return the number of bytes actually written to file or 0 if EOF */
/****************************************************************************************/
static int _dev_log_syslog_file_write(bcm_dev_log_file *file, const void *buf, uint32_t length)
{
const char *cbuf = (const char *)buf;
static int log_priority = LOG_DEBUG;
/* Identify log lovel */
if (cbuf && cbuf[0] == '[')
{
const char *clevel = strchr(cbuf, ' ');
if (clevel)
{
switch (*(clevel + 1))
{
case 'F':
log_priority = LOG_CRIT;
break;
case 'E':
log_priority = LOG_ERR;
break;
case 'W':
log_priority = LOG_WARNING;
break;
case 'I':
log_priority = LOG_INFO;
break;
case 'D':
log_priority = LOG_DEBUG;
break;
default:
break;
}
}
}
syslog(log_priority, "%s", cbuf);
return length;
}
static void set_syslog_file_callbacks(bcm_dev_log_file *file)
{
file->file_parm.open_cb = _dev_log_syslog_file_open;
file->file_parm.close_cb = _dev_log_syslog_file_close;
file->file_parm.read_cb = _dev_log_syslog_file_read;
file->file_parm.write_cb = _dev_log_syslog_file_write;
file->file_parm.rewind_cb = _dev_log_syslog_file_rewind;
}
#endif /* #ifdef DEV_LOG_SYSLOG */
static bcmos_errno bcm_dev_log_create(
const bcm_dev_log_parm *dev_log_parm,
const bcmos_task_parm *save_task_parm,
const bcmos_task_parm *print_task_parm,
const bcmos_msg_queue_parm *save_queue_parm,
const bcmos_msg_queue_parm *print_queue_parm,
const bcmos_msg_pool_parm *pool_parm)
{
bcmos_errno err;
int i;
if (!dev_log_parm)
return BCM_ERR_PARM;
if (dev_log.state != BCM_DEV_LOG_STATE_UNINITIALIZED)
return BCM_ERR_ALREADY;
/* Set user callbacks */
dev_log.dev_log_parm = *dev_log_parm;
if (!dev_log.dev_log_parm.print_cb)
dev_log.dev_log_parm.print_cb = default_print;
if (!dev_log.dev_log_parm.get_time_cb)
dev_log.dev_log_parm.get_time_cb = default_get_time;
if (!dev_log.dev_log_parm.time_to_str_cb)
dev_log.dev_log_parm.time_to_str_cb = default_time_to_str;
for (i = 0; (i < DEV_LOG_MAX_FILES) && (dev_log_parm->log_file[i].flags & BCM_DEV_LOG_FILE_FLAG_VALID); i++)
{
/* Copy log files */
dev_log.files[i].file_parm = dev_log_parm->log_file[i];
if (!dev_log.files[i].file_parm.open_cb)
{
if (dev_log.files[i].file_parm.type == BCM_DEV_LOG_FILE_MEMORY)
set_default_file_callbacks(&dev_log.files[i]);
#ifdef BCM_OS_POSIX
else if (dev_log.files[i].file_parm.type == BCM_DEV_LOG_FILE_REGULAR)
{
set_regular_file_callbacks(&dev_log.files[i]);
}
#endif
#ifdef DEV_LOG_SYSLOG
else if (dev_log.files[i].file_parm.type == BCM_DEV_LOG_FILE_SYSLOG)
set_syslog_file_callbacks(&dev_log.files[i]);
#endif
else
{
DEV_LOG_ERROR_PRINTF("file%d: open_cb must be set for user-defined file\n\n", i);
continue;
}
}
err = dev_log.files[i].file_parm.open_cb(&dev_log.files[i].file_parm, &dev_log.files[i]);
if (err)
{
DEV_LOG_ERROR_PRINTF("file%d: open failed: %s (%d)\n\n", i, bcmos_strerror(err), err );
continue;
}
DEV_LOG_INFO_PRINTF("file: start_addr: 0x%p, size: %u, max msg size %u\n",
dev_log.files[i].file_parm.start_addr, dev_log.files[i].file_parm.size, MAX_DEV_LOG_STRING_SIZE);
}
/* Create pool */
err = bcmos_msg_pool_create(&dev_log.pool, pool_parm);
if (err != BCM_ERR_OK)
{
DEV_LOG_ERROR_PRINTF("Error: Can't create pool (error: %d)\n", (int)err);
return err;
}
/* Create message queues */
err = bcmos_msg_queue_create(&dev_log.save_queue, save_queue_parm);
if (err != BCM_ERR_OK)
{
DEV_LOG_ERROR_PRINTF("(%s) Error: Can't create save queue (error: %d)\n", __FUNCTION__, (int)err);
return err;
}
err = bcmos_msg_queue_create(&dev_log.print_queue, print_queue_parm);
if (err != BCM_ERR_OK)
{
DEV_LOG_ERROR_PRINTF("(%s) Error: Can't create print queue (error: %d)\n", __FUNCTION__, (int)err);
return err;
}
/* Create tasks */
err = bcmos_task_create(&dev_log.save_task, save_task_parm);
if (err != BCM_ERR_OK)
{
DEV_LOG_ERROR_PRINTF("Error: Can't spawn save task (error: %d)\n", (int)err);
return err;
}
err = bcmos_task_create(&dev_log.print_task, print_task_parm);
if (err != BCM_ERR_OK)
{
DEV_LOG_ERROR_PRINTF("Error: Can't spawn print task (error: %d)\n", (int)err);
return err;
}
err = bcmos_sem_create(&dev_log.save_task_is_terminated, 0, 0, "save_task_sem");
if (err != BCM_ERR_OK)
{
DEV_LOG_ERROR_PRINTF("Error: Can't create save task sem (error: %d)\n", (int)err);
return err;
}
err = bcmos_sem_create(&dev_log.print_task_is_terminated, 0, 0, "print_task_sem");
if (err != BCM_ERR_OK)
{
DEV_LOG_ERROR_PRINTF("Error: Can't create print task sem (error: %d)\n", (int)err);
return err;
}
dev_log.state = BCM_DEV_LOG_STATE_ENABLED;
return BCM_ERR_OK;
}
void bcm_dev_log_destroy(void)
{
bcmos_errno err;
uint32_t i;
bcmos_msg_send_flags msg_flags;
if (dev_log.state == BCM_DEV_LOG_STATE_UNINITIALIZED)
{
return;
}
/* Send a shutdown message to each task. When received by the main loops, it will tear down the tasks gracefully.
* If the flag is set to tear down immediately, we'll send an URGENT teardown message, so it'll be handled before
* all oustanding log messages (the oustanding log messages will be freed during bcmos_msg_queue_destroy). */
msg_flags = BCMOS_MSG_SEND_NOLIMIT;
if ((dev_log.flags & BCM_DEV_LOG_FLAG_DESTROY_IMMEDIATELY) != 0)
msg_flags |= BCMOS_MSG_SEND_URGENT;
/* The save task depends on the print task, so we terminate the save task first. */
bcmos_msg_send(&dev_log.save_queue, &shutdown_msg, msg_flags);
bcmos_sem_wait(&dev_log.save_task_is_terminated, BCMOS_WAIT_FOREVER);
bcmos_msg_send(&dev_log.print_queue, &shutdown_msg, msg_flags);
bcmos_sem_wait(&dev_log.print_task_is_terminated, BCMOS_WAIT_FOREVER);
bcmos_sem_destroy(&dev_log.save_task_is_terminated);
bcmos_sem_destroy(&dev_log.print_task_is_terminated);
err = bcmos_task_destroy(&dev_log.save_task);
if (err != BCM_ERR_OK)
{
DEV_LOG_ERROR_PRINTF("Error: Can't destroy dev_log save task (error: %d)\n", (int)err);
}
err = bcmos_task_destroy(&dev_log.print_task);
if (err != BCM_ERR_OK)
{
DEV_LOG_ERROR_PRINTF("Error: Can't destroy dev_log print task (error: %d)\n", (int)err);
}
err = bcmos_msg_queue_destroy(&dev_log.save_queue);
if (err != BCM_ERR_OK)
{
DEV_LOG_ERROR_PRINTF("Error: Can't destroy save queue (error: %d)\n", (int)err);
}
err = bcmos_msg_queue_destroy(&dev_log.print_queue);
if (err != BCM_ERR_OK)
{
DEV_LOG_ERROR_PRINTF("Error: Can't destroy print queue (error: %d)\n", (int)err);
}
err = bcmos_msg_pool_destroy(&dev_log.pool);
if (err != BCM_ERR_OK)
{
DEV_LOG_ERROR_PRINTF("Error: Can't destroy pool (error: %d)\n", (int)err);
}
for (i = 0; (i < DEV_LOG_MAX_FILES) && (dev_log.dev_log_parm.log_file[i].flags & BCM_DEV_LOG_FILE_FLAG_VALID); i++)
{
dev_log.files[i].file_parm.close_cb(&dev_log.files[i]);
}
dev_log.state = BCM_DEV_LOG_STATE_UNINITIALIZED;
}
typedef struct
{
bcmos_msg msg;
dev_log_queue_msg log_queue_msg;
bcmos_bool lock;
bcmos_fastlock fastlock;
} bcm_dev_log_drop_msg;
typedef struct
{
bcm_dev_log_drop_msg msg;
uint32_t drops;
uint32_t reported_drops;
bcmos_timer timer;
uint32_t last_report_timestamp;
} bcm_dev_log_drop;
static bcm_dev_log_drop dev_log_drop;
static void bcm_dev_log_log_message_release_drop(bcmos_msg *m)
{
unsigned long flags;
flags = bcmos_fastlock_lock(&dev_log_drop.msg.fastlock);
dev_log_drop.msg.lock = BCMOS_FALSE;
bcmos_fastlock_unlock(&dev_log_drop.msg.fastlock, flags);
/* Schedule a timer to report extra drops, because we may not meet DEV_LOG_DROP_REPORT_DROP_THRESHOLD soon. */
bcmos_timer_start(&dev_log_drop.timer, DEV_LOG_DROP_REPORT_RATE_US);
}
static void _bcm_dev_log_drop_report(void)
{
bcmos_msg *msg;
dev_log_queue_msg *log_queue_msg;
static char drop_str[MAX_DEV_LOG_STRING_SIZE];
msg = &dev_log_drop.msg.msg;
msg->release = bcm_dev_log_log_message_release_drop;
log_queue_msg = &dev_log_drop.msg.log_queue_msg;
log_queue_msg->flags = BCM_LOG_FLAG_DONT_SKIP_PRINT;
log_queue_msg->time_stamp = dev_log.dev_log_parm.get_time_cb();
log_queue_msg->msg_level = DEV_LOG_LEVEL_ERROR;
sprintf(drop_str, "Log message pool exhausted, dropped message count=%u\n", dev_log_drop.drops - dev_log_drop.reported_drops);
log_queue_msg->u.fmt_args.fmt = (const char *)drop_str;
log_queue_msg->log_id = (dev_log_id_parm *)def_log_id;
log_queue_msg->time_stamp = dev_log.dev_log_parm.get_time_cb();
dev_log_drop.reported_drops = dev_log_drop.drops;
dev_log_drop.last_report_timestamp = bcmos_timestamp();
msg->data = log_queue_msg;
msg->size = sizeof(*log_queue_msg);
bcmos_msg_send(&dev_log.save_queue, msg, BCMOS_MSG_SEND_AUTO_FREE);
}
void bcm_dev_log_drop_report(void)
{
unsigned long flags;
dev_log_drop.drops++;
flags = bcmos_fastlock_lock(&dev_log_drop.msg.fastlock);
/* The 1st drop report will be done immediately, because although DEV_LOG_DROP_REPORT_DROP_THRESHOLD isn't reached, the time difference is greater than
* DEV_LOG_DROP_REPORT_RATE_US. */
if (dev_log_drop.msg.lock ||
((dev_log_drop.drops - dev_log_drop.reported_drops < DEV_LOG_DROP_REPORT_DROP_THRESHOLD) &&
(bcmos_timestamp() - dev_log_drop.last_report_timestamp < DEV_LOG_DROP_REPORT_RATE_US)))
{
bcmos_fastlock_unlock(&dev_log_drop.msg.fastlock, flags);
return;
}
dev_log_drop.msg.lock = BCMOS_TRUE;
bcmos_fastlock_unlock(&dev_log_drop.msg.fastlock, flags);
/* Do the actual report. */
_bcm_dev_log_drop_report();
}
static bcmos_timer_rc bcm_dev_log_drop_timer_cb(bcmos_timer *timer, long data)
{
unsigned long flags;
flags = bcmos_fastlock_lock(&dev_log_drop.msg.fastlock);
if (dev_log_drop.msg.lock)
{
bcmos_fastlock_unlock(&dev_log_drop.msg.fastlock, flags);
/* Logger task hasn't released the lock yet.
* bcm_dev_log_log_message_release_drop() will (re)start drop reporting timer eventually. */
}
else
{
if (dev_log_drop.drops == dev_log_drop.reported_drops)
{
/* No new drops to report. */
bcmos_fastlock_unlock(&dev_log_drop.msg.fastlock, flags);
return BCMOS_TIMER_OK;
}
dev_log_drop.msg.lock = BCMOS_TRUE;
bcmos_fastlock_unlock(&dev_log_drop.msg.fastlock, flags);
/* Do the actual report. */
_bcm_dev_log_drop_report();
}
return BCMOS_TIMER_OK;
}
bcmos_errno bcm_dev_log_init_default_logger_ext(
bcm_dev_log_parm *dev_log_parm,
uint32_t num_files,
uint32_t stack_size,
bcmos_task_priority priority,
uint32_t pool_size)
{
bcmos_errno err;
bcmos_task_parm save_task_parm = {0};
bcmos_task_parm print_task_parm = {0};
bcmos_msg_queue_parm print_queue_parm = {0};
bcmos_msg_queue_parm save_queue_parm = {0};
bcmos_msg_pool_parm pool_parm = {0};
bcmos_timer_parm timer_params =
{
.name = "dev_log_drop_timer",
.owner = BCMOS_MODULE_ID_NONE, /* Will be called in ISR context */
.handler = bcm_dev_log_drop_timer_cb,
};
if (!dev_log_parm)
{
DEV_LOG_ERROR_PRINTF("Error: dev_log_parm must be set\n");
return BCM_ERR_PARM;
}
save_task_parm.priority = priority;
save_task_parm.stack_size = stack_size;
save_task_parm.name = "dev_log_save";
save_task_parm.handler = dev_log_save_task;
save_task_parm.data = 0;
print_task_parm.priority = priority;
print_task_parm.stack_size = stack_size;
print_task_parm.name = "dev_log_print";
print_task_parm.handler = dev_log_print_task;
print_task_parm.data = 0;
/* It is important to avoid terminating logger task during an exception, as logger task is low priority and might have backlog of unhandled messages.
* Even if as a result of the exception the logger task will be in a deadlock waiting for a resource (semaphore/mutex/timer), it is in lower priority than CLI and thus should not block
* CLI. */
save_task_parm.flags = BCMOS_TASK_FLAG_NO_SUSPEND_ON_OOPS;
print_task_parm.flags = BCMOS_TASK_FLAG_NO_SUSPEND_ON_OOPS;
save_queue_parm.name = "dev_log_save";
save_queue_parm.size = 0; /* unlimited */
print_queue_parm.name = "dev_log_print";
print_queue_parm.size = 0; /* unlimited */
pool_parm.name = "dev_log";
pool_parm.size = pool_size;
pool_parm.data_size = sizeof(dev_log_queue_msg);
def_log_id = bcm_dev_log_id_register("default", DEV_LOG_LEVEL_INFO, DEV_LOG_ID_TYPE_BOTH);
err = bcmos_timer_create(&dev_log_drop.timer, &timer_params);
BCMOS_TRACE_CHECK_RETURN(err, err, "bcmos_timer_create");
bcmos_fastlock_init(&dev_log_drop.msg.fastlock, 0);
if (!dev_log_parm->get_time_cb)
dev_log_parm->get_time_cb = bcmos_timestamp;
err = bcm_dev_log_create(
dev_log_parm,
&save_task_parm,
&print_task_parm,
&save_queue_parm,
&print_queue_parm,
&pool_parm);
BCMOS_TRACE_CHECK_RETURN(err, err, "bcm_dev_log_create");
/* Init the frontend */
bcm_dev_log_frontend_init();
return BCM_ERR_OK;
}
bcmos_errno bcm_dev_log_init_default_logger(void **start_addresses,
uint32_t *sizes,
bcm_dev_log_file_flags *flags,
uint32_t num_files,
uint32_t stack_size,
bcmos_task_priority priority,
uint32_t pool_size)
{
bcm_dev_log_parm dev_log_parm = {0};
uint32_t i;
for (i = 0; i < num_files; i++)
{
dev_log_parm.log_file[i].start_addr = start_addresses[i];
dev_log_parm.log_file[i].size = sizes[i];
/* size[i] might be 0 in simulation build for sram buffer. */
dev_log_parm.log_file[i].flags = (bcm_dev_log_file_flags)
((sizes[i] ? BCM_DEV_LOG_FILE_FLAG_VALID : BCM_DEV_LOG_FILE_FLAG_NONE) |
(flags ? flags[i] : BCM_DEV_LOG_FILE_FLAG_WRAP_AROUND));
}
return bcm_dev_log_init_default_logger_ext(&dev_log_parm, num_files, stack_size, priority,
pool_size);
}
/* Log entry timestamp formatting callback */
static int bcm_log_time_to_ms_str_cb(uint32_t time_stamp, char *time_str, int time_str_size)
{
return snprintf(time_str, time_str_size, "%u", time_stamp / 1000); /* convert from usec to msec. */
}
/* Simplified init function intended mainly for host use */
bcmos_errno bcm_log_init(const dev_log_init_parms *init_parms)
{
bcmos_errno rc;
bcm_dev_log_parm log_parms = {};
uint32_t queue_size;
log_parms.time_to_str_cb = bcm_log_time_to_ms_str_cb;
if (init_parms->type == BCM_DEV_LOG_FILE_MEMORY)
{
log_parms.log_file[0].size = init_parms->mem_size ?
init_parms->mem_size : BCM_DEV_LOG_DEFAULT_MEM_SIZE;
log_parms.log_file[0].start_addr = bcmos_calloc(log_parms.log_file[0].size);
log_parms.log_file[0].flags = (bcm_dev_log_file_flags)(BCM_DEV_LOG_FILE_FLAG_WRAP_AROUND | BCM_DEV_LOG_FILE_FLAG_CLEAR_AFTER_READ);
if (log_parms.log_file[0].start_addr == NULL)
return BCM_ERR_NOMEM;
}
#ifdef BCM_OS_POSIX
else if (init_parms->type == BCM_DEV_LOG_FILE_REGULAR)
{
if (init_parms->filename == NULL)
{
bcmos_printf("%s: filename is required for log type BCMOLT_LOG_TYPE_FILE\n", __FUNCTION__);
return BCM_ERR_PARM;
}
log_parms.log_file[0].udef_parms = (char *)(long)init_parms->filename;
}
#endif
else
#ifdef DEV_LOG_SYSLOG
if (init_parms->type != BCM_DEV_LOG_FILE_SYSLOG)
#endif
{
bcmos_printf("%s: log type %d is invalid\n", __FUNCTION__, init_parms->type);
return BCM_ERR_PARM;
}
log_parms.log_file[0].type = init_parms->type;
log_parms.log_file[0].flags |= BCM_DEV_LOG_FILE_FLAG_VALID;
queue_size = init_parms->queue_size ? init_parms->queue_size : BCM_DEV_LOG_DEFAULT_QUEUE_SIZE;
/* Only init a single log file */
rc = bcm_dev_log_init_default_logger_ext(&log_parms, 1, 0x4000, TASK_PRIORITY_DEV_LOG, queue_size);
BCMOS_TRACE_CHECK_RETURN(rc, rc, "bcm_dev_log_init_default_logger_ext()\n");
bcm_dev_log_level_set_style(DEV_LOG_LEVEL_WARNING, BCM_DEV_LOG_STYLE_BOLD);
if (init_parms->post_init_cb != NULL)
{
rc = init_parms->post_init_cb();
BCMOS_TRACE_CHECK_RETURN(rc, rc, "%s: post_init_cb()\n", __FUNCTION__);
}
BCM_LOG(INFO, def_log_id, "Logging started\n");
return BCM_ERR_OK;
}
log_name_table logs_names[DEV_LOG_MAX_IDS];
uint8_t log_name_table_index = 0;
static void dev_log_add_log_name_to_table(const char *name)
{
char _name[MAX_DEV_LOG_ID_NAME + 1] = {};
char *p = _name;
char *p_end;
int i = 0;
long val = -1;
strncpy(_name, name, MAX_DEV_LOG_ID_NAME);
while (*p)
{
/* While there are more characters to process... */
if (isdigit(*p))
{
/* Upon finding a digit, ... */
val = strtol(p, &p_end, 10); /* Read a number, ... */
if ((_name + strlen(_name)) != p_end)
{
DEV_LOG_ERROR_PRINTF("Error: dev_log_add_log_name_to_table %s)\n", name);
}
*p = '\0';
break;
}
else
{
/* Otherwise, move on to the next character. */
p++;
}
}
for (i = 0; i < log_name_table_index; i++)
{
if (strcmp(_name, logs_names[i].name) == 0)
{
if (val < logs_names[i].first_instance)
{
logs_names[i].first_instance = val;
}
if (val > logs_names[i].last_instance)
{
logs_names[i].last_instance = val;
}
break;
}
}
if ((i == log_name_table_index) && (i < DEV_LOG_MAX_IDS))
{
strncpy(logs_names[i].name, name, MAX_DEV_LOG_ID_NAME);
if (val == -1)
{
val = LOG_NAME_NO_INSTANCE;
}
logs_names[i].last_instance = val;
logs_names[i].first_instance = val;
log_name_table_index++;
}
}
void dev_log_get_log_name_table(char *buffer, uint32_t buf_len)
{
uint32_t i = 0;
uint32_t buf_len_free = buf_len;
buffer[0] = '\0';
for (i = 0; i < log_name_table_index; i++)
{
if (logs_names[i].first_instance == LOG_NAME_NO_INSTANCE)
{
snprintf(&buffer[strlen(buffer)], buf_len_free, "%s\n", logs_names[i].name);
}
else
{
snprintf(&buffer[strlen(buffer)], buf_len_free, "%s %d - %d\n", logs_names[i].name, logs_names[i].first_instance, logs_names[i].last_instance);
}
buffer[buf_len - 1] = '\0';
buf_len_free = buf_len - strlen(buffer);
if (buf_len_free <= 1)
{
DEV_LOG_ERROR_PRINTF("Error: dev_log_get_log_name_table too long\n");
break;
}
}
}
static dev_log_id _bcm_dev_log_id_get_by_name(const char *name)
{
uint32_t i;
for (i = 0; i < BCM_SIZEOFARRAY(dev_log.ids); i++)
{
if (!dev_log.ids[i].is_active)
continue;
if (!strcmp(dev_log.ids[i].name, name))
{
return (dev_log_id)&dev_log.ids[i];
}
}
return DEV_LOG_INVALID_ID;
}
static dev_log_id_parm *bcm_dev_log_get_free_id(void)
{
uint32_t i;
for (i = 0; i < BCM_SIZEOFARRAY(dev_log.ids); i++)
{
if (!dev_log.ids[i].is_active)
return &dev_log.ids[i];
}
return NULL;
}
dev_log_id bcm_dev_log_id_register(const char *name,
bcm_dev_log_level default_log_level,
bcm_dev_log_id_type default_log_type)
{
dev_log_id_parm *new_id;
/* Check that we have room for one more ID */
new_id = bcm_dev_log_get_free_id();
if (!new_id)
{
DEV_LOG_ERROR_PRINTF("Error: Failed to register log ID for '%s' - out of free log IDs\n", name);
return DEV_LOG_INVALID_ID;
}
/* Check that the log name isn't already registered */
if (!(dev_log.flags & BCM_DEV_LOG_FLAG_ALLOW_DUPLICATES) && _bcm_dev_log_id_get_by_name(name) != DEV_LOG_INVALID_ID)
{
DEV_LOG_ERROR_PRINTF("Error: duplicate log name \"%s\"\n", name);
return DEV_LOG_INVALID_ID;
}
/* Add prefix for kernel log_ids in order to avoid clash with similarly-names logs in the user space */
#ifdef __KERNEL__
strcpy(new_id->name, "k_");
#endif
/* Set log_id parameters */
strncat(new_id->name, name, sizeof(new_id->name) - strlen(new_id->name));
new_id->name[MAX_DEV_LOG_ID_NAME - 1] = '\0';
new_id->default_log_type = default_log_type;
new_id->default_log_level = default_log_level;
dev_log_add_log_name_to_table(new_id->name);
bcm_dev_log_id_set_levels_and_type_to_default((dev_log_id)new_id);
new_id->style = BCM_DEV_LOG_STYLE_NORMAL;
new_id->is_active = BCMOS_TRUE;
return (dev_log_id)new_id;
}
void bcm_dev_log_id_unregister(dev_log_id id)
{
dev_log_id_parm *parm = (dev_log_id_parm *)id;
parm->is_active = BCMOS_FALSE;
*parm->name = '\0';
}
bcmos_errno bcm_dev_log_id_set_type(dev_log_id id, bcm_dev_log_id_type log_type)
{
dev_log_id_parm *parm = (dev_log_id_parm *)id;
if (!id || (id == DEV_LOG_INVALID_ID))
{
DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id);
return BCM_ERR_PARM;
}
/* In linux kernel we only support save */
#ifdef __KERNEL__
if (log_type & DEV_LOG_ID_TYPE_BOTH)
log_type = DEV_LOG_ID_TYPE_SAVE;
#endif
DEV_LOG_INFO_PRINTF("ID: 0x%lx, New log type: %d\n", id, (int)log_type);
parm->log_type = log_type;
/* In linux user space we need to notify kernel integration code */
#if defined(LINUX_KERNEL_SPACE) && !defined(__KERNEL__)
if (using_inband_get())
{
bcm_dev_log_linux_id_set_type_ud(id, log_type);
}
else
{
bcm_dev_log_linux_id_set_type(id, log_type);
}
#endif
return BCM_ERR_OK;
}
bcmos_errno bcm_dev_log_id_set_level(dev_log_id id, bcm_dev_log_level log_level_print, bcm_dev_log_level log_level_save)
{
dev_log_id_parm *parm = (dev_log_id_parm *)id;
if (!id || (id == DEV_LOG_INVALID_ID))
{
DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id);
return BCM_ERR_PARM;
}
if ((log_level_print >= DEV_LOG_LEVEL_NUM_OF) || (log_level_save >= DEV_LOG_LEVEL_NUM_OF))
{
DEV_LOG_ERROR_PRINTF("Error: wrong parameters\n");
return BCM_ERR_PARM;
}
DEV_LOG_INFO_PRINTF("ID: 0x%p, New: log_level_print=%u, log_level_save=%u\n",
(void *)parm,
log_level_print,
log_level_save);
parm->log_level_print = log_level_print;
parm->log_level_save = log_level_save;
/* In linux user space we need to notify kernel integration code */
#if defined(LINUX_KERNEL_SPACE) && !defined(__KERNEL__)
if (using_inband_get())
{
bcm_dev_log_linux_id_set_level_ud(id, log_level_print, log_level_save);
}
else
{
bcm_dev_log_linux_id_set_level(id, log_level_print, log_level_save);
}
#endif
return BCM_ERR_OK;
}
bcmos_errno bcm_dev_log_id_set_levels_and_type_to_default(dev_log_id id)
{
dev_log_id_parm *parm = (dev_log_id_parm *)id;
if (!id || (id == DEV_LOG_INVALID_ID))
{
DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id);
return BCM_ERR_PARM;
}
parm->log_level_print = parm->default_log_level;
parm->log_level_save = parm->default_log_level;
parm->log_type = parm->default_log_type;
#ifdef TRIGGER_LOGGER_FEATURE
memset(&parm->throttle,0, sizeof(dev_log_id_throttle));
memset(&parm->trigger, 0, sizeof(dev_log_id_trigger));
parm->throttle_log_level = DEV_LOG_LEVEL_NO_LOG;
parm->trigger_log_level = DEV_LOG_LEVEL_NO_LOG;
#endif
/* In linux kernel space we don't support PRINT, only SAVE */
#ifdef __KERNEL__
if (parm->log_type & DEV_LOG_ID_TYPE_BOTH)
parm->log_type = DEV_LOG_ID_TYPE_SAVE;
#endif
return BCM_ERR_OK;
}
void bcm_dev_log_level_set_style(bcm_dev_log_level level, bcm_dev_log_style style)
{
dev_log_level2style[level] = style;
}
bcmos_errno bcm_dev_log_id_set_style(dev_log_id id, bcm_dev_log_style style)
{
dev_log_id_parm *parm = (dev_log_id_parm *)id;
if (!id || (id == DEV_LOG_INVALID_ID))
{
DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id);
return BCM_ERR_PARM;
}
parm->style = style;
return BCM_ERR_OK;
}
bcmos_errno bcm_dev_log_id_clear_counters(dev_log_id id)
{
dev_log_id_parm *parm = (dev_log_id_parm *)id;
if (!id || (id == DEV_LOG_INVALID_ID))
{
DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id);
return BCM_ERR_PARM;
}
memset(parm->counters, 0, sizeof(parm->counters));
parm->lost_msg_cnt = 0;
parm->print_skipped_count = 0;
return BCM_ERR_OK;
}
bcmos_errno bcm_dev_log_id_get(dev_log_id id, dev_log_id_parm *parm)
{
if (!id || (id == DEV_LOG_INVALID_ID))
{
DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id);
return BCM_ERR_PARM;
}
*parm = *(dev_log_id_parm *)id;
return BCM_ERR_OK;
}
bcmos_errno bcm_dev_log_id_get_level(dev_log_id id, bcm_dev_log_level *p_log_level_print,
bcm_dev_log_level *p_log_level_save)
{
dev_log_id_parm *parm = (dev_log_id_parm *)id;
if (!id || (id == DEV_LOG_INVALID_ID))
{
DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id);
return BCM_ERR_PARM;
}
if (p_log_level_print)
*p_log_level_print = parm->log_level_print;
if (p_log_level_save)
*p_log_level_save = parm->log_level_save;
return BCM_ERR_OK;
}
bcmos_errno bcm_dev_log_id_set(dev_log_id id, dev_log_id_parm *parm)
{
if (!id || (id == DEV_LOG_INVALID_ID))
{
DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id);
return BCM_ERR_PARM;
}
*(dev_log_id_parm *)id = *parm;
return BCM_ERR_OK;
}
dev_log_id bcm_dev_log_id_get_by_index(uint32_t index)
{
if (index >= BCM_SIZEOFARRAY(dev_log.ids) || !dev_log.ids[index].is_active)
return DEV_LOG_INVALID_ID;
return (dev_log_id)&dev_log.ids[index];
}
uint32_t bcm_dev_log_get_index_by_id(dev_log_id id)
{
uint32_t idx = (dev_log_id_parm *)id - &dev_log.ids[0];
if (idx >= BCM_SIZEOFARRAY(dev_log.ids))
idx = DEV_LOG_INVALID_INDEX;
/* Return idx even is "is_active" is false. This is because the callers rely on this. */
return idx;
}
dev_log_id bcm_dev_log_id_get_next(dev_log_id id)
{
if (id == DEV_LOG_INVALID_ID)
id = (dev_log_id)&dev_log.ids;
else
id = (dev_log_id)((dev_log_id_parm *)id + 1);
for (; bcm_dev_log_get_index_by_id(id) != DEV_LOG_INVALID_INDEX && !((dev_log_id_parm *)id)->is_active;
id = (dev_log_id)((dev_log_id_parm *)id + 1));
return bcm_dev_log_get_index_by_id(id) == DEV_LOG_INVALID_INDEX ? DEV_LOG_INVALID_ID : id;
}
dev_log_id bcm_dev_log_id_get_by_name(const char *name)
{
dev_log_id id;
if (name == NULL)
{
return DEV_LOG_INVALID_ID;
}
id = _bcm_dev_log_id_get_by_name(name);
if (id == DEV_LOG_INVALID_ID)
{
DEV_LOG_ERROR_PRINTF("Error: can't find name\n");
}
return id;
}
bcmos_bool bcm_dev_log_get_control(void)
{
return dev_log.state == BCM_DEV_LOG_STATE_ENABLED;
}
uint32_t bcm_dev_log_get_num_of_messages(const bcm_dev_log_file *file)
{
return file->u.mem_file.file_header.num_msgs;
}
void bcm_dev_log_set_control(bcmos_bool control)
{
if (control && dev_log.state == BCM_DEV_LOG_STATE_DISABLED)
dev_log.state = BCM_DEV_LOG_STATE_ENABLED;
else if (!control && dev_log.state == BCM_DEV_LOG_STATE_ENABLED)
dev_log.state = BCM_DEV_LOG_STATE_DISABLED;
}
bcm_dev_log_file_flags bcm_dev_log_get_file_flags(uint32_t file_id)
{
return dev_log.files[file_id].file_parm.flags;
}
void bcm_dev_log_set_file_flags(uint32_t file_id, bcm_dev_log_file_flags flags)
{
dev_log.files[file_id].file_parm.flags = flags;
}
bcm_dev_log_flags bcm_dev_log_get_flags(void)
{
return dev_log.flags;
}
void bcm_dev_log_set_flags(bcm_dev_log_flags flags)
{
dev_log.flags = flags;
}
void bcm_dev_log_set_print_cb(bcm_dev_log_print_cb cb)
{
dev_log.dev_log_parm.print_cb = cb;
}
void bcm_dev_log_set_get_time_cb(bcm_dev_log_get_time_cb cb)
{
dev_log.dev_log_parm.get_time_cb = cb;
}
void bcm_dev_log_set_time_to_str_cb(bcm_dev_log_time_to_str_cb cb)
{
dev_log.dev_log_parm.time_to_str_cb = cb;
}
#ifdef TRIGGER_LOGGER_FEATURE
/********************************************************************************************/
/* */
/* Name: bcm_dev_log_set_throttle */
/* */
/* Abstract: Set throttle level for the specific log is and its level */
/* */
/* Arguments: */
/* - id - The ID in the Dev log (what we got form bcm_dev_log_id_register) */
/* - log_level - log level */
/* - throttle - throttle number, 0 - no throttle */
/* */
/* Return Value: */
/* bcmos_errno - Success code (BCM_ERR_OK) or Error code (see bcmos_errno.h) */
/* */
/********************************************************************************************/
bcmos_errno bcm_dev_log_set_throttle(dev_log_id id, bcm_dev_log_level log_level, uint32_t throttle)
{
dev_log_id_parm *parm = (dev_log_id_parm *)id;
if (!id || (id == DEV_LOG_INVALID_ID))
{
DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id);
return BCM_ERR_PARM;
}
parm->throttle_log_level = log_level;
parm->throttle.threshold = throttle;
parm->throttle.counter = 0;
return BCM_ERR_OK;
}
/********************************************************************************************/
/* */
/* Name: bcm_dev_log_set_trigger */
/* */
/* Abstract: Set trigger counters for the specific log is and its level */
/* */
/* Arguments: */
/* - id - The ID in the Dev log (what we got form bcm_dev_log_id_register) */
/* - log_level - log level */
/* - start - start printing after this number, 0 - no trigger */
/* - stop - stop printing after this number, 0 - do not stop */
/* - repeat - start printing after this number, 0 - no repeat, -1 always */
/* */
/* Return Value: */
/* bcmos_errno - Success code (BCM_ERR_OK) or Error code (see bcmos_errno.h) */
/* */
/********************************************************************************************/
bcmos_errno bcm_dev_log_set_trigger(dev_log_id id, bcm_dev_log_level log_level, uint32_t start, uint32_t stop, int32_t repeat)
{
dev_log_id_parm *parm = (dev_log_id_parm *)id;
if (!id || (id == DEV_LOG_INVALID_ID))
{
DEV_LOG_ERROR_PRINTF("Error: id not valid (0x%x)\n", (unsigned int)id);
return BCM_ERR_PARM;
}
parm->trigger_log_level = log_level;
parm->trigger.start_threshold = start;
parm->trigger.stop_threshold = stop;
parm->trigger.repeat_threshold = repeat;
parm->trigger.counter = 0;
parm->trigger.repeat = 0;
return BCM_ERR_OK;
}
#endif /* TRIGGER_LOGGER_FEATURE */
/* Get file info: max data size, used bytes */
bcmos_errno bcm_dev_log_get_file_info(bcm_dev_log_file *file, uint32_t *file_size, uint32_t *used_bytes)
{
if (!file || !file_size || !used_bytes)
return BCM_ERR_PARM;
/* Only supported for memory files */
if (!bcm_dev_log_is_memory_file(file))
return BCM_ERR_NOT_SUPPORTED;
*file_size = file->u.mem_file.file_header.data_size;
*used_bytes = (file->u.mem_file.file_header.file_wrap_cnt || file->is_full) ?
file->u.mem_file.file_header.data_size : file->u.mem_file.file_header.write_offset;
return BCM_ERR_OK;
}
/* Register indication to be sent when file utilization crosses threshold */
bcmos_errno bcm_dev_log_almost_full_ind_register(bcm_dev_log_file *file, uint32_t used_bytes_threshold,
F_dev_log_file_almost_full send_ind_cb, long ind_cb_priv)
{
if (!file || (used_bytes_threshold && !send_ind_cb))
return BCM_ERR_PARM;
/* Only supported for memory files */
if (!bcm_dev_log_is_memory_file(file))
return BCM_ERR_NOT_SUPPORTED;
bcmos_mutex_lock(&file->u.mem_file.mutex);
file->almost_full.threshold = used_bytes_threshold;
file->almost_full.send_ind_cb = send_ind_cb;
file->almost_full.priv = ind_cb_priv;
file->almost_full.ind_sent = BCMOS_FALSE;
bcmos_mutex_unlock(&file->u.mem_file.mutex);
return BCM_ERR_OK;
}
#endif /* ENABLE_LOG */
<file_sep># libgpg-error
#
include(third_party)
bcm_3rdparty_module_name(libgpg-error "1.41")
bcm_3rdparty_download_wget("https://gnupg.org/ftp/gcrypt/libgpg-error" "libgpg-error-${LIBGPG-ERROR_VERSION}.tar.bz2")
bcm_3rdparty_build_automake()
bcm_3rdparty_export()
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#ifndef _BCMOLT_MATH_H_
#define _BCMOLT_MATH_H_
/* Works for both float and double. */
#define ROUND_FLOAT(size_in_bytes) ((typeof(size_in_bytes))((size_in_bytes) + 0.5))
/* Works for integers. */
#define CEIL_INT(size_in_bytes) (((size_in_bytes) - (typeof(size_in_bytes))(size_in_bytes)) > 0 ? ((typeof(size_in_bytes))(size_in_bytes) + 1) : (typeof(size_in_bytes))(size_in_bytes))
#define SQUARE(x) ((x) * (x))
#define PERCENT(percent, x) (((float)(percent) * (x)) / 100)
/*
* Unit Conversion
*/
#define BITS_TO_BYTES(bits) ((bits) >> 3)
#define BYTES_TO_BITS(bytes) ((bytes) << 3)
/* Quantization */
/*
* VAL_TO_BIN classifies the value of val to the proper bin
* val - a value in the range [0, maxval]
* bin - a value in the range [0, bins-1] (result of macro)
*/
#define VAL_TO_BIN(val, maxval, bins) ((val) < (maxval) ? ((val) * (bins)) / (maxval) : (bins) - 1)
/* If a value is in a certain bin, it is in the range [min_bin_val, max_bin_val]
* min_bin_val - minimum value that belongs to bin
* max_bin_val - maximum value that belongs to bin
*/
#define BIN_TO_MIN_BIN_VAL(bin, maxval, bins) ((bin) * ((double)(maxval) / (bins)))
#define BIN_TO_MAX_BIN_VAL(bin, maxval, bins) (((bin) + 1) * ((double)(maxval) / (bins)))
#define GET_MASK(width) ((1 << (width)) - 1)
#ifndef MAX
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#endif
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
#ifndef MAX3
#define MAX3(a, b, c) MAX(MAX(a, b), c)
#endif
#ifndef MIN3
#define MIN3(a, b, c) MIN(MIN(a, b), c)
#endif
#define CEILING(a, b) (((a) + ((b) - 1)) / (b))
/* Divide a by b (a/b) and round (up or down) to the nearest integer */
#define DIV_ROUND(a, b) (((a) + ((b) / 2)) / (b))
#define TWO_TO_POWER_OF(x) (1 << (x))
#endif /* _BCMOLT_MATH_H_ */
<file_sep>#!/bin/sh
#
# BBF check script (loosely) based on the IETF one.
ietf_dir="standard/ietf"
bbf_dir="standard/bbf"
cwd=`pwd`
cd $bbf_dir
to_check=`find standard draft -mindepth 1 -maxdepth 1 -type d`
cd $cwd
pyang_flags="--strict --max-line-length=70 --lint --lint-modulename-prefix=bbf --lint-namespace-prefix=urn:bbf:yang: --verbose --path=$cwd/$ietf_dir --path=$cwd/$bbf_dir"
checkDir () {
local dir="$bbf_dir/$1"
echo Checking yang files in $dir
exit_status=""
printf "\n"
for f in `find $dir -name '*.yang'`; do
errors=`pyang $pyang_flags $f 2>&1 | grep "error:"`
if [ ! -z "$errors" ]; then
echo Errors in $f
printf "\n $errors \n"
exit_status="failed!"
fi
done
if [ ! -z "$exit_status" ]; then
exit 1
fi
}
echo Checking modules with pyang command:
printf "\n pyang $pyang_flags MODULE\n\n"
for d in $to_check; do
checkDir $d
done
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#include <bcmos_system.h>
#include <bcm_dev_log.h>
#include <bcm_dev_log_task_internal.h>
#include <bcmcli.h>
#include <bcm_dev_log_cli.h>
/* We don't support dev_log CLI in linux kernel space */
#ifndef __KERNEL__
/* Dev log CLI session supports receiving long lines - we shall simply split them into shorter log messages. */
#define DEV_LOG_CLI_SESSION_MAX_MSG_SIZE (MAX_DEV_LOG_STRING_NET_SIZE * 10)
enum
{
ID_BY_INDEX,
ID_BY_NAME,
};
static bcmos_errno bcm_dev_log_file_print(uint32_t file_index, int32_t msgs_num, bcm_dev_log_print_cb print_callback, void *arg, bcmos_bool clear)
{
bcm_dev_log_file *file;
char log_string[MAX_DEV_LOG_STRING_SIZE];
int length;
uint32_t num_msgs;
uint32_t i;
uint32_t offset = 0;
bcmos_errno err = BCM_ERR_OK;
file = bcm_dev_log_file_get(file_index);
if (!file)
return BCM_ERR_PARM;
num_msgs = bcm_dev_log_get_num_of_messages(file);
if (msgs_num && msgs_num < num_msgs)
num_msgs = msgs_num;
DEV_LOG_INFO_PRINTF("file=%p, print %d msgs from file (orig: %d)\n", (void *)file, (int)num_msgs, (int)msgs_num);
/* Print file */
for (i = 0; (i < msgs_num) || !msgs_num; i++)
{
/* Read from file */
length = bcm_dev_log_file_read(file, &offset, log_string, sizeof(log_string));
if (!length)
break;
print_callback(arg, log_string);
}
if (clear == BCMOS_TRUE)
err = bcm_dev_log_file_clear(file);
return err;
}
static const char *dev_log_str_style(bcm_dev_log_style style)
{
static const char *strings[] =
{
[BCM_DEV_LOG_STYLE_NORMAL] = "NORMAL",
[BCM_DEV_LOG_STYLE_BOLD] = "BOLD",
[BCM_DEV_LOG_STYLE_UNDERLINE] = "UNDERLINE",
[BCM_DEV_LOG_STYLE_BLINK] = "BLINK",
[BCM_DEV_LOG_STYLE_REVERSE_VIDEO] = "REVERSE_VIDEO",
};
return strings[style > BCM_DEV_LOG_STYLE_REVERSE_VIDEO ? BCM_DEV_LOG_STYLE_REVERSE_VIDEO : style];
}
#ifdef TRIGGER_LOGGER_FEATURE
static void bcm_dev_log_cli_session_print_features(bcmcli_session *session, const char *tabs, const dev_log_id_parm *id_parm)
{
bcmcli_session_print(session,
"%sthrottle : level = %c, threshold = %-5u\n",
tabs,
log_level_str[id_parm->throttle_log_level],
id_parm->throttle.threshold);
bcmcli_session_print(session,
"%strigger : level = %c, start = %-5u, stop = %-5u, repeat = %-5u\n",
tabs,
log_level_str[id_parm->trigger_log_level],
id_parm->trigger.start_threshold,
id_parm->trigger.stop_threshold,
id_parm->trigger.repeat_threshold);
}
#endif
static void bcm_dev_log_cli_session_print_id_parm(bcmcli_session *session, const char *tabs, const dev_log_id_parm *id_parm)
{
bcmcli_session_print(session,
"name=%16s, log_type=%u, default_log_type=%u, log_level_print=%c (%u), log_level_save=%c (%u), default_log_level=%c (%u), style=%s (%u), lost_msg_cnt=%u, print_skipped_count=%u\n",
id_parm->name,
id_parm->log_type,
id_parm->default_log_type,
log_level_str[id_parm->log_level_print],
id_parm->log_level_print,
log_level_str[id_parm->log_level_save],
id_parm->log_level_save,
log_level_str[id_parm->default_log_level],
id_parm->default_log_level,
dev_log_str_style(id_parm->style),
id_parm->style,
id_parm->lost_msg_cnt,
id_parm->print_skipped_count);
bcmcli_session_print(session,
"%scounters = {%c %-5u,%c %-5u,%c %-5u,%c %-5u,%c %-5u,%c %-5u}\n",
tabs,
log_level_str[DEV_LOG_LEVEL_NO_LOG],
id_parm->counters[DEV_LOG_LEVEL_NO_LOG],
log_level_str[DEV_LOG_LEVEL_FATAL],
id_parm->counters[DEV_LOG_LEVEL_FATAL],
log_level_str[DEV_LOG_LEVEL_ERROR],
id_parm->counters[DEV_LOG_LEVEL_ERROR],
log_level_str[DEV_LOG_LEVEL_WARNING],
id_parm->counters[DEV_LOG_LEVEL_WARNING],
log_level_str[DEV_LOG_LEVEL_INFO],
id_parm->counters[DEV_LOG_LEVEL_INFO],
log_level_str[DEV_LOG_LEVEL_DEBUG],
id_parm->counters[DEV_LOG_LEVEL_DEBUG]);
#ifdef TRIGGER_LOGGER_FEATURE
bcm_dev_log_cli_session_print_features(session, tabs, id_parm);
#endif
}
static bcmos_errno bcm_dev_log_cli_print_dev_log(
bcmcli_session *session,
const bcmcli_cmd_parm parm[],
uint16_t n_parms)
{
uint32_t i;
bcm_dev_log_file *file;
dev_log_id log_id = DEV_LOG_INVALID_ID;
for (i = 0; i < DEV_LOG_MAX_FILES; i++)
{
file = bcm_dev_log_file_get(i);
if (!file)
continue;
bcmcli_session_print(session, BCM_TAB "file[%u]:\n", i);
bcmcli_session_print(session, BCM_TAB2 "max_msgs = %u\n", bcm_dev_log_get_num_of_messages(file));
bcmcli_session_print(session, BCM_TAB2 "file_parm:\n");
bcmcli_session_print(session, BCM_TAB3 "start_addr = %p\n", dev_log.files[i].file_parm.start_addr);
bcmcli_session_print(session, BCM_TAB3 "size = %u\n", dev_log.files[i].file_parm.size);
bcmcli_session_print(session, BCM_TAB3 "read_cb = %p\n", (void *)dev_log.files[i].file_parm.read_cb);
bcmcli_session_print(session, BCM_TAB3 "write_cb = %p\n", (void *)dev_log.files[i].file_parm.write_cb);
bcmcli_session_print(session, BCM_TAB3 "flags = %x\n", dev_log.files[i].file_parm.flags);
}
bcmcli_session_print(session, BCM_TAB "state = %u\n", dev_log.state);
bcmcli_session_print(session, BCM_TAB "msg_count = %u\n", dev_log.msg_count);
bcmcli_session_print(session, BCM_TAB "save_queue:\n");
bcmcli_session_print(session, BCM_TAB2 "is_waiting = %u\n", dev_log.save_queue.is_waiting);
bcmcli_session_print(session, BCM_TAB "print_queue:\n");
bcmcli_session_print(session, BCM_TAB2 "is_waiting = %u\n", dev_log.print_queue.is_waiting);
bcmcli_session_print(session, BCM_TAB "save_task:\n");
bcmcli_session_print(session, BCM_TAB2 "active_modules = %u\n", dev_log.save_task.active_modules);
bcmcli_session_print(session, BCM_TAB2 "current_module = %u\n", dev_log.save_task.current_module);
bcmcli_session_print(session, BCM_TAB "print_task:\n");
bcmcli_session_print(session, BCM_TAB2 "active_modules = %u\n", dev_log.print_task.active_modules);
bcmcli_session_print(session, BCM_TAB2 "current_module = %u\n", dev_log.print_task.current_module);
bcmcli_session_print(session, BCM_TAB "ids[]:\n");
while ((log_id = bcm_dev_log_id_get_next(log_id)) != DEV_LOG_INVALID_ID)
{
bcmcli_session_print(session, BCM_TAB2 "ids[%2u]: ", bcm_dev_log_get_index_by_id(log_id));
bcm_dev_log_cli_session_print_id_parm(session, BCM_TAB3, (dev_log_id_parm *)log_id);
}
for (i = 0; i < log_name_table_index; i++)
{
if (logs_names[i].first_instance == LOG_NAME_NO_INSTANCE)
{
bcmcli_session_print(session, BCM_TAB2 "%s\n", logs_names[i].name);
}
else
{
bcmcli_session_print(session, BCM_TAB2 "%s %d - %d\n", logs_names[i].name, logs_names[i].first_instance, logs_names[i].last_instance);
}
}
return BCM_ERR_OK;
}
static bcmos_errno bcm_dev_log_cli_logger_control(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
bcm_dev_log_set_control(parm[0].value.unumber != 0);
return BCM_ERR_OK;
}
static bcmos_errno bcm_dev_log_cli_file_print(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
return bcm_dev_log_file_print(
parm[0].value.unumber,
0,
(bcm_dev_log_print_cb)bcmcli_session_print,
session,
(bcmos_bool)parm[1].value.unumber);
}
static bcmos_errno bcm_dev_log_cli_file_clear(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
bcm_dev_log_file *file = bcm_dev_log_file_get(parm[0].value.unumber);
if (!file)
return BCM_ERR_PARM;
return bcm_dev_log_file_clear(file);
}
static bcmos_errno bcm_dev_log_cli_file_set_flags(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
dev_log.files[parm[0].value.unumber].file_parm.flags |= (bcm_dev_log_file_flags)parm[1].value.unumber;
return BCM_ERR_OK;
}
static bcmos_errno bcm_dev_log_cli_file_reset_flags(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
dev_log.files[parm[0].value.unumber].file_parm.flags = BCM_DEV_LOG_FILE_FLAG_NONE;
return BCM_ERR_OK;
}
static bcmos_errno bcm_dev_log_cli_id_get(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
dev_log_id id;
dev_log_id_parm id_parm;
bcmos_errno err;
id = parm[0].value.unumber == ID_BY_INDEX ? bcm_dev_log_id_get_by_index(parm[1].value.unumber) :
bcm_dev_log_id_get_by_name(parm[1].value.string);
if (id == DEV_LOG_INVALID_ID)
return BCM_ERR_NOENT;
err = bcm_dev_log_id_get(id, &id_parm);
if (err)
{
bcmcli_session_print(session, "Error: can get id (err: %d)\n", err);
return err;
}
bcm_dev_log_cli_session_print_id_parm(session, BCM_TAB, &id_parm);
return BCM_ERR_OK;
}
static bcmos_errno bcm_dev_log_cli_id_set_type(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
dev_log_id id;
id = bcm_dev_log_id_get_by_index(parm[0].value.unumber);
if (id == DEV_LOG_INVALID_ID)
return BCM_ERR_NOENT;
return bcm_dev_log_id_set_type(id, (bcm_dev_log_id_type)parm[1].value.unumber);
}
static bcmos_errno bcm_dev_log_cli_id_set_level(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
dev_log_id id;
id = bcm_dev_log_id_get_by_index(parm[0].value.unumber);
if (id == DEV_LOG_INVALID_ID)
return BCM_ERR_NOENT;
return bcm_dev_log_id_set_level(
id,
(bcm_dev_log_level)parm[1].value.unumber,
(bcm_dev_log_level)parm[2].value.unumber);
}
static bcmos_errno bcm_dev_log_cli_name_set_level(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
dev_log_id id;
id = bcm_dev_log_id_get_by_name(parm[0].value.string);
if (id == DEV_LOG_INVALID_ID)
{
return BCM_ERR_NOENT;
}
return bcm_dev_log_id_set_level(
id,
(bcm_dev_log_level)parm[1].value.unumber,
(bcm_dev_log_level)parm[2].value.unumber);
}
static bcmos_errno bcm_dev_log_cli_id_set_to_default(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
dev_log_id id;
id = bcm_dev_log_id_get_by_index(parm[0].value.unumber);
if (id == DEV_LOG_INVALID_ID)
return BCM_ERR_NOENT;
return bcm_dev_log_id_set_levels_and_type_to_default(id);
}
static bcmos_errno bcm_dev_log_cli_id_set_style(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
dev_log_id id;
bcm_dev_log_style style;
id = bcm_dev_log_id_get_by_index(bcmcli_find_named_parm(session, "index")->value.unumber);
if (id == DEV_LOG_INVALID_ID)
return BCM_ERR_NOENT;
style = (bcm_dev_log_style)bcmcli_find_named_parm(session, "style")->value.unumber;
return bcm_dev_log_id_set_style(id, style);
}
static bcmos_errno bcm_dev_log_cli_id_clear_counters(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
dev_log_id id;
id = bcm_dev_log_id_get_by_index(parm[0].value.unumber);
if (id == DEV_LOG_INVALID_ID)
return BCM_ERR_NOENT;
return bcm_dev_log_id_clear_counters(id);
}
static bcmos_errno bcm_dev_log_cli_log(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
dev_log_id id;
bcm_dev_log_level log_level;
uint32_t count = 1;
const char *string;
bcmcli_cmd_parm *cmd_parm;
id = bcm_dev_log_id_get_by_index(parm[0].value.unumber);
if (id == DEV_LOG_INVALID_ID)
return BCM_ERR_NOENT;
if ((cmd_parm = bcmcli_find_named_parm(session, "count")))
{
count = cmd_parm->value.unumber;
if (!count)
{
count = 1;
}
}
log_level = (bcm_dev_log_level)parm[1].value.unumber;
string = parm[2].value.string;
while (count--)
{
bcm_dev_log_log(id, log_level, BCM_LOG_FLAG_NONE, "%5u| Message: %s\n", count, string);
}
return BCM_ERR_OK;
}
typedef enum
{
DEV_LOG_ID_SET_ALL_NONE,
DEV_LOG_ID_SET_ALL_DEFAULT
} bcm_dev_log_id_set_all;
static bcmos_errno bcm_dev_log_cli_set_levels_and_type_all(
bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
bcm_dev_log_id_set_all set_all = (bcm_dev_log_id_set_all)bcmcli_find_named_parm(session, "set_all")->value.unumber;
dev_log_id log_id = DEV_LOG_INVALID_ID;
bcmos_errno err;
while ((log_id = bcm_dev_log_id_get_next(log_id)) != DEV_LOG_INVALID_ID)
{
if (set_all == DEV_LOG_ID_SET_ALL_NONE)
{
err = bcm_dev_log_id_set_type(log_id, DEV_LOG_ID_TYPE_NONE);
if (err == BCM_ERR_OK)
err = bcm_dev_log_id_set_level(log_id, DEV_LOG_LEVEL_NO_LOG, DEV_LOG_LEVEL_NO_LOG);
}
else
err = bcm_dev_log_id_set_levels_and_type_to_default(log_id);
if (err != BCM_ERR_OK)
{
bcmcli_session_print(session, "Error setting log type/level: %s for index=%u\n", bcmos_strerror(err), bcm_dev_log_get_index_by_id(log_id));
return err;
}
}
return BCM_ERR_OK;
}
static bcmos_errno bcm_dev_log_cli_instance_enable(
bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
bcmos_bool enable = (bcmos_bool)bcmcli_find_named_parm(session, "enable")->value.unumber;
uint32_t inst = bcmcli_find_named_parm(session, "instance")->value.unumber;
static char log_name[(MAX_DEV_LOG_ID_NAME + 1)] = {};
dev_log_id log_id;
bcmos_errno err;
uint32_t i;
char inst_str[10] = {}; /* uint32 can have up to 9 chars + 1 for NULL */
snprintf(inst_str, sizeof(inst_str), "%u", inst);
for (i = 0; i < log_name_table_index; i++)
{
if (logs_names[i].first_instance != LOG_NAME_NO_INSTANCE &&
inst >= logs_names[i].first_instance &&
inst <= logs_names[i].last_instance)
{
if ((strlen(logs_names[i].name) + strlen(inst_str)) > MAX_DEV_LOG_ID_NAME)
{
bcmcli_session_print(session, "Error: log name is too long %s%s\n", logs_names[i].name, inst_str);
return BCM_ERR_INTERNAL;
}
strncpy(log_name, logs_names[i].name, MAX_DEV_LOG_ID_NAME);
strncat(log_name, inst_str, MAX_DEV_LOG_ID_NAME - strlen(log_name));
log_id = bcm_dev_log_id_get_by_name(log_name);
if (log_id == DEV_LOG_INVALID_ID)
{
bcmcli_session_print(session, "Error: log ID not found: %s\n", log_name);
return BCM_ERR_INTERNAL;
}
err = bcm_dev_log_id_set_type(log_id, enable ? DEV_LOG_ID_TYPE_BOTH : DEV_LOG_ID_TYPE_NONE);
if (err != BCM_ERR_OK)
{
bcmcli_session_print(session, "Error setting log type: %s\n", bcmos_strerror(err));
return err;
}
bcmcli_session_print(session, "Log '%s' %s\n", log_name, enable ? "enabled" : "disabled");
}
}
return BCM_ERR_OK;
}
#ifdef TRIGGER_LOGGER_FEATURE
static bcmos_errno bcm_dev_log_cli_throttle(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
dev_log_id id;
id = bcm_dev_log_id_get_by_index(parm[0].value.unumber);
if (id == DEV_LOG_INVALID_ID)
return BCM_ERR_NOENT;
return bcm_dev_log_set_throttle(id, parm[1].value.unumber, parm[2].value.unumber);
}
static bcmos_errno bcm_dev_log_cli_trigger(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
dev_log_id id;
int32_t repeat = 0;
bcmcli_cmd_parm *cmd_parm;
id = bcm_dev_log_id_get_by_index(parm[0].value.unumber);
if (id == DEV_LOG_INVALID_ID)
return BCM_ERR_NOENT;
if ((cmd_parm = bcmcli_find_named_parm(session, "repeat")))
repeat = cmd_parm->value.number;
return bcm_dev_log_set_trigger(id, parm[1].value.unumber, parm[2].value.unumber, parm[3].value.unumber, repeat);
}
static bcmos_errno bcm_dev_log_cli_get_features(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
dev_log_id id;
dev_log_id_parm id_parm;
bcmos_errno err;
id = bcm_dev_log_id_get_by_index(parm[0].value.unumber);
if (id == DEV_LOG_INVALID_ID)
return BCM_ERR_NOENT;
err = bcm_dev_log_id_get(id, &id_parm);
if (err)
{
bcmcli_session_print(session, "Error: can get id (err: %d)\n", err);
return err;
}
bcm_dev_log_cli_session_print_features(session, BCM_TAB, &id_parm);
return BCM_ERR_OK;
}
#endif
static int dev_log_cli_session_write_cb(bcmcli_session *cli_session, const char *buf, uint32_t size)
{
bcm_dev_log_cli_session *session = bcmcli_session_user_priv(cli_session);
char tmp_str[DEV_LOG_CLI_SESSION_MAX_MSG_SIZE] = {};
char *p;
uint32_t tmp_str_len;
strncpy(tmp_str, buf, sizeof(tmp_str) - 1); /* leave room for the terminator */
p = tmp_str;
tmp_str_len = strlen(tmp_str);
while (tmp_str_len > session->free_len)
{
/* Not enough space in 'str' for concatenating what's in 'p' -> split it. */
strncat(session->str, p, session->free_len);
bcm_dev_log_log(
session->log_id, session->log_level, BCM_LOG_FLAG_NO_HEADER | BCM_LOG_FLAG_CALLER_FMT, "%s", session->str);
*session->str = '\0';
p += session->free_len;
tmp_str_len -= session->free_len;
session->free_len = MAX_DEV_LOG_STRING_NET_SIZE - 1;
}
/* Enough space in 'str' for concatenating what's in 'p'. */
strncat(session->str, p, tmp_str_len);
session->free_len -= tmp_str_len;
/* If the message is not terminated by '\n', do not submit the message to logger yet
* (rather save it, waiting for a later message with '\n'). */
if (session->str[strlen(session->str) - 1] == '\n')
{
bcm_dev_log_log(
session->log_id, session->log_level, BCM_LOG_FLAG_NO_HEADER | BCM_LOG_FLAG_CALLER_FMT, "%s", session->str);
*session->str = '\0';
session->free_len = MAX_DEV_LOG_STRING_NET_SIZE - 1;
}
return size;
}
bcmos_errno bcm_dev_log_cli_session_create(
dev_log_id log_id,
bcm_dev_log_level log_level,
bcm_dev_log_cli_session **session)
{
bcmos_errno err;
bcmcli_session_parm session_params = { .write = dev_log_cli_session_write_cb };
*session = bcmos_calloc(sizeof(bcm_dev_log_cli_session));
if (*session == NULL)
{
return BCM_ERR_NOMEM;
}
session_params.user_priv = *session;
err = bcmcli_session_open(&session_params, &((*session)->session));
if (err != BCM_ERR_OK)
{
bcmos_free(*session);
*session = NULL;
return err;
}
(*session)->log_id = log_id;
(*session)->log_level = log_level;
(*session)->free_len = MAX_DEV_LOG_STRING_NET_SIZE - 1;
return BCM_ERR_OK;
}
bcmcli_entry *bcm_dev_log_cli_init(bcmcli_entry *root_dir)
{
bcmcli_entry *dir;
static bcmcli_enum_val enum_table_log_level[] =
{
{ .name = "NO_LOG", .val = (long)DEV_LOG_LEVEL_NO_LOG },
{ .name = "FATAL", .val = (long)DEV_LOG_LEVEL_FATAL },
{ .name = "ERROR", .val = (long)DEV_LOG_LEVEL_ERROR },
{ .name = "WARNING", .val = (long)DEV_LOG_LEVEL_WARNING},
{ .name = "INFO", .val = (long)DEV_LOG_LEVEL_INFO },
{ .name = "DEBUG", .val = (long)DEV_LOG_LEVEL_DEBUG },
BCMCLI_ENUM_LAST
};
dir = bcmcli_dir_add(root_dir, "logger", "Dev Log", BCMCLI_ACCESS_GUEST, NULL);
BUG_ON(dir == NULL);
{
BCMCLI_MAKE_CMD_NOPARM(dir, "print_dev_log", "Print Dev log", bcm_dev_log_cli_print_dev_log);
}
{
BCMCLI_MAKE_CMD(dir, "logger_control", "Logger Control", bcm_dev_log_cli_logger_control,
BCMCLI_MAKE_PARM_RANGE("enable", "enable", BCMCLI_PARM_UDECIMAL, 0, 0, 1));
}
{
BCMCLI_MAKE_CMD(dir, "file_print", "Print logger file", bcm_dev_log_cli_file_print,
BCMCLI_MAKE_PARM("index", "index", BCMCLI_PARM_UDECIMAL, 0),
BCMCLI_MAKE_PARM_RANGE("clear", "clear", BCMCLI_PARM_UDECIMAL, 0, 0, 1));
}
{
BCMCLI_MAKE_CMD(dir, "file_clear", "Clear file", bcm_dev_log_cli_file_clear,
BCMCLI_MAKE_PARM("index", "index", BCMCLI_PARM_UDECIMAL, 0));
}
{
static bcmcli_enum_val enum_table_file_flags[] =
{
{ .name = "VALID", .val = (long)BCM_DEV_LOG_FILE_FLAG_VALID },
{ .name = "WRAP_AROUND", .val = (long)BCM_DEV_LOG_FILE_FLAG_WRAP_AROUND },
{ .name = "STOP_WHEN_FULL", .val = (long)BCM_DEV_LOG_FILE_FLAG_STOP_WHEN_FULL },
BCMCLI_ENUM_LAST
};
BCMCLI_MAKE_CMD(dir, "file_set_flags", "Set file flags", bcm_dev_log_cli_file_set_flags,
BCMCLI_MAKE_PARM_RANGE("index", "index", BCMCLI_PARM_UDECIMAL, 0, 0, DEV_LOG_MAX_FILES-1),
BCMCLI_MAKE_PARM_ENUM("flags", "flags", enum_table_file_flags, 0));
}
{
BCMCLI_MAKE_CMD(dir, "file_reset_flags", "Reset file flags", bcm_dev_log_cli_file_reset_flags,
BCMCLI_MAKE_PARM_RANGE("index", "index", BCMCLI_PARM_UDECIMAL, 0, 0, DEV_LOG_MAX_FILES-1));
}
{
static bcmcli_cmd_parm set1[]=
{
BCMCLI_MAKE_PARM("index", "index", BCMCLI_PARM_UDECIMAL, 0),
BCMCLI_PARM_LIST_TERMINATOR
};
static bcmcli_cmd_parm set2[] =
{
BCMCLI_MAKE_PARM("name", "name", BCMCLI_PARM_STRING, 0),
BCMCLI_PARM_LIST_TERMINATOR
};
static bcmcli_enum_val selector_table[] =
{
{ .name = "by_index", .val = ID_BY_INDEX, .parms = set1 },
{ .name = "by_name", .val = ID_BY_NAME, .parms = set2 },
BCMCLI_ENUM_LAST
};
BCMCLI_MAKE_CMD(dir, "id_get", "id_get", bcm_dev_log_cli_id_get,
BCMCLI_MAKE_PARM_SELECTOR("by", "by", selector_table, 0));
}
{
static bcmcli_enum_val enum_table_log_type[] =
{
{ .name = "none", .val = (long)DEV_LOG_ID_TYPE_NONE },
{ .name = "print", .val = (long)DEV_LOG_ID_TYPE_PRINT },
{ .name = "save", .val = (long)DEV_LOG_ID_TYPE_SAVE },
{ .name = "both", .val = (long)DEV_LOG_ID_TYPE_BOTH },
BCMCLI_ENUM_LAST
};
BCMCLI_MAKE_CMD(dir, "id_set_type", "id_set_type", bcm_dev_log_cli_id_set_type,
BCMCLI_MAKE_PARM("index", "index", BCMCLI_PARM_UDECIMAL, 0),
BCMCLI_MAKE_PARM_ENUM("log_type", "log_type", enum_table_log_type, 0));
}
{
BCMCLI_MAKE_CMD(dir, "id_set_level", "id_set_level", bcm_dev_log_cli_id_set_level,
BCMCLI_MAKE_PARM("index", "index", BCMCLI_PARM_UDECIMAL, 0),
BCMCLI_MAKE_PARM_ENUM("log_level_print", "log_level", enum_table_log_level, 0),
BCMCLI_MAKE_PARM_ENUM("log_level_save", "log_level", enum_table_log_level, 0));
}
{
BCMCLI_MAKE_CMD(dir, "name_set_level", "name_set_level", bcm_dev_log_cli_name_set_level,
BCMCLI_MAKE_PARM("name", "name", BCMCLI_PARM_STRING, 0),
BCMCLI_MAKE_PARM_ENUM("log_level_print", "log_level", enum_table_log_level, 0),
BCMCLI_MAKE_PARM_ENUM("log_level_save", "log_level", enum_table_log_level, 0));
}
{
BCMCLI_MAKE_CMD(dir, "id_set_to_default", "id_set_to_default", bcm_dev_log_cli_id_set_to_default,
BCMCLI_MAKE_PARM("index", "index", BCMCLI_PARM_UDECIMAL, 0));
}
{
static bcmcli_enum_val enum_table_log_style[] =
{
{ .name = "normal", .val = (long)BCM_DEV_LOG_STYLE_NORMAL },
{ .name = "bold", .val = (long)BCM_DEV_LOG_STYLE_BOLD },
{ .name = "underline", .val = (long)BCM_DEV_LOG_STYLE_UNDERLINE },
{ .name = "blink", .val = (long)BCM_DEV_LOG_STYLE_BLINK },
{ .name = "reverse_video", .val = (long)BCM_DEV_LOG_STYLE_REVERSE_VIDEO },
BCMCLI_ENUM_LAST
};
BCMCLI_MAKE_CMD(dir, "id_set_style", "id_set_style", bcm_dev_log_cli_id_set_style,
BCMCLI_MAKE_PARM("index", "index", BCMCLI_PARM_UDECIMAL, 0),
BCMCLI_MAKE_PARM_ENUM("style", "style", enum_table_log_style, 0));
}
{
BCMCLI_MAKE_CMD(dir, "id_clear_counters", "id_clear_counters", bcm_dev_log_cli_id_clear_counters,
BCMCLI_MAKE_PARM("index", "index", BCMCLI_PARM_UDECIMAL, 0));
}
{
BCMCLI_MAKE_CMD(dir, "log", "log", bcm_dev_log_cli_log,
BCMCLI_MAKE_PARM("index", "index", BCMCLI_PARM_UDECIMAL, 0),
BCMCLI_MAKE_PARM_ENUM("log_level_print", "log_level", enum_table_log_level, 0),
BCMCLI_MAKE_PARM("string", "string", BCMCLI_PARM_STRING, 0),
BCMCLI_MAKE_PARM("count", "Number of messages to send", BCMCLI_PARM_UDECIMAL, BCMCLI_PARM_FLAG_OPTIONAL));
}
{
BCMCLI_MAKE_CMD(dir, "instance_enable", "enable/disable instance number", bcm_dev_log_cli_instance_enable,
BCMCLI_MAKE_PARM_ENUM("enable", "enable", bcmcli_enum_bool_table, 0),
BCMCLI_MAKE_PARM("instance", "instance number", BCMCLI_PARM_UDECIMAL, 0));
}
#ifdef TRIGGER_LOGGER_FEATURE
{
BCMCLI_MAKE_CMD(dir, "id_set_throttle", "set throttle", bcm_dev_log_cli_throttle,
BCMCLI_MAKE_PARM("index", "index", BCMCLI_PARM_UDECIMAL, 0),
BCMCLI_MAKE_PARM_ENUM("log_level_print", "log_level", enum_table_log_level, 0),
BCMCLI_MAKE_PARM("throttle", "throttle", BCMCLI_PARM_UDECIMAL, 0));
}
{
BCMCLI_MAKE_CMD(dir, "id_set_trigger", "set trigger", bcm_dev_log_cli_trigger,
BCMCLI_MAKE_PARM("index", "index", BCMCLI_PARM_UDECIMAL, 0),
BCMCLI_MAKE_PARM_ENUM("log_level_print", "log_level", enum_table_log_level, 0),
BCMCLI_MAKE_PARM("start", "start", BCMCLI_PARM_UDECIMAL, 0),
BCMCLI_MAKE_PARM("stop", "stop", BCMCLI_PARM_UDECIMAL, 0),
BCMCLI_MAKE_PARM("repeat", "repeat", BCMCLI_PARM_DECIMAL, BCMCLI_PARM_FLAG_OPTIONAL));
}
{
BCMCLI_MAKE_CMD(dir, "id_get_feature", "get feature", bcm_dev_log_cli_get_features,
BCMCLI_MAKE_PARM("index", "index", BCMCLI_PARM_UDECIMAL, 0));
}
#endif
{
static bcmcli_enum_val enum_table_log_set_all[] =
{
{ .name = "none", .val = (long)DEV_LOG_ID_SET_ALL_NONE },
{ .name = "default", .val = (long)DEV_LOG_ID_SET_ALL_DEFAULT },
BCMCLI_ENUM_LAST
};
BCMCLI_MAKE_CMD(dir, "set_levels_and_type_all", "set_levels_and_type_all", bcm_dev_log_cli_set_levels_and_type_all,
BCMCLI_MAKE_PARM_ENUM("set_all", "log_type", enum_table_log_set_all, 0));
}
return dir;
}
#endif /* #ifndef __KERNEL__ */
<file_sep>#!/bin/bash
#set -x
EXE=`which $0`
START_DIR=`dirname $EXE`
export LD_LIBRARY_PATH=$START_DIR/lib:$LD_LIBRARY_PATH
if [ "$1" = "gdb" ]; then
GDB="gdb --args"
shift
fi
if [ "$1" = "valgrind" ]; then
GDB="valgrind"
shift
fi
$GDB $START_DIR/tr451_polt_daemon $*
<file_sep># Attach to running daemon
bcm_module_name(daemon_attach)
bcm_module_dependencies(PUBLIC os)
bcm_module_header_paths(PUBLIC ${daemon_SRC_DIR})
if(LOG)
bcm_module_dependencies(PUBLIC dev_log)
endif()
if(CLI_LINENOISE)
bcm_module_dependencies(PUBLIC linenoise)
endif()
bcm_module_srcs(bcmolt_daemon_attach.c)
bcm_create_app_target(fs RELEASE)
<file_sep>/* This file may be modified or replaced by the user to contain any version information
* necessary for the customer's application or for any customer patch(es) applied to the
* host source code
*/
#ifndef CUSTOMER_VERSION_INFO_H
#define CUSTOMER_VERSION_INFO_H
#endif /*CUSTOMER_VERSION_INFO_H*/
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#include "bcmolt_string.h"
#include "bcmolt_math.h"
int bcmolt_string_copy(bcmolt_string *str, const char *buf, uint32_t size)
{
int to_copy = MIN(size, str->remaining);
memcpy(str->curr, buf, to_copy);
str->remaining -= to_copy;
str->curr += to_copy;
str->curr[0] = '\0';
return to_copy;
}
int bcmolt_string_append(bcmolt_string *str, const char *fmt, ...)
{
int n;
va_list args;
va_start(args, fmt);
n = vsnprintf(str->curr, str->remaining, fmt, args);
va_end(args);
if (n > 0)
{
if (n > str->remaining)
{
n = str->remaining;
}
str->remaining -= n;
str->curr += n;
}
return n;
}
const char *bcmolt_string_get(bcmolt_string *str)
{
return str->str;
}
void bcmolt_string_reset(bcmolt_string *str)
{
str->str[0] = '\0';
str->curr = str->str;
str->remaining = str->max_len;
}
void bcmolt_string_rewind(bcmolt_string *str, int len)
{
int used = str->curr - str->str;
len = MIN(len, used);
str->remaining += len;
str->curr -= len;
str->curr[0] = '\0';
}
void bcmolt_string_init(bcmolt_string *str, char *buf, uint32_t max_len)
{
str->str = buf;
str->max_len = max_len;
bcmolt_string_reset(str);
}
char *bcmolt_string_indent(char *dst, uint32_t dst_size, uint32_t indent_level)
{
uint32_t i;
char *s = dst;
for (i = 0; i < indent_level; i++)
{
int len;
len = snprintf(s, dst_size, "%s", TAB2);
if (len < 0)
break;
s += len;
dst_size -= len;
}
return dst;
}
<file_sep># bbf-wt451-polt-sim
*Copyright (c) 2016-2020 Broadcom. All Rights Reserved*
pOLT Simulator for Broadband Forum WT-451 vOMCI project
The project implements pOLT interfaces defined
in WT-451 vOMCI Interface Specifications.
At its NBI pOLT implements the following interfaces:
NETCONF/YANG interface
======================
- bbf-polt-vomci.yang
---- client and server endpoints
---- client and server filters
- generates remote-endpoint-connected/disconnected notification as defined in YMVOMCI-11
- generates bbf-xpon-onu-states:onu-state-change notification (simulation mode only)
gRPC interface
==============
- Client and Server that can be active simultaneously.
Multiple client remote-endpoints and server listen-endpoints can be provisioned via
YANG interface or using CLI commands
- Both pOLT gRPC client and pOLT gRPC server support OmciFunctionHelloSbi and OmciFunctionMessageSbi services
defined in WT-451 vOMCI Interface Specifications
- Both gRPC client and gRPC server support secured and unsecured connection. By default connections are
unsecured. In order to create/expect secure connection cerificate file locations must
be provisioned using CLI command
- new/dropped connactions are reported using NETCONF notifications defined in YMVOMCI-11
Simulation functions:
=====================
pOLT is provided with simulation vendor sublayer (See "Vendor interface" below).
This sublayer is controlled by CLI commands that allow to
- add/remove ONU. These CLI commands populate the internal data base and also provoke sending
NETCONF notification bbf-xpon-onu-states:onu-state-change
- set receive-from-vOMCI handling mode. The following modes are supported:
- discard: OMCI packets received from vOMCI are silently discarded
- loopback <skip>:
- OMCI packets that don't require acknowledge (AR bit in OMCI header is not set) are silently discarded
- For every <skip>+1 packets that require acknowledge
- discard <skip> packets
- toggle AR and AK bits in packet <skip>+1 and send it back to vOMCI as if received from ONU
- onu_sim <remote_IP_address> <remote_port> [local_port]:
Forward packets to/from ONU simulator via UDP socket. The packets have the following format:
- char cterm_name[30]
- uint16_t onu_id; // in network order
- <omci packet without MIC>
HowTo Build
===========
The build machine must have gcc, g++, make, cmake and wget installed.
Provided that these prerequisites are met, the build is invoked using
"make" command.
It will pull a number of third party packages, such as grpc, openssh,
libssh, netopeer2, etc. from their repositories, build them and then build
pOLT simulator. The 1st build takes a while because of those bit 3rd party
packages.
Once the build is complete, build artifacts are located in build/fs
subdfirectory.
Either of the following commands builds polt-simulator with OB-BAA olt_adapter 1.0 YANG models support:
```
> make
> make OBBAA_DEVICE_ADAPTER_VERSION="1.0"
```
The following command build polt-simulator with OB-BAA olt_adapter 2.0 YANG models support:
```
> make OBBAA_DEVICE_ADAPTER_VERSION="2.0"
```
Build artifacts
======================
All build artifacts are created in build/fs directory. The following artifacts are relative to build/fs.
- bcmolt_netconf_server - pOLT executable implementing all the interfaces above
- start_netconf_server.sh - a simple shell script for starting bcmolt_netconf_server
- tr451_polt_daemon - pOLT executable implementing only gRPC and CLI interfaces above (no NETCONF/YANG)
- start_tr451_polt.sh - a simple shell script for starting tr451_polt_daemon
- daemon_attach - a small application allowing to "attach" to a daemon running in the background and use CLI.
- lib/ - third-party packages compiled as shared libraries
- bin/ - executables provided by third-party libraries (such as sysrepoctl, etc.)
- sysrepo/ - sysrepo repository
Starting the application
========================
The following commands are relative to build/fs directory.
1) Start pOLT simulator
./start_netconf_server.sh [parameters]
```
Below is output of "start_netconf_server.sh -help" command.
bcmolt_netconf_server [-d] [-dummy_tr385] [-log level] [-srlog level] [-tr451_polt_log level] [-syslog]
-d - debug mode. Stay in the foreground
-dummy_tr385 - Dummy TR-385 management. Register for some TR-385 events
-syslog - log to syslog
-tr451_polt_log error|info|debug TR-451 pOLT log level
-log error|info|debug - netconf server log level
-srlog error|info|debug - sysrepo log level
Parameters are self-explanatory.
"-d" is recommented because using CLI in foreground mode is more convenient
start_netconf_server_script.sh starts netopeer2-server in the background.
```
2) netopeer2-cli can be used for WT-451 NETCONF configuration. Alternatively,
any other compliant netconf client can be used (for example, "Atom" by Nokia)
# bin/sysrepotool.sh bin/netopeer2-cli
A few relevant netopeer2-cli commands are below
- connect --port 10830
- subscribe
- edit-config --target running --defop merge --test test-then-set --config=../../netconf_server/bbf-vomci-cli-examples/1-set-tr451-server.yc
- edit-config --target running --defop merge --test test-then-set --config=../../netconf_server/bbf-vomci-cli-examples/2-add-interfaces-olt.yc
CLI interface
=============
pOLT simulator supports CLI interface with built-in help, history and TAB completion.
CLI commands are organized hierarchically in directories.
- To change directory type its name or any unique abbreviation
- To execute command without changing current directory type fully qualified command name (ie /dir1/dir2/cmd)
- To return to the main directory use "/"
- To return to the parent directory use ".."
- To print help for a command use "? command"
- Command can be invoked by any unique abbreviation starting from the 1st character, or using a single
character that is capitalized in command name
Below are commands that are relevant for operating pOLT simulator:
1) Set logging level
```
/log/name LOG_ID PRINT_LEVEL FILE_LEVEL
```
whereas the relevant LOG_IDs are: POLT, NETCONF
PRINT_LEVEL and FILE_LEVEL values are: DEBUG, INFO, ERROR.
- PRINT_LEVEL controls output on the screen.
- FILE_LEVEL controls output to a memory file or syslog.
2) /Polt - pOLT debug directory contains the following commands. The parameters are self-explanatory:
```
?
Directory Polt/ - pOLT Debug
Commands:
Set_state(2 parms): Enable/disable client/server subsystem
Endpoint_create(4 parms): Create a client/server endpoint
endpoint_Delete(2 parms): Delete a client/server endpoint
Filter(7 parms): Create a client/server filter
Auth(3 parms): Set authentication keys
sTats(0 parms): Print statistics
Onu_add(3 parms): Add ONU
oNu_delete(3 parms): Delete ONU
Inject(3 parms): Inject OMCI packet received from ONU
Rx_mode(1 parms): Set Receive handling mode
```
NOTE: if vOMCI instance should communicate with pOLT simulator using
authenticated connection, private key and certificate location
must be set using "/polt/auth" CLI command BEFORE creating the
relevant client and/or server endpoint.
Running pOLT simulator with ONU simulator(TR451 flow)
======================
The following CLI commands can be either executed manually or placed in the stratup script:
```
#/polt/au priv_key=/certificates/vomci_privatekey.pem local_cert=/certificates/vomci.cer peer_cert=/certificates/polt.cer
/polt/set client_server=client enable=yes
#/polt/end client_server=client name=polt-simulator port=8433 host=polt-simulator
/log/n name=POLT log_level_print=DEBUG log_level_save=DEBUG
/polt/rx_mode mode=onu_sim onu_sim_ip=<ip-of-onu-simulator-container> onu_sim_port=<port-used-in-onu-simulator>
# example : /polt/rx_mode mode=onu_sim onu_sim_ip=192.168.96.3 onu_sim_port=50000
```
At this point polt-simulator must be provisioned
- with a client endpoint pointing to either vOMCI proxy or vOMCI
- with an endpoint filter
- with a channel-termination
Once it is done, ONU can be added using CLI command
```
/polt/onu_add channel_term=channeltermination.1 onu_id=2 serial_vendor_id=ABCD serial_vendor_specific=12345678
```
Further reading
======================
- Additional up-to-date info can be found in [pOLT Simulator](https://wiki.broadband-forum.org/pages/viewpage.action?spaceKey=OBBAA&title=pOLT+simulator).
- A full featured NETCONF server capable of controlling a Broadcom OLT and connected ONUs is released on github in [Broadcom pOLT NETCONF Server](https://github.com/balapi/netconf-polt).
It is a superset of this polt-simulator.
Implementation
======================
Implementation is split in 2 parts. The first part handles NETCONF/YANG interfaces.
It is implemented as a sysrepo2 application.
NETCONF server
======================
1) Of-the-shelf netopeer2-server application handles NETCONF/YANG messages received via ssh or tls.
netopeer2-server uses sysrepo2 APIs to provoke data change events.
2) sysrepo2 generates a series of events that are "forwarded" waiting application(s) via registered callback functions.
3) Application response (OK or failure with error message) is propagated by sysrepo2 back to netopeer2-server,
which in turn generates NETCONF response.
4) "Notifications" are provoked by sysrepo2 applications and forwarded by sysrepo2 engine to netopeer2-server,
similarly to responses.
The NETCONF/YANG part of TR-451 pOLT simulator is located in netconf_server/ directory
```
netconf_server/
├── bcmolt_netconf_server.c
├── CMakeLists.txt
├── modules
│ ├── b64.c
│ ├── b64.h
│ ├── bbf-vomci
│ │ ├── bbf-vomci.c
│ │ ├── bbf-vomci.h
│ │ └── CMakeLists.txt
│ ├── bbf-xpon-dummy
│ │ ├── bbf-xpon.c
│ │ ├── bbf-xpon.h
│ │ └── CMakeLists.txt
│ ├── bcmolt_netconf_constants.h
│ ├── bcmolt_netconf_module_init.c
│ ├── bcmolt_netconf_module_init.h
│ ├── bcmolt_netconf_module_utils.c
│ ├── bcmolt_netconf_module_utils.h
│ ├── bcmolt_netconf_notifications.c
│ ├── bcmolt_netconf_notifications.h
│ └── CMakeLists.txt
└── start_netconf_server.sh
```
File bbf-vomci.c implements WT-451 bbf-polt-vomci.yang YANG model. Other files listed above are
common utilities and the "main" program.
File bbf-xpon-dummy/bbf-xpon.c is a dummy TR-385 implementation that registers for ietf-interfaces changes and
OKs all changes. This module is initialized if bcm_netconf_server is started with command line option "-dummy_tr385".
This dummy module is required if there is no "real" TR-385 netconf server registered with the same sysrepo2.
Otherwise, all ietf-interface changes will remain in "pending" datastore and some bbf-polt-vomci notifications
will fail because of references to "non-existing" interfaces.
gRPC client/server
======================
```
tr451_vomci_polt
├── bcm_tr451_polt_cli.cc <--- CLI commands
├── bcm_tr451_polt_client.cc <--- gRPC client implementation
├── bcm_tr451_polt_common.cc <--- Common client & server code: filters, ONU add/delete, common connection handling
├── bcm_tr451_polt.h <--- External C interface, for NETCONF server integration
├── bcm_tr451_polt_internal.h <--- Class definitions, internal functions
├── bcm_tr451_polt_server.cc <--- gRPC server imnplementation
├── CMakeLists.txt
├── grpc_cli_examples
│ └── examples.txt
├── message_definition
... .proto files
│ ├── tr451_vomci_function_sbi_message.proto
│ └── tr451_vomci_function_sbi_service.proto
├── polt_daemon
│ ├── bcm_tr451_polt_main.c <--- "alternative" main program for gRPC-only application, without NETCONF/YANG part
│ ├── CMakeLists.txt
│ └── start_tr451_polt.sh <--- startup shell script
├── README
└── tr451_polt_vendor <--- vendor sub-layer
├── CMakeLists.txt
├── sim
│ ├── CMakeLists.txt
│ ├── sim_tr451_polt_vendor.cc <--- simulation "vendor" implementation
│ ├── sim_tr451_polt_vendor_cli.cc <--- simulation "vendor" CLI commands
│ ├── sim_tr451_polt_vendor_internal.h
│ └── tr451_polt_vendor_specific.h <--- simulation "vendor"-specific interfaces
├── tr451_polt_for_vendor.h <--- Helper functions that "vendor" implementation is allowed to use
└── tr451_polt_vendor.h <--- Functions and interfaces that "vendor" sub-layer must implement
```
Although NETCONF/YANG server is implemented in C, gRPC client/server is implemented
Vendor interface
================
Internally pOLT package has a vendor sub-layer for interacting with ONU via vendor-specific OLT interface.
Vendor interface is defined in the following header files:
- tr451_polt_vendor/tr451_polt_vendor.h - interfaces that vendor sub-layer must implement
- tr451_polt_vendor/tr451_polt_for_vendor.h - common interfaces that vendor sub-layer can use
In addition each vendor can define vendor-specific interfaces in file
tr451_polt_vendor/<vendor>/tr451_polt_vendor_specific.h.
The only vendor interface released as Open Source is "sim" which stands for simulation.
Class hierarchy
======================
See class-diagram.uml, class-diagram.png
<file_sep>version: "3.5"
services:
polt-simulator:
build:
context: ./
args:
OBBAA_OLT_ADAPTER_VERSION: "1.0"
dockerfile: Dockerfile
image: broadbandforum/obbaa-polt-simulator:latest
stdin_open: true
tty: true
container_name: polt-simulator_compose
command: ["-dummy_tr385","-f","/certificates/cli_scripts/read_certs_start_server.cli"]
environment:
- PASSWD=root
ports:
- "10830:10830"
volumes:
- "./certificates:/certificates"
<file_sep># This file contains macros for code generation using protobuf protoc
#==============
# Global variables defined when this file gets included to the top level CMakeLists.txt
#==============
set(BCM_PROTOGEN_LICENSE_PATH ${SOURCE_TOP}/codegen/license.txt)
#==============
# PRIVATE: Clear all local variables after using them.
#==============
macro(_bcm_module_protoc_clear)
unset(_MOD_GEN_SRCS)
unset(_MOD_GEN_HDRS)
endmacro(_bcm_module_protoc_clear)
#==============
# Add source files to be generated. Entries are appended to the running list. Global _MOD_GEN_SRCS is used
# for storage.
# @param ARGN [in] Sources to append to the running list
#==============
macro(bcm_module_protoc_srcs)
list(APPEND _MOD_GEN_SRCS ${ARGN})
string(REPLACE .cc .h _hdrs ${ARGN})
list(APPEND _MOD_GEN_HDRS ${hdrs})
endmacro(bcm_module_protoc_srcs)
#==============
# Run the protoc code generator.
#
# _MOD_GEN_SRCS: .c files to generate.
#
# All output files must have a corresponding file with extension .proto in the source directory.
#==============
macro(bcm_protoc_generate)
set(OUT_DIR ${CMAKE_CURRENT_BINARY_DIR})
unset(OUTPUTS)
unset(_PROTOC)
unset(_GRPC_PLUGIN)
# Check that protoc and grpc_cpp_plugic are installed
# When building on x86, protoc is one of the artifacts of imported grpc module.
# When cross-compiling, protoc must be pre-installed
# ToDo: deal with multiple protoc version on the build server
if(BCM_CONFIG_HOST MATCHES "x86")
set(_PROTOC ${BUILD_TOP}/fs/bin/protoc)
else()
if(EXISTS ${BUILD_TOP}/../host-sim/fs/bin/protoc)
set(_PROTOC ${BUILD_TOP}/../host-sim/fs/bin/protoc)
elseif(PROTOC_PATH)
find_program(_PROTOC protoc PATHS ${PROTOC_PATH})
else()
find_program(_PROTOC protoc)
endif()
if(NOT _PROTOC)
message(FATAL_ERROR "protoc is not found. Can't generate C++ code from .proto files")
endif()
endif()
get_filename_component(_PROTOC_DIR ${_PROTOC} DIRECTORY)
set(_GRPC_PLUGIN ${_PROTOC_DIR}/grpc_cpp_plugin)
if(NOT (BCM_CONFIG_HOST MATCHES "x86"))
find_program(_GRPC_PLUGIN ${_GRPC_PLUGIN})
if(NOT _GRPC_PLUGIN)
message(FATAL_ERROR "${_GRPC_PLUGIN} is not found. Can't generate C++ grpc stubs from .proto files")
endif()
endif()
set(_SHLIB_PATH ${_PROTOC_DIR}/../lib)
set(_PROTOGEN_RULE LD_LIBRARY_PATH=${_SHLIB_PATH} ${_PROTOC} -I${CMAKE_CURRENT_SOURCE_DIR} --cpp_out=${OUT_DIR})
set(_GRPCGEN_RULE LD_LIBRARY_PATH=${_SHLIB_PATH} ${_PROTOC} -I${CMAKE_CURRENT_SOURCE_DIR} --grpc_out=${OUT_DIR} --plugin=protoc-gen-grpc=${_GRPC_PLUGIN})
# Export the output directory as an include path.
bcm_module_header_paths(PUBLIC ${OUT_DIR})
foreach(_FILENAME ${_MOD_GEN_SRCS})
bcm_module_srcs("${OUT_DIR}/${_FILENAME}")
endforeach(_FILENAME)
# This path we generate the files, otherwise we've already added the pre-existing files before we got here.
set(TEMPLATE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
foreach(_FILENAME ${_MOD_GEN_SRCS})
bcm_module_srcs("${OUT_DIR}/${_FILENAME}")
endforeach(_FILENAME)
foreach(_FILENAME ${_MOD_GEN_SRCS})
# Generate protobuf or grpc classes, depending on file extension
if(${_FILENAME} MATCHES ".*\.grpc\.pb\.cc")
set(_RULE ${_GRPCGEN_RULE})
string(REPLACE ".grpc.pb.cc" ".proto" _PROTOFILE ${_FILENAME})
elseif(${_FILENAME} MATCHES ".*\.pb\.cc")
set(_RULE ${_PROTOGEN_RULE})
string(REPLACE ".pb.cc" ".proto" _PROTOFILE ${_FILENAME})
else()
message(FATAL_ERROR "Filename must be in format name.pb.cc or name.grpc.pb.cc: ${_FILENAME}")
endif()
string(REPLACE ".pb.cc" ".pb.h" _HDRNAME ${_FILENAME})
list(APPEND OUTPUTS ${OUT_DIR}/${_FILENAME})
list(APPEND OUTPUTS ${OUT_DIR}/${_HDRNAME})
# Add target for .cc generation
add_custom_command(OUTPUT ${OUT_DIR}/${_FILENAME} ${OUT_DIR}/${_HDRNAME}
COMMAND echo "Generating files ${_FILENAME}, ${_HDRNAME} in ${OUT_DIR}..."
COMMAND mkdir -p ${OUT_DIR}
COMMAND ${_RULE} ${CMAKE_CURRENT_SOURCE_DIR}/${_PROTOFILE}
VERBATIM
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/${_PROTOFILE} grpc)
endforeach(_FILENAME)
# Set the build global with the output files
bcm_module_codegen_output(${OUTPUTS})
_bcm_module_protoc_clear()
endmacro(bcm_protoc_generate)
<file_sep># sysrepo - NETCONF/YANG data base service
#
include(third_party)
bcm_make_normal_option(SYSREPO_SHM_PREFIX STRING "sysrepo SHM file prefix" "none")
if(NETCONF_TOOLS_FROM_DEVEL)
set(_VERSION "devel")
elseif(NETOPEER2_VERSION_2X)
set(_VERSION "2.0.1")
else()
set(_VERSION "1.4.140")
endif()
bcm_3rdparty_module_name(sysrepo ${_VERSION})
if("${SYSREPO_VERSION}" STREQUAL "devel")
bcm_3rdparty_download_wget("https://github.com/sysrepo/sysrepo/archive" "devel.zip" "sysrepo-devel")
else()
bcm_3rdparty_download_wget("https://github.com/sysrepo/sysrepo/archive" "v${SYSREPO_VERSION}.tar.gz")
endif()
bcm_3rdparty_add_dependencies(libev libredblack libyang protobuf protobuf-c sysrepo-commands)
bcm_3rdparty_add_build_options(-DBUILD_CPP_EXAMPLES=OFF -DBUILD_EXAMPLES=ON -DGEN_LANGUAGE_BINDINGS=OFF)
bcm_3rdparty_add_build_options(-DENABLE_TESTS=OFF -DENABLE_VALGRIND_TESTS=OFF -DGEN_PYTHON_BINDINGS=OFF)
if(SYSREPO_SHM_PREFIX AND NOT "${SYSREPO_SHM_PREFIX}" STREQUAL "none")
bcm_3rdparty_add_env_variables(SYSREPO_SHM_PREFIX=${SYSREPO_SHM_PREFIX})
endif()
set(_REPO_LOC ${_${_MOD_NAME_UPPER}_INSTALL_TOP}/sysrepo)
# Use native tools when compiling for target other than x86*
if(BCM_CONFIG_HOST MATCHES "x86")
set(_SYSREPO_TOOLS_PATH ${_${_MOD_NAME_UPPER}_SRC_DIR}/build/src)
else()
set(_SYSREPO_TOOLS_PATH ${CMAKE_BINARY_DIR}/../host-sim/fs/bin)
endif()
bcm_3rdparty_add_build_options(-DREPO_PATH:PATH=${_REPO_LOC})
bcm_3rdparty_build_cmake(shm_clean install)
bcm_3rdparty_export()
add_custom_target(sysrepo-commands
COMMAND mkdir -p ${CMAKE_BINARY_DIR}/fs/bin
COMMAND cp -af ${CMAKE_CURRENT_SOURCE_DIR}/*.sh ${CMAKE_BINARY_DIR}/fs/bin/)
unset(_SYSREPO_TOOLS_PATH)
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
/** TR-451 pOLT vendor interface
* This header file declares functions that should be implemented by vendor-specific plugin
* and dependant types.
*/
#ifndef BCM_TR451_VENDOR__H
#define BCM_TR451_VENDOR__H
#ifdef __cplusplus
extern "C"
{
#endif
#include <bcmos_system.h>
#include <bcmcli.h>
#include <bcm_tr451_polt.h>
#ifdef __cplusplus
}
#endif
#include <tr451_polt_vendor_specific.h>
#include <tr451_vomci_sbi_message.pb.h>
using tr451_vomci_sbi_message::v1::OmciPacket;
using tr451_vomci_sbi_message::v1::OnuHeader;
/** OmciPacket that can be enqueued */
class OmciPacketEntry: public OmciPacket {
public:
STAILQ_ENTRY(OmciPacketEntry) next;
};
/** ONU serial number */
typedef struct
{
uint8_t data[8]; /* in binary format. 4 bytes vendor_id followed by 4 bytes vendor-specific id */
} tr451_polt_onu_serial_number;
/** ONU information */
typedef struct
{
const char *cterm_name; /* Channel termination name */
tr451_polt_onu_serial_number serial_number;
union
{
uint8_t password[10]; /* ITU.T G.984.3 */
uint8_t registration_id[36]; /* ITU.T G.987.3, G.989.3, G.9807 */
};
uint16_t pon_interface_id; /* PON interface ID on the front panel */
#define POLT_PON_ID_UNDEFINED 0xffff
uint16_t onu_id;
#define POLT_ONU_ID_UNDEFINED 0xffff
xpon_onu_presence_flags presence_flags; /* ONU presence flags */
} tr451_polt_onu_info;
/**
* @brief Initialize TR-451 vendor library
* @returns BCM_ERR_OK(0) or error code <0
*/
bcmos_errno tr451_vendor_init(void);
/**
* @brief Terminate TR-451 vendor library
* @returns BCM_ERR_OK(0) or error code <0
*/
bcmos_errno tr451_vendor_init(void);
/**
* @brief Send packet to ONU
* @note The function can be called for multiple ONUs simultaneously
* from different execution context. It is the responsibility of the
* implementer to make it thread-safe.
* @param[in] &packet: OMCI packet received from vOMCI peer
* @returns BCM_ERR_OK(0) or error code <0
*/
bcmos_errno tr451_vendor_omci_send_to_onu(const OmciPacket &packet);
/** Callbacks for reporting events */
typedef struct
{
void *user_handle; /**< Handle that is passed transparently to event callbacks */
/**
* @brief Callback function to be called when OMCI packet is received from ONU.
* @note It is the responsibility of the callback to release the packet eventually
*/
void (*tr451_omci_rx_cb)(void *user_handle, OmciPacketEntry *packet);
/**
* @brief Callback function to be called upon ONU state change
*/
void (*tr451_onu_state_change_cb)(void *user_handle, const tr451_polt_onu_info *onu_info);
/**
* @brief Send onu state change notification.
* Usually this callback is called when ONU is added using CLI command
*/
bcmos_errno (*tr451_onu_state_change_notify_cb)(void *user_handle, const tr451_polt_onu_info *onu_info);
} tr451_vendor_event_cfg;
/**
* @brief Register to receive OMCI packets
* @note
* @param[in] rx_cb: Receive callback function to be called when OMCI packet is received
* @param[in] *rx_cb_handle: Handle to pass to rx_cb
* @returns BCM_ERR_OK(0) or error code <0
*/
bcmos_errno tr451_vendor_event_register(const tr451_vendor_event_cfg *cb_cfg);
#endif /* #ifndef BCM_TR451_VENDOR__H */
<file_sep># libyang - YANG support library
#
include(third_party)
if(NETCONF_TOOLS_FROM_DEVEL)
set(_VERSION "devel")
elseif(NETOPEER2_VERSION_2X)
set(_VERSION "2.0.7")
else()
set(_VERSION "1.0.240")
endif()
bcm_3rdparty_module_name(libyang "${_VERSION}")
if("${LIBYANG_VERSION}" STREQUAL "devel")
bcm_3rdparty_download_wget("https://github.com/CESNET/libyang/archive" "devel.zip" "libyang-devel")
else()
bcm_3rdparty_download_wget("https://github.com/CESNET/libyang/archive" "v${LIBYANG_VERSION}.tar.gz" libyang-${LIBYANG_VERSION})
endif()
bcm_3rdparty_add_build_options(-DENABLE_BUILD_TESTS=OFF -DENABLE_VALGRIND_TESTS=OFF -DPLUGINS_DIR=lib/libyang)
bcm_3rdparty_add_build_options(-DPLUGINS_DIR:PATH="${CMAKE_BINARY_DIR}/fs/lib/libyang")
if(NETOPEER2_VERSION_2X)
bcm_3rdparty_add_dependencies(pcre2)
bcm_3rdparty_add_env_variables(PATH="${CMAKE_BINARY_DIR}/fs/bin:$ENV{PATH}")
else()
bcm_3rdparty_add_dependencies(pcre)
endif()
bcm_3rdparty_build_cmake()
bcm_3rdparty_export()
<file_sep># Netconf modules
if(NETCONF_SERVER AND TR451_VOMCI_POLT)
bcm_module_name(netconf_bbf-polt-vomci)
bcm_module_dependencies(PUBLIC sysrepo libnetconf2 netconf_modules tr451_polt)
bcm_module_header_paths(PUBLIC .)
bcm_module_definitions(PUBLIC -DNETCONF_MODULE_BBF_POLT_VOMCI)
bcm_module_srcs(
bbf-vomci.c)
bcm_create_lib_target()
endif()
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
/*
* bcm_tr451_polt.h
*/
#ifndef BCM_TR451_POLT_INTERNAL_H_
#define BCM_TR451_POLT_INTERNAL_H_
#include <iostream>
#include <memory>
#include <string>
#include <grpcpp/server_builder.h>
#include <grpcpp/security/server_credentials.h>
#include <grpc/grpc.h>
#include <grpcpp/channel.h>
#include <grpcpp/client_context.h>
#include <grpcpp/create_channel.h>
#include <grpcpp/security/credentials.h>
#include <tr451_vomci_sbi_message.pb.h>
#include <tr451_vomci_sbi_service.pb.h>
#include <tr451_vomci_sbi_service.grpc.pb.h>
#include <bcm_tr451_polt.h>
#include <tr451_polt_vendor.h>
#include <tr451_polt_for_vendor.h>
#define TR451_OMCI_PACKET_POLL_TIMEOUT (100*1000)
using grpc::Server;
using grpc::ServerWriter;
using grpc::ServerBuilder;
using grpc::ServerCompletionQueue;
using grpc::ServerContext;
using grpc::Status;
using grpc::StatusCode;
using grpc::Channel;
using grpc::ClientWriter;
using grpc::ClientReader;
using grpc::ClientContext;
using google::protobuf::Empty;
using std::string;
using tr451_vomci_sbi_message::v1::Hello;
using tr451_vomci_sbi_message::v1::HelloVomciRequest;
using tr451_vomci_sbi_message::v1::HelloVomciResponse;
using tr451_vomci_sbi_message::v1::VomciMessage;
using tr451_vomci_sbi_message::v1::OmciPacket;
// Endpoint as provisioned over TR-451 YANG
class Endpoint {
public:
Endpoint(const tr451_endpoint *ep) :
name_(ep->name ? ep->name : ""),
host_name_(ep->host_name ? ep->host_name : ""),
port_(ep->port) { memset(&next, 0, sizeof(next)); }
const char *name() const { return name_.length() ? name_.c_str() : nullptr; }
const char *host_name() const { return host_name_.length() ? host_name_.c_str() : nullptr; }
uint16_t port() const { return port_; }
STAILQ_ENTRY(Endpoint) next;
private:
string name_;
string host_name_;
uint16_t port_;
};
// Client endpoint as provisioned via TR-451 YANG
// It contains a list of 1 or more access points that are tried serially
// until successful completion of vOMCI hello exchangeg
class ClientEndpoint
{
public:
ClientEndpoint(const char *name, const char *name_for_hello) :
name_(name), name_for_hello_(name_for_hello ? name_for_hello : "") {
STAILQ_INIT(&entry_list_);
}
~ClientEndpoint() {
Endpoint *ep;
while ((ep = STAILQ_FIRST(&entry_list_)) != nullptr) {
STAILQ_REMOVE_HEAD(&entry_list_, next);
delete ep;
}
}
void AddEntry(const tr451_endpoint *entry) {
Endpoint *ep = new Endpoint(entry);
STAILQ_INSERT_TAIL(&entry_list_, ep, next);
}
const Endpoint *entry(const Endpoint *prev) const {
return prev ? STAILQ_NEXT(prev, next) : STAILQ_FIRST(&entry_list_);
}
const char *name() const { return name_.c_str(); }
const char *name_for_hello() const { return name_for_hello_.length() ? name_for_hello_.c_str() : name_.c_str(); }
private:
string name_;
string name_for_hello_;
STAILQ_HEAD(, Endpoint) entry_list_;
};
// Server endpoint as provisioned via TR-451 YANG
class ServerEndpoint : public Endpoint
{
public:
ServerEndpoint(const tr451_endpoint *ep, const char *name_for_hello) :
Endpoint(ep), name_for_hello_(name_for_hello ? name_for_hello : "") {}
const char *name_for_hello() const { return name_for_hello_.length() ? name_for_hello_.c_str() : name(); }
private:
string name_for_hello_;
};
// The base class for both BcmPoltServer and BcmPoltClient
//
class GrpcProcessor {
public:
typedef enum
{
GRPC_PROCESSOR_TYPE_SERVER,
GRPC_PROCESSOR_TYPE_CLIENT
} processor_type;
GrpcProcessor(processor_type type, const char *ep_name);
virtual ~GrpcProcessor();
virtual bcmos_errno Start() = 0;
Status OmciTxToOnu(const OmciPacket &grpc_omci_packet, const char *peer = nullptr);
bcmos_errno CreateTaskAndStart();
virtual void Stop();
bool isStarted() const { return started_; }
const char *name() const { return endpoint_name_.c_str(); }
processor_type type() const { return type_; }
const char *type_name() const {
static const char *type_name[2] = { "server", "client" };
return type_name[(int)type_];
}
GrpcProcessor *GetNext() { return STAILQ_NEXT(this, next );}
STAILQ_ENTRY(GrpcProcessor) next;
bool stopping;
private:
processor_type type_;
string endpoint_name_;
bool started_;
bcmos_task task_;
};
class VomciConnectionStats
{
public:
uint32_t packets_onu_to_vomci_recv;
uint32_t packets_onu_to_vomci_sent;
uint32_t packets_onu_to_vomci_disc;
uint32_t packets_vomci_to_onu_recv;
uint32_t packets_vomci_to_onu_sent;
uint32_t packets_vomci_to_onu_disc;
};
// Logical "connection"
// Multiple logical connections can be multiplexed over a single underlying transport connection
class VomciConnection
{
public:
VomciConnection(GrpcProcessor *parent,
const string &endpoint,
const string &local_name,
const string &vomci_name,
const string &vomci_address = string());
~VomciConnection();
GrpcProcessor *parent() { return parent_; }
const char *name() const { return name_.c_str(); }
const char *peer() const { return peer_.c_str(); }
const char *endpoint() const { return endpoint_.c_str(); }
const char *local_name() const { return local_name_.length() ? local_name_.c_str() : endpoint_.c_str(); }
const char *remote_endpoint_name() {
/* Remote endpoint name is 'loca; for client connection and 'remote' for server connection */
return (parent_->type() == GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_SERVER) ?
name() : parent_->name();
}
bool isConnected() { return connected_; };
void setConnected(bool connected);
bool OmciRxFromOnu(OmciPacketEntry *omci_packet);
bcmos_errno WaitForPacketFromOnu(uint32_t poll_timeout = TR451_OMCI_PACKET_POLL_TIMEOUT) {
return bcmos_sem_wait(&omci_ind_sem, poll_timeout);
}
OmciPacketEntry *PopPacketFromOnuFromTxQueue(void);
void conn_lock() { bcmos_mutex_lock(&conn_lock_); }
void conn_unlock() { bcmos_mutex_unlock(&conn_lock_); }
void UpdateOnuAssignmentsConnected();
void UpdateOnuAssignmentsDisconnected();
// Debug counters
VomciConnectionStats stats;
// List maintenance
STAILQ_ENTRY(VomciConnection) next;
private:
GrpcProcessor *parent_;
const string name_;
const string peer_;
const string endpoint_;
const string local_name_;
bool connected_;
bcmos_mutex conn_lock_;
STAILQ_HEAD(, OmciPacketEntry) omci_ind_list;
bcmos_sem omci_ind_sem;
bcmos_mutex omci_ind_lock;
};
VomciConnection *vomci_connection_get_by_name(const char *name, const GrpcProcessor *owner = nullptr);
VomciConnection *vomci_connection_get_by_peer(const char *peer, const GrpcProcessor *owner = nullptr);
VomciConnection *vomci_connection_get_next(VomciConnection *prev, const GrpcProcessor *owner = nullptr);
void vomci_notify_connect_disconnect(VomciConnection *conn, bool is_connected);
//
// Server class
// There is an instance per server listen-endpoint in bbf-polt-vomci.yang
//
class BcmPoltServer : public GrpcProcessor
{
public:
BcmPoltServer(const tr451_server_endpoint *ep);
virtual ~BcmPoltServer();
bcmos_errno Start() override;
void Stop() override;
const ServerEndpoint *endpoint() { return &endpoint_; }
VomciConnection *connection_by_name(const string &vomci_name) {
return vomci_connection_get_by_name(vomci_name.c_str(), this);
}
VomciConnection *connection_by_peer(const string &peer) {
return vomci_connection_get_by_peer(peer.c_str(), this);
}
// Find or update remote endpoint
private:
class OmciServiceHello final :
public ::tr451_vomci_sbi_service::v1::VomciHelloSbi::Service
{
public:
OmciServiceHello(BcmPoltServer *parent) : parent_ (parent) {}
BcmPoltServer *parent() { return parent_; }
private:
Status HelloVomci(ServerContext* context,
const HelloVomciRequest* request,
HelloVomciResponse* response) override;
BcmPoltServer *parent_;
};
class OmciServiceMessage final :
public ::tr451_vomci_sbi_service::v1::VomciMessageSbi::Service
{
public:
OmciServiceMessage(BcmPoltServer *parent) : parent_ (parent) {}
BcmPoltServer *parent() { return parent_; }
private:
Status ListenForVomciRx(ServerContext* context,
const Empty* request,
ServerWriter<VomciMessage>* writer) override;
Status VomciTx(ServerContext* context, const VomciMessage* request, Empty* response) override;
BcmPoltServer *parent_;
};
OmciServiceHello hello_service_;
OmciServiceMessage message_service_;
ServerEndpoint endpoint_;
std::unique_ptr<Server> *p_server_;
};
//
// Client class
// There is an instance per client remote-endpoint in bbf-polt-vomci.yang
//
class BcmPoltClient : public GrpcProcessor
{
public:
BcmPoltClient(const tr451_client_endpoint *ep);
virtual ~BcmPoltClient();
bcmos_errno Start() override;
void Stop() override;
bcmos_errno OmciTxToVomci(OmciPacket *grpc_omci_packet);
const ClientEndpoint *endpoint() { return &endpoint_; }
void Disconnected();
VomciConnection *connection() { return connection_; }
private:
bcmos_errno Connect(const Endpoint *entry);
bcmos_errno Hello(const Endpoint *entry);
void ListenForVomciTx();
void CancelListenForVomciTx();
std::unique_ptr<::tr451_vomci_sbi_service::v1::VomciHelloSbi::Stub> hello_stub_;
std::unique_ptr<::tr451_vomci_sbi_service::v1::VomciMessageSbi::Stub> message_stub_;
std::shared_ptr<Channel> channel_;
ClientEndpoint endpoint_;
bcmos_task tx_task_;
ClientContext *listen_context_;
VomciConnection *connection_;
};
// Generic client/server gRPC processor helpers
GrpcProcessor *bcm_grpc_processor_get_by_name(const char *name, GrpcProcessor::processor_type type);
bcmos_errno bcm_grpc_processor_enable_disable(bool enable, GrpcProcessor::processor_type type);
bool bcm_grpc_processor_is_enabled(GrpcProcessor::processor_type type);
// Get server by name
BcmPoltServer *bcm_polt_server_get_by_name(const char *name);
// Get client by name
BcmPoltClient *bcm_polt_client_get_by_name(const char *name);
bool bcm_tr451_auth_data(string &priv_key, string &my_cert, string &peer_cert);
void bcm_tr451_stats_get(const char **endpoint_name, const char **peer_name, VomciConnectionStats *stats);
#endif<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#include "bcmos_hash_table.h"
#define ht_overhead sizeof(void *)
/** Create a hash table using a block pool
* \param[in] pool_parm pointer to block pool parameters
* \param[in] max_data_entries Maximum entries the hash table needs to hold
* \param[in] entry_size Size of each entry in bytes
* \param[in] key_size Size of each key in bytes
* \return pointer to newly created hash table
*/
static hash_table *hash_table_create_in_pool(bcmos_blk_pool_parm *pool_parm,
uint32_t max_data_entries,
uint16_t entry_size,
uint8_t key_size)
{
uint32_t lookup_table_entries = max_data_entries + (max_data_entries / 4);
hash_table *ht;
bcmos_errno err;
if (pool_parm == NULL)
{
/* most likely a coding error */
BUG();
return NULL;
}
entry_size += key_size;
ht = bcmos_alloc(sizeof(hash_table));
if (ht == NULL)
{
return NULL;
}
ht->obj_len = entry_size;
ht->key_len = key_size;
ht->data_offset = ht_overhead;
ht->ht_lookup_tbl_entries = lookup_table_entries;
ht->ht_max_data_entries = max_data_entries;
ht->look_up_entries_tbl = bcmos_alloc(lookup_table_entries * sizeof(ht_block));
if (ht->look_up_entries_tbl == NULL)
{
bcmos_free(ht);
return NULL;
}
ht->ht_cur_entries = 0;
err = bcmos_blk_pool_create(&ht->key_data_pool, pool_parm);
if (err != BCM_ERR_OK)
{
bcmos_free(ht->look_up_entries_tbl);
bcmos_free(ht);
return NULL;
}
if (ht->ht_max_data_entries > ht->ht_lookup_tbl_entries)
{
BCMOS_TRACE_ERR("%s: 32 bits unsiged overlow\n", __FUNCTION__);
hash_table_delete(ht);
return NULL;
}
ht->obj_len -= ht->key_len;
memset(ht->look_up_entries_tbl, 0, lookup_table_entries * sizeof(ht_block));
return ht;
}
hash_table *hash_table_create(uint32_t max_data_entries,
uint16_t entry_size,
uint8_t key_size,
char *pool_name)
{
bcmos_blk_pool_parm parm = {0};
parm.name = pool_name;
parm.blk_size = entry_size + key_size + ht_overhead;
parm.num_blks = max_data_entries;
return hash_table_create_in_pool(&parm, max_data_entries, entry_size, key_size);
}
/** Hash a length of bytes into a uint32_t
* \param[in] key Bytes to hash
* \param[in] len Number of bytes in key
* \return The hash as a uint32_t
*/
static uint32_t get_hash_for_key(const uint8_t *key, uint8_t len)
{
uint32_t hash = 5381;
uint8_t i;
const uint8_t *tmp = key;
for (i = 0; i < len; tmp++, i++)
{
hash = ((hash << 5) + hash) + (*tmp);
}
return hash;
}
/** Gets a hash key used for the keyDataPool in the HashTable
* \param[in] ht Associated hashtable we are getting hash for key for
* \param[in] key Key we are getting hash for
* \return An index into the keyDataPool
*/
static uint32_t get_hash_val_for_key(const hash_table *ht, const uint8_t *key)
{
return get_hash_for_key(key, ht->key_len) % ht->ht_lookup_tbl_entries;
}
/** Returns the location of the key within an HtBlock
* \param[in] ht Hash table in question
* \param[in] block HtBlock in question
* \return pointer to the data within the block
*/
static uint8_t *get_key_from_block_in_table(const hash_table *ht, ht_block *block)
{
return(uint8_t *) block + ht->data_offset + ht->obj_len;
}
/** Gets and populates a HtBlock with all of its data
* \param[in] next Next block in this buckets chain
* \param[in] ht Hash table in question
* \param[in] key This blocks key
* \param[in] val This blocks data
* \return The block that we allocated and returned
*/
static ht_block *fill_ht_block(ht_block *next,
hash_table *ht,
const uint8_t *key,
const void *val)
{
ht_block *dest_block = bcmos_blk_pool_alloc(&ht->key_data_pool);
if (dest_block != NULL)
{
/* storage is nextobj ptr, hash obj,
key which keeps all uint32_t aligned. */
dest_block->next_chain = next;
if (val != NULL)
{
memcpy((uint8_t *) dest_block + ht->data_offset, val, ht->obj_len);
}
else
{
memset((uint8_t *) dest_block + ht->data_offset,0,ht->obj_len);
}
/* Need to put key in after obj */
memcpy(
(uint8_t *) dest_block + ht->data_offset + ht->obj_len,
key,
ht->key_len);
}
return dest_block;
}
/** Determine whether two keys in a particular hash table match
* \param[in] ht Hashtable
* \param[in] key_a first key to compare
* \param[in] key_b second key to compare
* \return whether they are the same
*/
static bcmos_bool is_key_match(const hash_table *ht, const uint8_t *key_a, const uint8_t *key_b)
{
return memcmp(key_a, key_b, ht->key_len) == 0;
}
/** Searches a chained bucket looking for an instance of the key. If found returns the block if found the key in.
* Prev guy is set to the block in the chain before the block we returned (except in the case * where there is no
* block before the one we returned.
* \param[in] ht HashTable in question
* \param[in] key_to_find Key we wonder if exists
* \param[in] chain_start Where to start looking in the chain
* \param[in] prev_block The previous guy before the block we returned (if exists)
* \return The block that matches doesExists (if exists)
*/
static ht_block *get_key_loc_in_chain(
const hash_table *ht,
const uint8_t *key_to_find,
ht_block *chain_start,
ht_block **prev_block)
{
*prev_block = NULL;
while (chain_start != NULL)
{
if (is_key_match(ht, key_to_find, get_key_from_block_in_table(ht, chain_start)))
{
return chain_start;
}
*prev_block = chain_start;
chain_start = chain_start->next_chain;
}
return NULL;
}
bcmos_bool hash_table_remove(hash_table *ht, const uint8_t *key)
{
uint32_t hash_val = get_hash_val_for_key(ht, key);
ht_block *prev_entry;
ht_block *entry = get_key_loc_in_chain(
ht,
key,
ht->look_up_entries_tbl[hash_val].next_chain,
&prev_entry);
if (entry == NULL)
{
/* No one to delete */
return BCMOS_FALSE;
}
else
{
ht->ht_cur_entries--;
if (prev_entry == NULL)
{
/* last entry */
ht->look_up_entries_tbl[hash_val].next_chain = entry->next_chain;
}
else
{
prev_entry->next_chain = entry->next_chain;
}
bcmos_blk_pool_free(entry);
return BCMOS_TRUE;
}
}
/** Returns a pointer to the data within the HT
* \param[in] ht Hashtable in question
* \param[in] block_ptr HtBlock that we wonder where its data is
*/
static void *get_ht_data_ptr(const hash_table *ht, ht_block *block_ptr)
{
return(uint8_t*)block_ptr + ht->data_offset;
}
/** Get an entry in the hash table
* \param[in] ht pointer to hash table
* \param[in] key pointer to key data
* \param[in] hash_val hash value of key
* \return pointer to hash table entry
*/
static inline void *ht_get_internal(const hash_table *ht,
const uint8_t *key,
uint32_t hash_val)
{
ht_block *tmp;
ht_block *ret;
ret = get_key_loc_in_chain(
ht,
key,
ht->look_up_entries_tbl[hash_val].next_chain,
&tmp);
if (ret != NULL)
{
return get_ht_data_ptr(ht,ret);
}
else
{
return ret;
}
}
void *hash_table_get(const hash_table *ht, const uint8_t *key)
{
uint32_t hashVal = get_hash_val_for_key(ht, key);
return ht_get_internal(ht,key,hashVal);
}
void *hash_table_put(hash_table *ht, const uint8_t *key, const void *val)
{
void *ret_block;
uint32_t hash_val;
if (ht->ht_cur_entries >= ht->ht_max_data_entries)
{
return NULL;
}
hash_val = get_hash_val_for_key(ht, key);
ret_block = ht_get_internal((const hash_table *) ht, key, hash_val);
if (ret_block != NULL)
{
/* replace existing value with new value */
if (val != NULL)
{
memcpy(ret_block, val, ht->obj_len);
}
else
{
memset(ret_block, 0, ht->obj_len);
}
return ret_block;
}
else
{
ht_block *new_block=fill_ht_block(
ht->look_up_entries_tbl[hash_val].next_chain, ht, key, val);
if (new_block != NULL)
{
ht->look_up_entries_tbl[hash_val].next_chain = new_block;
ht->ht_cur_entries++;
return get_ht_data_ptr(ht,new_block);
}
else
{
return NULL;
}
}
}
ht_iterator ht_iterator_get(const hash_table *ht)
{
ht_iterator to_ret;
to_ret.ht = ht;
to_ret.cur_idx = 0;
to_ret.removed_at = BCMOS_FALSE;
to_ret.still_valid = BCMOS_TRUE;
to_ret.cur_block = NULL;
return to_ret;
}
ht_iterator ht_iterator_get_by_key(const hash_table *ht, const uint8_t *key)
{
ht_block *tmp;
uint32_t hash_val = get_hash_val_for_key(ht, key);
ht_iterator to_ret = {};
to_ret.ht = ht;
to_ret.removed_at = BCMOS_FALSE;
to_ret.cur_block = get_key_loc_in_chain(ht, key, ht->look_up_entries_tbl[hash_val].next_chain, &tmp);
to_ret.still_valid = (to_ret.cur_block != NULL);
to_ret.cur_idx = hash_val;
return to_ret;
}
/** Advance linear scan iterator
* \param[in] it Iterator to advance
*/
static void ht_iterator_scan_adv(ht_iterator *it)
{
if (it->cur_block != NULL)
{
it->cur_block = it->cur_block->next_chain;
if (it->cur_block != NULL)
{
it->still_valid = BCMOS_TRUE;
return;
}
else
{
it->cur_idx++;
}
}
/* find non null entry */
while (it->cur_idx < it->ht->ht_lookup_tbl_entries)
{
if (it->ht->look_up_entries_tbl[it->cur_idx].next_chain != NULL)
{
it->cur_block = it->ht->look_up_entries_tbl[it->cur_idx].next_chain;
it->still_valid = BCMOS_TRUE;
return;
}
else
{
it->cur_idx++;
}
}
it->still_valid = BCMOS_FALSE;
}
void ht_iterator_deref(const ht_iterator *hti, uint8_t **key, void **obj)
{
if (!hti->still_valid)
{
BCMOS_TRACE_ERR("%s: Invalid deref\n", __FUNCTION__);
}
else
{
*key = get_key_from_block_in_table(hti->ht, hti->cur_block);
*obj = get_ht_data_ptr(hti->ht, hti->cur_block); /* to data */
}
}
void ht_iterator_remove_at(hash_table *ht, ht_iterator *it)
{
if (ht != it->ht)
{
BCMOS_TRACE_ERR("%s: Incorrect writeable hash table pointer\n", __FUNCTION__);
}
else if (it->removed_at)
{
BCMOS_TRACE_ERR("%s: No delete twice\n", __FUNCTION__);
}
else
{
uint8_t *key;
uint8_t *obj;
ht_iterator_deref(it, &key, (void **) &obj);
it->removed_at = BCMOS_TRUE;
it->still_valid = ht_iterator_next(it);
if (!hash_table_remove(ht, key))
{
BCMOS_TRACE_ERR("%s: Remove error\n", __FUNCTION__);
}
}
}
bcmos_bool ht_iterator_next(ht_iterator *it)
{
if (it->still_valid)
{
if (it->removed_at)
{
it->removed_at = BCMOS_FALSE;
}
else
{
ht_iterator_scan_adv(it);
}
}
return it->still_valid; /* No entry found */
}
void hash_table_clear(hash_table *ht)
{
ht_iterator it = ht_iterator_get(ht);
while (ht_iterator_next(&it))
{
ht_iterator_remove_at(ht, &it);
}
}
void hash_table_delete(hash_table *ht)
{
bcmos_free(ht->look_up_entries_tbl);
bcmos_blk_pool_destroy(&ht->key_data_pool);
bcmos_free(ht);
}
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
/*
* tr451_polt_vendor_specific.h
*/
#ifndef TR451_POLT_VENDOR_SPECIFIC_H_
#define TR451_POLT_VENDOR_SPECIFIC_H_
#define TR451_POLT_MAX_PONS_PER_OLT 16
#define TR451_POLT_MAX_ONUS_PER_PON 128
#define TR451_POLT_ENABLE_VENDOR_CLI
/**
* @brief Initialize vendor CLI
* @param[in] *dir: main vomci direcory
* @returns BCM_ERR_OK(0) or error code <0
*/
bcmos_errno tr451_vendor_cli_init(bcmcli_entry *dir);
#endif /* TR451_POLT_VENDOR_SPECIFIC_H_ */
<file_sep># libgcrypt
#
include(third_party)
bcm_3rdparty_module_name(libgcrypt "1.8.4")
bcm_3rdparty_download_wget("https://gnupg.org/ftp/gcrypt/libgcrypt" "libgcrypt-${LIBGCRYPT_VERSION}.tar.bz2")
bcm_3rdparty_add_dependencies(libgpg-error)
bcm_3rdparty_add_build_options(--disable-pclmul-support --disable-doc --with-libgpg-error-prefix=${_${_MOD_NAME_UPPER}_INSTALL_TOP})
bcm_3rdparty_build_automake()
bcm_3rdparty_export()
<file_sep>#!/bin/bash
#set -x
START_DIR=`dirname $0`
cd $START_DIR
export SYSREPO_REPOSITORY_PATH=`pwd`/sysrepo
export LIBYANG_EXTENSIONS_PLUGINS_DIR=`pwd`/lib/libyang/extensions
export LIBYANG_USER_TYPES_PLUGINS_DIR=`pwd`/lib/libyang/user_types
export LD_LIBRARY_PATH=`pwd`/lib:$LD_LIBRARY_PATH
# busibox version of 'ps' doesn't support '-ef' operand
if ls -l `which ps` | grep busybox > /dev/null; then
PS="ps"
else
PS="ps -ef"
fi
NETCONF_PARMS=""
# Kill the old netopeer2-server instance unless it is running in the foreground (ie, was started separately)
if $PS | grep netopeer2\-server | grep -v grep | grep '\-d' > /dev/null; then
echo "netopeer2-server is running in the foreground. Keeping the running instance"
else
# Kill stale netopeer2-server instance if any
killall netopeer2-server 2> /dev/null
echo "Starting netopeer2-server in the background"
`pwd`/bin/start_netopeer2_server.sh -v3
sleep 2
fi
if [ "$1" = "gdb" ]; then
INSTRUMENT="gdb --args"
shift
fi
if [ "$1" = "valgrind" ]; then
INSTRUMENT="valgrind"
shift
fi
$INSTRUMENT ./bcmolt_netconf_server $*
if ! $PS | grep bcmolt_netconf_server | grep -v grep > /dev/null; then
echo Killing netopeer2-server
killall netopeer2-server 2> /dev/null
fi
<file_sep>/*
<:copyright-BRCM:2016-2019:Apache:standard
Copyright (c) 2016-2019 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
* :>
*/
#ifndef __BCM_DEV_LOG_API_H_
#define __BCM_DEV_LOG_API_H_
#include <bcmos_system.h>
/* Log file type */
typedef enum
{
BCM_DEV_LOG_FILE_MEMORY, /**< Memory file */
#ifdef BCM_OS_POSIX
BCM_DEV_LOG_FILE_REGULAR, /**< Regular file */
#endif
#ifdef DEV_LOG_SYSLOG
BCM_DEV_LOG_FILE_SYSLOG, /**< syslog "file" */
#endif
BCM_DEV_LOG_FILE_UDEF /**< User-defined file */
} bcm_dev_log_file_type;
/** Logger initialization parameters */
typedef struct dev_log_init_parms
{
bcm_dev_log_file_type type; /**< Log file type */
uint32_t queue_size; /**< Max number of entries that can be waiting on dev_log task queue. 0=use default */
#define BCM_DEV_LOG_DEFAULT_QUEUE_SIZE 4096
union /* Log parameters per log_type */
{
uint32_t mem_size; /**< Memory size for log_type == BCMOLT_LOG_TYPE_MEMORY. 0=use default */
#define BCM_DEV_LOG_DEFAULT_MEM_SIZE (1024 * 1024)
#ifdef BCM_OS_POSIX
const char *filename; /**< For log_type == BCMOLT_LOG_TYPE_FILE */
#endif
};
/**< Optional callback to call after common log initialization.
It can be used to set default log levels, timestamp format, etc.
*/
bcmos_errno (*post_init_cb)(void);
} dev_log_init_parms;
#endif /* __BCM_DEV_LOG_API_H_ */
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
/*
* bcm_tr451_polt.h
*/
#ifndef BCM_TR451_POLT_H_
#define BCM_TR451_POLT_H_
#ifdef __cplusplus
extern "C"
{
#endif
#include <bcmos_system.h>
#include <bcmcli.h>
#include <bcm_dev_log.h>
/* Include vendor-specific services that can be used for integration with vendor's NETCONF server */
#include <tr451_polt_vendor_specific.h>
typedef enum
{
TR451_FILTER_TYPE_ANY,
TR451_FILTER_TYPE_VENDOR_ID,
TR451_FILTER_TYPE_SERIAL_NUMBER
} tr451_polt_filter_type;
typedef struct tr451_endpoint
{
const char *name;
const char *host_name;
uint16_t port;
/* The following field is for internal use */
STAILQ_ENTRY(tr451_endpoint) next;
} tr451_endpoint;
/* Server endpoint */
typedef struct tr451_server_endpoint
{
tr451_endpoint endpoint;
const char *local_name; /* If set, it overrides name for hello exchange */
} tr451_server_endpoint;
/* Client endpoint */
typedef struct tr451_client_endpoint
{
const char *name;
const char *local_name; /* If set, it overrides name for hello exchange */
STAILQ_HEAD(, tr451_endpoint) entry_list; /* Client attempts connecting to the entries 1-by-1 untilll successful */
} tr451_client_endpoint;
typedef struct tr451_polt_filter
{
const char *name;
tr451_polt_filter_type type;
uint16_t priority;
uint8_t serial_number[8];
} tr451_polt_filter;
typedef struct tr451_polt_init_parms
{
bcm_dev_log_level log_level;
} tr451_polt_init_parms;
bcmos_errno bcm_tr451_polt_init(const tr451_polt_init_parms *init_parms);
typedef void (*bcm_tr451_polt_grpc_server_connect_disconnect_cb)
(void *data, const char *server_name, const char *client_name, bcmos_bool is_connected);
typedef void (*bcm_tr451_polt_grpc_client_connect_disconnect_cb)
(void *data, const char *remote_endpoint_name, const char *access_point_name, bcmos_bool is_connected);
tr451_client_endpoint *bcm_tr451_client_endpoint_alloc(const char *name);
bcmos_errno bcm_tr451_client_endpoint_add_entry(tr451_client_endpoint *ep, const tr451_endpoint *entry);
void bcm_tr451_client_endpoint_free(tr451_client_endpoint *ep);
/* Authentication */
bcmos_errno bcm_tr451_auth_set(const char *priv_key_file, const char *my_cert_file, const char *peer_cert_file);
bcmos_errno bcm_tr451_auth_get(const char **p_priv_key_file, const char **p_my_cert_file, const char **p_peer_cert_file);
/* Server interface */
bcmos_errno bcm_tr451_polt_grpc_server_init(void);
bcmos_errno bcm_tr451_polt_grpc_server_enable_disable(bcmos_bool is_enabled);
bcmos_errno bcm_tr451_polt_grpc_server_create(const tr451_server_endpoint *endpoint);
bcmos_errno bcm_tr451_polt_grpc_server_start(const char *endpoint_name);
bcmos_errno bcm_tr451_polt_grpc_server_stop(const char *endpoint_name);
bcmos_errno bcm_tr451_polt_grpc_server_delete(const char *endpoint_name);
const char *bcm_tr451_polt_grpc_server_client_get_next(const char *prev);
bcmos_errno bcm_tr451_polt_grpc_server_connect_disconnect_cb_register(
bcm_tr451_polt_grpc_server_connect_disconnect_cb cb, void *data);
void bcm_tr451_polt_grpc_server_shutdown(void);
bcmos_errno bcm_tr451_polt_filter_set(const tr451_polt_filter *filter, const char *endpoint_name);
bcmos_errno bcm_tr451_polt_filter_get(const char *filter_name, tr451_polt_filter *filter);
bcmos_errno bcm_tr451_polt_filter_delete(const char *filter_name);
/* Client interface */
bcmos_errno bcm_tr451_polt_grpc_client_init(void);
bcmos_errno bcm_tr451_polt_grpc_client_enable_disable(bcmos_bool is_enabled);
bcmos_errno bcm_tr451_polt_grpc_client_create(const tr451_client_endpoint *endpoint);
bcmos_errno bcm_tr451_polt_grpc_client_start(const char *endpoint_name);
bcmos_errno bcm_tr451_polt_grpc_client_stop(const char *endpoint_name);
bcmos_errno bcm_tr451_polt_grpc_client_delete(const char *endpoint_name);
bcmos_errno bcm_tr451_polt_grpc_client_connect_disconnect_cb_register(
bcm_tr451_polt_grpc_client_connect_disconnect_cb cb, void *data);
#ifndef XPON_ONU_PRESENCE_FLAGS_DEFINED
typedef enum
{
XPON_ONU_PRESENCE_FLAG_NONE = 0,
XPON_ONU_PRESENCE_FLAG_V_ANI = 0x01,
XPON_ONU_PRESENCE_FLAG_ONU = 0x02,
XPON_ONU_PRESENCE_FLAG_ONU_IN_O5 = 0x04,
XPON_ONU_PRESENCE_FLAG_ONU_ACTIVATION_FAILED = 0x08,
} xpon_onu_presence_flags;
#define XPON_ONU_PRESENCE_FLAGS_DEFINED
#endif
typedef enum
{
BBF_VOMCI_COMMUNICATION_STATUS_CONNECTION_ACTIVE,
BBF_VOMCI_COMMUNICATION_STATUS_CONNECTION_INACTIVE,
BBF_VOMCI_COMMUNICATION_STATUS_REMOTE_ENDPOINT_IS_NOT_ASSIGNED,
BBF_VOMCI_COMMUNICATION_STATUS_COMMUNICATION_FAILURE,
BBF_VOMCI_COMMUNICATION_STATUS_UNSPECIFIED_FAILURE
} bbf_vomci_communication_status;
bcmos_errno xpon_v_ani_vomci_endpoint_set(const char *cterm_name, uint16_t onu_id, const char *endpoint_name);
bcmos_errno xpon_v_ani_vomci_endpoint_clear(const char *cterm_name, uint16_t onu_id);
typedef bcmos_errno (*xpon_v_ani_state_change_report_cb)(const char *cterm_name, uint16_t onu_id,
const uint8_t *serial_number, xpon_onu_presence_flags presence_flags);
bcmos_errno bcm_tr451_onu_state_change_notify_cb_register(xpon_v_ani_state_change_report_cb cb);
bcmos_errno bcm_tr451_onu_status_get(const char *cterm_name, uint16_t onu_id,
bbf_vomci_communication_status *status, const char **remote_endpoint,
uint64_t *in_messages, uint64_t *out_messages, uint64_t *message_errors);
void bcm_tr451_polt_cli_init(void);
#ifdef __cplusplus
}
#endif
#endif /* BCM_DOLT_H_ */
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
/*
* sim_tr451_polt_vendor_internal.h
*/
#ifndef SIM_TR451_POLT_VENDOR_INTERNAL_H_
#define SIM_TR451_POLT_VENDOR_INTERNAL_H_
/* Receive handling mode */
typedef enum
{
TR451_POLT_SIM_RX_MODE_DISCARD,
TR451_POLT_SIM_RX_MODE_LOOPBACK,
TR451_POLT_SIM_RX_MODE_ONU_SIM
} tr451_polt_sim_rx_mode;
/* Receive handling configuration */
typedef struct
{
tr451_polt_sim_rx_mode mode;
union
{
struct
{
uint32_t skip; /* Send back 1 reply for every skip+1 requests */
} loopback;
struct
{
uint16_t local_port; /* 0=autoassign */
uint32_t remote_address; /* ONU simulator address */
uint16_t remote_port; /* ONU simulator port */
} onu_sim;
};
} tr451_polt_sim_rx_cfg;
/* Packet header for ONU sim communication */
typedef struct
{
#define TR451_ONU_SIM_CTERM_NAME_SIZE 30
char cterm_name[TR451_ONU_SIM_CTERM_NAME_SIZE];
uint16_t onu_id;
} tr451_onu_sim_packet_header;
/* Set receive handling mode */
bcmos_errno sim_tr451_vendor_rx_cfg_set(const tr451_polt_sim_rx_cfg *cfg);
/* Report ONU discovered */
bcmos_errno sim_tr451_vendor_onu_added(const char *cterm, uint16_t onu_id,
const tr451_polt_onu_serial_number *serial, xpon_onu_presence_flags flags);
/* Report ONU removed */
bcmos_errno sim_tr451_vendor_onu_removed(const char *cterm, uint16_t onu_id,
const tr451_polt_onu_serial_number *serial, xpon_onu_presence_flags flags);
/* Report packet received from ONU */
bcmos_errno sim_tr451_vendor_packet_received_from_onu(const char *cterm, uint16_t onu_id,
const uint8_t *data, uint32_t length);
#endif /* SIM_TR451_POLT_VENDOR_INTERNAL_H_ */
<file_sep># netopeer2 - NETCONF agent
#
include(third_party)
bcm_make_normal_option(NETCONF_ENABLE_NACM BOOL "Enable NETCONF Access Control Management (NACM)" n)
bcm_make_normal_option(NETOPEER_SSH_PORT STRING "Default SSH port netopeer listens on" "10830")
if(NETCONF_TOOLS_FROM_DEVEL)
set(_VERSION "devel")
elseif(NETOPEER2_VERSION_2X)
set(_VERSION "2.0.0")
else()
set(_VERSION "1.1.76")
endif()
# Netopeer2 consists from multiple components
# Umbrella module
bcm_3rdparty_module_name(netopeer2 ${_VERSION})
if("${NETOPEER2_VERSION}" STREQUAL "devel")
bcm_3rdparty_download_wget("https://github.com/CESNET/netopeer2/archive" "devel.zip" "netopeer2-devel")
else()
bcm_3rdparty_download_wget("https://github.com/CESNET/netopeer2/archive" "v${NETOPEER2_VERSION}.tar.gz" "netopeer2-${NETOPEER2_VERSION}")
endif()
bcm_3rdparty_add_dependencies(netopeer2-server-configured netopeer2-commands)
bcm_3rdparty_build_dummy()
set(_NETOPEER2_TYPE PACKAGE)
set(NETOPEER2_BASE_DIR ${_${_MOD_NAME_UPPER}_SRC_DIR})
set(NETOPEER2_LOADED ${_${_MOD_NAME_UPPER}_LOADED_FILE})
bcm_3rdparty_export()
if(SYSREPO_SHM_PREFIX AND NOT "${SYSREPO_SHM_PREFIX}" STREQUAL "none")
set(ENV{SYSREPO_SHM_PREFIX} ${SYSREPO_SHM_PREFIX})
endif()
# Use native tools when cross-compiling
if(BCM_CONFIG_HOST MATCHES "x86")
set(_SYSREPO_TOOLS_DIR ${CMAKE_BINARY_DIR}/fs/bin)
else()
set(_SYSREPO_TOOLS_DIR ${CMAKE_BINARY_DIR}/../host-sim/fs/bin)
endif()
set(_SYSREPOCFG_EXECUTABLE ${CMAKE_BINARY_DIR}/fs/bin/sysrepotool.sh ${_SYSREPO_TOOLS_DIR}/sysrepocfg)
# Server
bcm_3rdparty_module_name(netopeer2-server ${NETOPEER2_VERSION})
bcm_3rdparty_add_dependencies(libyang libnetconf2 libssh sysrepo yang-models)
bcm_3rdparty_add_build_options(-DSYSREPOCTL="${_SYSREPO_TOOLS_DIR}/sysrepoctl")
bcm_3rdparty_add_build_options(-DSYSREPOCFG="${_SYSREPO_TOOLS_DIR}/sysrepocfg")
bcm_3rdparty_add_build_options(-DOPENSSL="${_SYSREPO_TOOLS_DIR}/openssl")
bcm_3rdparty_add_build_options(-DPIDFILE_PREFIX=/tmp)
bcm_3rdparty_add_build_options(-DBUILD_TESTS:bool=OFF -DVALGRIND_TESTS:bool=OFF)
bcm_3rdparty_add_build_options(-DINSTALL_MODULES=OFF)
#bcm_3rdparty_add_build_options(-DGENERATE_HOSTKEY=OFF)
bcm_3rdparty_add_build_options(-DLIBNETCONF2_ENABLED_SSH:bool=ON)
bcm_3rdparty_add_build_options(-DPOLL_IO_TIMEOUT=100)
bcm_3rdparty_add_build_options(-DBUILD_CLI:bool=ON)
#bcm_3rdparty_add_build_options(-DDATA_CHANGE_TIMEOUT=10)
bcm_3rdparty_add_env_variables(SYSREPO_REPOSITORY_PATH=${CMAKE_BINARY_DIR}/fs/sysrepo)
if(BCM_CONFIG_HOST MATCHES "x86")
bcm_3rdparty_add_env_variables(PATH=${CMAKE_BINARY_DIR}/fs/bin:$ENV{PATH})
endif()
set(_NETOPEER2-SERVER_SRC_DIR ${NETOPEER2_BASE_DIR})
set(_NETOPEER2-SERVER_TYPE APPLICATION)
add_custom_command(OUTPUT ${_${_MOD_NAME_UPPER}_LOADED_FILE}
COMMAND mkdir -p build
COMMAND touch ${_${_MOD_NAME_UPPER}_LOADED_FILE}
DEPENDS ${NETOPEER2_LOADED}
WORKING_DIRECTORY ${_${_MOD_NAME_UPPER}_SRC_DIR})
bcm_3rdparty_build_cmake()
bcm_3rdparty_export()
# Server configured
set(_NETOPEER2_CONFIGURED_FILE ${CMAKE_CURRENT_BINARY_DIR}/.netopeer2_configured)
if(NOT NETCONF_ENABLE_NACM)
set(_DISABLE_NACM_COMMAND COMMAND ${_SYSREPOCFG_EXECUTABLE} -d startup --format xml -m ietf-netconf-acm --edit=${CMAKE_CURRENT_SOURCE_DIR}/disable_nacm.xml)
endif()
add_custom_command(OUTPUT ${_NETOPEER2_CONFIGURED_FILE}
COMMAND sed -e \'s/@SSH_PORT@/${NETOPEER_SSH_PORT}/\' ${CMAKE_CURRENT_SOURCE_DIR}/set_ssh_port.xml > ./set_ssh_port.xml
COMMAND ${_SYSREPOCFG_EXECUTABLE} -d startup --format xml -m ietf-netconf-server --edit=set_ssh_port.xml
${_DISABLE_NACM_COMMAND}
COMMAND touch ${_NETOPEER2_CONFIGURED_FILE}
DEPENDS netopeer2-server
WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/fs)
add_custom_target(netopeer2-server-configured
DEPENDS ${_NETOPEER2_CONFIGURED_FILE})
unset(_DISABLE_NACM_COMMAND)
unset(_NETOPEER2_CONFIGURED_FILE)
add_custom_target(netopeer2-commands
COMMAND mkdir -p ${CMAKE_BINARY_DIR}/fs/bin
COMMAND cp -af ${CMAKE_CURRENT_SOURCE_DIR}/*.sh ${CMAKE_BINARY_DIR}/fs/bin/)
<file_sep>/*
<:copyright-BRCM:2016-2019:Apache:standard
Copyright (c) 2016-2019 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
* :>
*/
#ifndef __BCM_DEV_LOG_TASK_H_
#define __BCM_DEV_LOG_TASK_H_
#include "bcm_dev_log_api.h"
/* Because we cast from dev_log_id to pointer type in bcm_dev_log.c, we want it to be the same size as a pointer size (e.g: "typedef uint32_t dev_log_id" won't work
* on 64bit platform). */
typedef unsigned long dev_log_id;
#define DEV_LOG_INVALID_ID (dev_log_id)UINT_MAX
#ifdef ENABLE_LOG
/* Uncomment the following line to enable info prints for dev_log debugging */
/* #define DEV_LOG_DEBUG */
#include <bcmos_system.h>
/********************************************/
/* */
/* Log macros */
/* */
/********************************************/
/********************************************/
/* */
/* Defines/Typedefs */
/* */
/********************************************/
#define STRINGIFY(x) #x
#define STRINGIFY_EXPAND(str) STRINGIFY(str)
#ifdef __KERNEL__
#define DEV_LOG_PRINTF printk
#define DEV_LOG_VPRINTF vprintk
#else
#define DEV_LOG_PRINTF bcmos_printf
#define DEV_LOG_VPRINTF bcmos_vprintf
#endif
#ifdef DEV_LOG_DEBUG
#define DEV_LOG_INFO_PRINTF(fmt, args...) DEV_LOG_PRINTF("(%s:" STRINGIFY_EXPAND(__LINE__) ") " fmt, __FUNCTION__, ##args)
#else
static inline void dev_log_info_printf_ignore(const char *fmt, ...) { }
#define DEV_LOG_INFO_PRINTF(fmt, args...) dev_log_info_printf_ignore(fmt, ##args)
#endif
#define DEV_LOG_ERROR_PRINTF(fmt, args...) DEV_LOG_PRINTF("(%s:" STRINGIFY_EXPAND(__LINE__) ") " fmt, __FUNCTION__, ##args)
/* IMPORTANT! when modifying DEV_LOG_MAX_ARGS,
* don't forget to add/remove _BCM_LOG_ARGS... macros in order to force number of arguments in compile time
*/
#define DEV_LOG_MAX_ARGS 36
/* String bigger than this size will be cut */
#define MAX_DEV_LOG_ID_NAME 32 /* Maximum size of log_id name */
#define DEV_LOG_MAX_IDS 512
#define DEV_LOG_MAX_FILES 2
#define MAX_DEV_LOG_STRING_SIZE 256 /* Note that this size includes header. */
#define MAX_DEV_LOG_HEADER_SIZE (7 + 16 + 20) /* (time=16, ID=20, delimiters=7) */
#define MAX_DEV_LOG_STRING_NET_SIZE (MAX_DEV_LOG_STRING_SIZE - MAX_DEV_LOG_HEADER_SIZE)
#define DEV_LOG_INVALID_INDEX UINT_MAX
#define DEV_LOG_DROP_REPORT_RATE_US 1000000 /* 1 second */
#define DEV_LOG_DROP_REPORT_DROP_THRESHOLD 1000
#define DEV_LOG_ENDIAN BCMOS_ENDIAN_LITTLE
/* If the log message pool utilization is >= this percentage, do not print messages (only save them).
* (note that error/fatal messages will not objey this rule). */
#define DEV_LOG_SKIP_PRINT_THRESHOLD_PERCENT 50
/* If the log message pool utilization is >= this percentage, drop all messages that aren't 'error' or 'fatal' level. */
#define DEV_LOG_ERROR_ONLY_THRESHOLD_PERCENT 75
/* Log level enum */
typedef enum
{
DEV_LOG_LEVEL_NO_LOG = 0,
DEV_LOG_LEVEL_FATAL,
DEV_LOG_LEVEL_ERROR,
DEV_LOG_LEVEL_WARNING,
DEV_LOG_LEVEL_INFO,
DEV_LOG_LEVEL_DEBUG,
DEV_LOG_LEVEL_NUM_OF
} bcm_dev_log_level;
/* Log type enum */
typedef enum
{
/* Bit[0] - Print Enable, Bit[1] - Save Enable */
DEV_LOG_ID_TYPE_NONE = 0, /* NO SAVE, NO PRINT*/
DEV_LOG_ID_TYPE_PRINT = 1,
DEV_LOG_ID_TYPE_SAVE = 1 << 1,
DEV_LOG_ID_TYPE_BOTH = DEV_LOG_ID_TYPE_PRINT | DEV_LOG_ID_TYPE_SAVE, /* SAVE & PRINT */
} bcm_dev_log_id_type;
typedef enum
{
BCM_DEV_LOG_FLAG_NONE = 0,
/* Even if logger is disabled, BCM_LOG() calls are redirected to bcmos_printf(). */
BCM_DEV_LOG_FLAG_DISABLED_WITH_PRINTF = 1 << 0,
/* When bcm_dev_log_destroy() is called, do not wait for outstanding log messages to be drained. Discard the
* messages and destroy the task immediately. */
BCM_DEV_LOG_FLAG_DESTROY_IMMEDIATELY = 1 << 1,
/* Allow registration of duplicate names. Typically this is used when killing a task and creating it again. */
BCM_DEV_LOG_FLAG_ALLOW_DUPLICATES = 1 << 2,
} bcm_dev_log_flags;
typedef enum
{
BCM_DEV_LOG_FILE_FLAG_NONE = 0,
BCM_DEV_LOG_FILE_FLAG_VALID = 1, /**< file is valid */
BCM_DEV_LOG_FILE_FLAG_WRAP_AROUND = 1 << 1, /**< new messages will override old */
BCM_DEV_LOG_FILE_FLAG_STOP_WHEN_FULL = 1 << 2, /**< stop logging if the file is full */
BCM_DEV_LOG_FILE_FLAG_CLEAR_AFTER_READ = 1 << 4, /**< auto-clear log when it is fully read */
} bcm_dev_log_file_flags;
typedef enum
{
BCM_DEV_LOG_STYLE_NORMAL,
BCM_DEV_LOG_STYLE_BOLD,
BCM_DEV_LOG_STYLE_UNDERLINE,
BCM_DEV_LOG_STYLE_BLINK,
BCM_DEV_LOG_STYLE_REVERSE_VIDEO,
} bcm_dev_log_style;
/********************************************/
/* */
/* Callbacks functions */
/* */
/********************************************/
/* Default logger ID */
extern dev_log_id def_log_id;
typedef struct bcm_dev_log_file_parm bcm_dev_log_file_parm;
typedef struct bcm_dev_log_file bcm_dev_log_file;
/****************************************************************************************/
/* OPEN CALLBACK: open memory/file */
/* file_parm - file parameters */
/* file - file */
/****************************************************************************************/
typedef bcmos_errno (*bcm_dev_log_file_open_cb)(const bcm_dev_log_file_parm *file_parm, bcm_dev_log_file *file);
/****************************************************************************************/
/* CLOSE CALLBACK: close memory/file */
/* file - file handle */
/****************************************************************************************/
typedef bcmos_errno (*bcm_dev_log_file_close_cb)(bcm_dev_log_file *file);
/****************************************************************************************/
/* REWIND CALLBACK: clears memory/file */
/* file - file handle */
/****************************************************************************************/
typedef bcmos_errno (*bcm_dev_log_file_rewind_cb)(bcm_dev_log_file *file);
/****************************************************************************************/
/* READ_CALLBACK: read form memory/file */
/* offset - the offset in bytes to read from, output */
/* buf - Where to put the result */
/* length - Buffer length */
/* This function should return the number of bytes actually read from file or 0 if EOF */
/****************************************************************************************/
typedef int (*bcm_dev_log_file_read_cb)(bcm_dev_log_file *file, uint32_t *offset, void *buf, uint32_t length);
/****************************************************************************************/
/* WRITE_CALLBACK: write form memory/file */
/* buf - The buffer that should be written */
/* length - The number of bytes to write */
/* This function should return the number of bytes actually written to file or 0 if EOF */
/****************************************************************************************/
typedef int (*bcm_dev_log_file_write_cb)(bcm_dev_log_file *file, const void *buf, uint32_t length);
/* File almost full indication callback prototype */
typedef bcmos_errno (*F_dev_log_file_almost_full)(long priv);
/* File parameters */
struct bcm_dev_log_file_parm
{
bcm_dev_log_file_type type;
/* File-access callbacks can be NULL for memory files, in this case start_addr */
/* should be a valid memory address, all read/writes options will be */
/* performed directly to this memory */
void *start_addr;
uint32_t size;
bcm_dev_log_file_open_cb open_cb;
bcm_dev_log_file_close_cb close_cb;
bcm_dev_log_file_write_cb write_cb;
bcm_dev_log_file_read_cb read_cb;
bcm_dev_log_file_rewind_cb rewind_cb;
bcm_dev_log_file_flags flags;
void *udef_parms;
};
#define FILE_MAGIC_STR_SIZE 16
#define FILE_MAGIC_STR "@LOGFILE MAGIC@" /* length should be FILE_MAGIC_STR_SIZE (including '\0') */
/* File almost full indication control info */
typedef struct dev_log_almost_full_info
{
F_dev_log_file_almost_full send_ind_cb;
uint32_t threshold;
bcmos_bool ind_sent;
long priv;
} dev_log_almost_full_info;
/* Memory file header */
typedef struct dev_log_mem_file_header
{
uint32_t file_wrap_cnt;
uint32_t write_offset;
uint32_t data_size;
uint32_t num_msgs;
char file_magic[FILE_MAGIC_STR_SIZE];
char msg_buffer[0];
} dev_log_mem_file_header;
struct bcm_dev_log_file
{
bcm_dev_log_file_parm file_parm;
dev_log_almost_full_info almost_full;
bcmos_bool is_full;
union
{
/* Memory file */
struct
{
bcmos_mutex mutex; /* Mutex to lock file access while printing it */
dev_log_mem_file_header file_header;
} mem_file;
#ifdef BCM_OS_POSIX
FILE *reg_file_handle;
#endif
/* User-defined file handle */
unsigned long udef_handle;
} u;
};
/*******************************************************************************************************/
/* Get time callback should return an integer representing time. If NULL time prints will be disabled. */
/*******************************************************************************************************/
typedef uint32_t (*bcm_dev_log_get_time_cb)(void);
/********************************************************************************************************/
/* Time to string callback receives timestamp (us) and should convert into time_str */
/* time_str_size is the maximum number of bytes to be copied. In the end function should update the */
/* number bytes actually written */
/* If NULL time will printed as an unsigned integer. */
/********************************************************************************************************/
typedef int (*bcm_dev_log_time_to_str_cb)(uint32_t time, char *time_str, int time_str_size);
typedef void (*bcm_dev_log_print_cb)(void *arg, const char *fmt, ...);
/********************************************/
/* */
/* Structs */
/* */
/********************************************/
typedef struct
{
bcm_dev_log_get_time_cb get_time_cb;
bcm_dev_log_time_to_str_cb time_to_str_cb;
bcm_dev_log_print_cb print_cb;
void *print_cb_arg;
bcm_dev_log_file_parm log_file[DEV_LOG_MAX_FILES];
} bcm_dev_log_parm;
#ifdef TRIGGER_LOGGER_FEATURE
typedef struct
{
uint32_t threshold; /* every threshold messages, print one */
uint32_t counter; /* current index - runs from 0 to threshold, periodically */
} dev_log_id_throttle;
typedef struct
{
uint32_t start_threshold; /* start printing when threshold is reached */
uint32_t stop_threshold; /* stop printing when threshold is reached, starting counting from start, if 0, do no stop */
uint32_t counter; /* current index - runs : first - from 0 to start_threshold
second - from start_threshold to stop_threshold */
int32_t repeat_threshold;/* the trigger period, how many times the trigger is set, -1 = always */
int32_t repeat; /* current repeat counter */
} dev_log_id_trigger;
#endif
typedef struct
{
bcmos_bool is_active;
char name[MAX_DEV_LOG_ID_NAME];
bcm_dev_log_id_type log_type;
bcm_dev_log_id_type default_log_type;
bcm_dev_log_level log_level_print;
bcm_dev_log_level log_level_save;
bcm_dev_log_level default_log_level;
bcm_dev_log_style style;
uint32_t lost_msg_cnt;
uint32_t print_skipped_count; /* see DEV_LOG_SKIP_PRINT_THRESHOLD_PERCENT */
uint32_t counters[DEV_LOG_LEVEL_NUM_OF];
#ifdef TRIGGER_LOGGER_FEATURE
bcm_dev_log_level throttle_log_level;
dev_log_id_throttle throttle;
bcm_dev_log_level trigger_log_level;
dev_log_id_trigger trigger;
#endif
} dev_log_id_parm;
/********************************************/
/* */
/* Functions prototypes */
/* */
/********************************************/
/** Tear down the dev_log, freeing all OS resources. */
void bcm_dev_log_destroy(void);
/* This function creates default logger that supports logging on the screen and
* into 0 or more memory files.
*/
bcmos_errno bcm_dev_log_init_default_logger(void **start_addresses,
uint32_t *sizes,
bcm_dev_log_file_flags *flags,
uint32_t num_files,
uint32_t stack_size,
bcmos_task_priority priority,
uint32_t pool_size);
/* This function is more flexible comparing with bcm_dev_log_init_default_logger().
* It creates logger that supports logging on the screen and into 0 or more
* memory, regular and user-defined files.
*/
bcmos_errno bcm_dev_log_init_default_logger_ext(
bcm_dev_log_parm *dev_log_parm,
uint32_t num_files,
uint32_t stack_size,
bcmos_task_priority priority,
uint32_t pool_size);
/**
* @brief High-level initialization function intended mainly for host use.
* @note Logger is initialized with a single log file using abbreviated set
of init parameters
* @param init_parms: Initialization parameters
* @retval BCM_ERR_OK(0) if successful or error code < 0
*/
bcmos_errno bcm_log_init(const dev_log_init_parms *init_parms);
/************************************************************************/
/* */
/* Name: bcm_dev_log_id_register */
/* */
/* Abstract: Add new ID to dev_log and return it to user */
/* */
/* Arguments: */
/* name - ID name */
/* default_log_level - ID default log level */
/* default_log_type - ID default log type */
/* */
/* Return Value: */
/* new ID */
/* */
/************************************************************************/
dev_log_id bcm_dev_log_id_register(const char *name,
bcm_dev_log_level default_log_level,
bcm_dev_log_id_type default_log_type);
/********************************************************************************************/
/* */
/* Name: bcm_dev_log_id_unregister */
/* */
/* Abstract: Unregister a registered log ID */
/* */
/* Arguments: */
/* - id - The ID in the Dev log (what we got form bcm_dev_log_id_register) */
/* */
/* Return Value: */
/* none */
/* */
/********************************************************************************************/
void bcm_dev_log_id_unregister(dev_log_id id);
/********************************************************************************************/
/* */
/* Name: bcm_dev_log_id_set_type */
/* */
/* Abstract: Set current log type for an ID */
/* */
/* Arguments: */
/* - id - The ID in the Dev log (what we got form bcm_dev_log_id_register) */
/* - log_type - New log type */
/* */
/* Return Value: */
/* bcmos_errno - Success code (BCM_ERR_OK) or Error code (see bcmos_errno.h) */
/* */
/********************************************************************************************/
bcmos_errno bcm_dev_log_id_set_type(dev_log_id id, bcm_dev_log_id_type log_type);
/********************************************************************************************/
/* */
/* Name: bcm_dev_log_id_set_level */
/* */
/* Abstract: Set current log level for an ID */
/* */
/* Arguments: */
/* - id - The ID in the Dev log (what we got form bcm_dev_log_id_register) */
/* - log_level - New log level */
/* */
/* Return Value: */
/* bcmos_errno - Success code (BCM_ERR_OK) or Error code (see bcmos_errno.h) */
/* */
/********************************************************************************************/
bcmos_errno bcm_dev_log_id_set_level(dev_log_id id, bcm_dev_log_level log_level_print, bcm_dev_log_level log_level_save);
/********************************************************************************************/
/* */
/* Name: bcm_dev_log_id_set_levels_and_type_to_default */
/* */
/* Abstract: Set log_type and log_level to default (creation) values for an ID */
/* */
/* Arguments: */
/* - id - The ID in the Dev log (what we got form bcm_dev_log_id_register) */
/* */
/* Return Value: */
/* bcmos_errno - Success code (BCM_ERR_OK) or Error code (see bcmos_errno.h) */
/* */
/********************************************************************************************/
bcmos_errno bcm_dev_log_id_set_levels_and_type_to_default(dev_log_id id);
/********************************************************************************************/
/* */
/* Name: bcm_dev_log_level_set_style */
/* */
/* Abstract: Set log style per level */
/* */
/* Arguments: */
/* - level - Log level */
/* - style - The style of the log, NORMAL, BOLD, UNDERLINE, BLINK, REVERSE_VIDEO */
/* */
/* Return Value: */
/* none */
/* */
/********************************************************************************************/
void bcm_dev_log_level_set_style(bcm_dev_log_level level, bcm_dev_log_style style);
/********************************************************************************************/
/* */
/* Name: bcm_dev_log_id_set_style */
/* */
/* Abstract: Set log style per log id */
/* */
/* Arguments: */
/* - id - The ID in the Dev log (what we got form bcm_dev_log_id_register) */
/* - style - The style of the log, NORMAL, BOLD, UNDERLINE, BLINK, REVERSE_VIDEO */
/* */
/* Return Value: */
/* bcmos_errno - Success code (BCM_ERR_OK) or Error code (see bcmos_errno.h) */
/* */
/********************************************************************************************/
bcmos_errno bcm_dev_log_id_set_style(dev_log_id id, bcm_dev_log_style style);
/************************************************************************************************/
/* */
/* Name: bcm_dev_log_id_clear_counters */
/* */
/* Abstract: Clear counter for an ID */
/* */
/* Arguments: */
/* - id - The ID in the Dev log (what we got form bcm_dev_log_id_register) */
/* */
/* Return Value: */
/* bcmos_errno - Success code (BCM_ERR_OK) or Error code (see bcmos_errno.h) */
/* */
/************************************************************************************************/
bcmos_errno bcm_dev_log_id_clear_counters(dev_log_id id);
/********************************************************************************************/
/* */
/* Name: bcm_dev_log_id_get_level */
/* */
/* Abstract: Get current log level for an ID */
/* */
/* Arguments: */
/* - id - The ID in the Dev log (what we got form bcm_dev_log_id_register) */
/* - p_log_level_print, p_log_level_save - print and save levels */
/* */
/* Return Value: */
/* bcmos_errno - Success code (BCM_ERR_OK) or Error code (see bcmos_errno.h) */
/* */
/********************************************************************************************/
bcmos_errno bcm_dev_log_id_get_level(dev_log_id id, bcm_dev_log_level *p_log_level_print,
bcm_dev_log_level *p_log_level_save);
/********************************************************************************************/
/* */
/* Name: bcm_dev_log_id_get */
/* */
/* Abstract: Get the ID status (type, level, counters ...) */
/* */
/* Arguments: */
/* - id - The ID in the Dev log (what we got form bcm_dev_log_id_register) */
/* - parm - Returned status structure */
/* */
/* Return Value: */
/* bcmos_errno - Success code (BCM_ERR_OK) or Error code (see bcmos_errno.h) */
/* */
/********************************************************************************************/
bcmos_errno bcm_dev_log_id_get(dev_log_id id, dev_log_id_parm *parm);
/********************************************************************************************/
/* */
/* Name: bcm_dev_log_id_set */
/* */
/* Abstract: set the ID status (type, level, style ...) */
/* */
/* Arguments: */
/* - id - The ID in the Dev log (what we got form bcm_dev_log_id_register) */
/* - parm - structure to set */
/* */
/* Return Value: */
/* bcmos_errno - Success code (BCM_ERR_OK) or Error code (see bcmos_errno.h) */
/* */
/********************************************************************************************/
bcmos_errno bcm_dev_log_id_set(dev_log_id id, dev_log_id_parm *parm);
/********************************************************************************/
/* */
/* Name: bcm_dev_log_id_get_by_index */
/* */
/* Abstract: Return ID for index, if no such index return (DEV_LOG_INVALID_ID) */
/* */
/* Arguments: */
/* index - The index of the ID in the global array. */
/* */
/* Return Value: */
/* uint32_t - The ID (DEV_LOG_INVALID_ID if index is not valid) */
/* */
/********************************************************************************/
dev_log_id bcm_dev_log_id_get_by_index(uint32_t index);
/********************************************************************************/
/* */
/* Name: bcm_dev_log_get_index_by_id */
/* */
/* Abstract: Return ID for index, if no such index return (DEV_LOG_INVALID_ID) */
/* */
/* Arguments: */
/* id - Log id. */
/* */
/* Return Value: */
/* uint32_t - The index ID (DEV_LOG_INVALID_INDEX if id is not valid) */
/* */
/********************************************************************************/
uint32_t bcm_dev_log_get_index_by_id(dev_log_id id);
/********************************************************************************/
/* */
/* Name: bcm_dev_log_id_get_next */
/* */
/* Abstract: Return the next active ID following a given ID */
/* */
/* Arguments: */
/* id - Log id. Use DEV_LOG_INVALID_ID to start the */
/* iteration. */
/* */
/* Return Value: */
/* uint32_t - The next ID or DEV_LOG_INVALID_ID if no more */
/* */
/********************************************************************************/
dev_log_id bcm_dev_log_id_get_next(dev_log_id id);
/********************************************************************************/
/* */
/* Name: bcm_dev_log_id_get_by_name */
/* */
/* Abstract: Return ID index for name */
/* */
/* Arguments: */
/* name - The name of the ID */
/* */
/* Return Value: */
/* dev_log_id - The ID index (-1 if name is not valid) */
/* */
/********************************************************************************/
dev_log_id bcm_dev_log_id_get_by_name(const char *name);
bcmos_bool bcm_dev_log_get_control(void);
void bcm_dev_log_set_control(bcmos_bool control);
bcm_dev_log_file_flags bcm_dev_log_get_file_flags(uint32_t file_id);
void bcm_dev_log_set_file_flags(uint32_t file_id, bcm_dev_log_file_flags flags);
bcm_dev_log_flags bcm_dev_log_get_flags(void);
void bcm_dev_log_set_flags(bcm_dev_log_flags flags);
void bcm_dev_log_set_print_cb(bcm_dev_log_print_cb cb);
void bcm_dev_log_set_get_time_cb(bcm_dev_log_get_time_cb cb);
void bcm_dev_log_set_time_to_str_cb(bcm_dev_log_time_to_str_cb cb);
/* File index to file handle */
bcm_dev_log_file *bcm_dev_log_file_get(uint32_t file_index);
/* Get number of messages stored in the file */
uint32_t bcm_dev_log_get_num_of_messages(const bcm_dev_log_file *file);
/* Get file info: max data size, used bytes */
bcmos_errno bcm_dev_log_get_file_info(bcm_dev_log_file *file, uint32_t *file_size, uint32_t *used_bytes);
/* Read from file.
* \param[in] file File to read from
* \param[in,out] offset offset to read from. 0=read from the start
* \param[in,out] buf buffer to read records to
* \param[in] buf_len buf size
* \returns - number of bytes read >= 0 or bcmos_errno < 0
* 0 = no more records to read
* BCM_ERR_OVERFLOW - buffer is too short for log record
*/
int bcm_dev_log_file_read(bcm_dev_log_file *file, uint32_t *offset, char *buf, uint32_t buf_len);
/* Clear file
* \param[in] file File handle
* \returns bcmos_errno error code
*/
bcmos_errno bcm_dev_log_file_clear(bcm_dev_log_file *file);
/* Attach file to memory buffer.
* The file data can be read using bcm_dev_log_file_read or bcm_dev_log_file_read_cut
* \param[in] buf buffer to be interpreted as memory file
* \param[in] buf_len buf size
* \param[out] file File handle.
* file_handle has to be destroyed using bcm_dev_log_file_detach() when no longer needed.
* \returns bcmos_errno error code
*/
bcmos_errno bcm_dev_log_file_attach(void *buf, uint32_t buf_len, bcm_dev_log_file *file);
/* Detach file handle from memory buffer.
* Following this call, the file handle becomes invalid
* \param[in] file File handle.
* \returns bcmos_errno error code
*/
bcmos_errno bcm_dev_log_file_detach(bcm_dev_log_file *file);
/* Register indication to be sent when file utilization crosses threshold */
bcmos_errno bcm_dev_log_almost_full_ind_register(bcm_dev_log_file *file, uint32_t used_bytes_threshold,
F_dev_log_file_almost_full send_ind_cb, long ind_cb_priv);
void dev_log_get_log_name_table(char *buffer, uint32_t buf_len);
void bcm_dev_log_drop_report(void);
/** Helper function to determine if a given log level qualifies as an error. */
static inline bcmos_bool bcm_dev_log_level_is_error(bcm_dev_log_level log_level)
{
return log_level == DEV_LOG_LEVEL_FATAL || log_level == DEV_LOG_LEVEL_ERROR;
}
/** Returns the percentage (0 - 100) of the msg pool that is currently in use. */
uint8_t bcm_dev_log_pool_occupancy_percent_get(void);
#ifdef TRIGGER_LOGGER_FEATURE
bcmos_errno bcm_dev_log_set_throttle(dev_log_id id, bcm_dev_log_level log_level, uint32_t throttle);
bcmos_errno bcm_dev_log_set_trigger(dev_log_id id, bcm_dev_log_level log_level, uint32_t start, uint32_t stop, int32_t repeat);
#endif /* TRIGGER_LOGGER_FEATURE */
void dev_log_oops_complete_cb(void);
#endif /* ENABLE_LOG */
#endif /* __BCM_DEV_LOG_TASK_H_ */
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#include <bcmolt_daemon.h>
#if defined(CONFIG_LINENOISE) && !defined(LINENOISE_DISABLE_TERMIOS)
#include <linenoise.h>
#include <termios.h>
static struct termios termios_org;
#endif
static FILE *daemon_in_fifo;
static FILE *daemon_out_fifo;
static bcmos_bool terminated;
static bcmos_bool no_lineedit;
#if defined(CONFIG_LINENOISE)
static bcmos_bool raw_mode;
#endif
static void raw_terminal_mode_disable(void)
{
/* Don't even check the return value as it's too late. */
#if defined(CONFIG_LINENOISE) && !defined(LINENOISE_DISABLE_TERMIOS)
if (raw_mode)
{
tcsetattr(STDIN_FILENO, TCSAFLUSH, &termios_org);
raw_mode = BCMOS_FALSE;
}
#endif
}
#if defined(CONFIG_LINENOISE)
/* Raw mode */
static bcmos_bool raw_terminal_mode_enable(void)
{
#if !defined(LINENOISE_DISABLE_TERMIOS)
int rc = -1;
struct termios raw;
if (raw_mode)
return BCMOS_TRUE;
if (tcgetattr(STDIN_FILENO, &termios_org) == -1)
{
return BCMOS_FALSE;
}
raw = termios_org; /* modify the original mode */
/* input modes: no break, no CR to NL, no parity check, no strip char,
* no start/stop output control. */
raw.c_iflag &= ~(BRKINT | IGNBRK | ICRNL | INPCK | ISTRIP | IXON | IXOFF);
/* output modes - disable post processing */
/* raw.c_oflag &= ~(OPOST); */
/* control modes - set 8 bit chars */
raw.c_cflag |= (CS8 /* | ISIG */);
/* local modes - echoing off, canonical off, no extended functions,
* no signal chars (^Z,^C) */
raw.c_lflag &= ~(ECHO | ICANON | IEXTEN);
/* control chars - set return condition: min number of bytes and timer.
* We want read to return every single byte, without timeout. */
raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */
/* put terminal in raw mode after flushing */
rc = tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw);
raw_mode = (rc != -1) ? BCMOS_TRUE : BCMOS_FALSE;
#endif
return raw_mode;
}
#endif
/* Check termios support */
static bcmos_bool raw_terminal_mode_check(void)
{
int rc = -1;
#if defined(CONFIG_LINENOISE) && !defined(LINENOISE_DISABLE_TERMIOS)
struct termios raw;
rc = tcgetattr(STDIN_FILENO, &raw);
#endif
return (rc != -1);
}
static int _fifo_read_handler(long arg)
{
bcmolt_daemon_parms *parms = (bcmolt_daemon_parms *)arg;
int c;
char str[256];
bcmolt_daemon_file_name(parms, DAEMON_CLI_OUTPUT_FILE_SUFFIX, str, sizeof(str));
daemon_out_fifo = fopen(str, "r");
if (daemon_out_fifo == NULL)
{
printf("daemon_attach: couldn't open CLI FIFO %s. Error %s\n", str, strerror(errno));
terminated = BCMOS_TRUE;
return 0;
}
/* coverity[tainted_data] - we want to mirror the input directly, even if it's "tainted" */
while ((c = fgetc(daemon_out_fifo)) >= 0)
{
/* Special handling of EnableRaw / DisableRaw special characters */
#if defined(CONFIG_LINENOISE)
if (c == REMOTE_SET_RAW_ON_CHAR)
{
raw_terminal_mode_enable();
}
else if (c == REMOTE_SET_RAW_OFF_CHAR)
{
raw_terminal_mode_disable();
}
else
#endif
{
putchar(c);
fflush(stdout);
}
}
printf("daemon_attach: Error or EOF when reading from CLI FIFO (%s). Terminated\n", strerror(errno));
terminated = BCMOS_TRUE;
if (!no_lineedit)
raw_terminal_mode_disable();
fclose(daemon_out_fifo);
return 0;
}
static int print_help(char *cmd)
{
fprintf(stderr, "Usage:\n"
"%s [-global] [-no-lineedit] [-path path] name\n", cmd);
fprintf(stderr, "\t-global\t\tOnly one daemon instance per host. The default is instance per user\n");
fprintf(stderr, "\t-no-lineedit\t\tDisable enhanced line editing\n");
fprintf(stderr, "\t-path path\t\tDaemon control files location. The default is /tmp\n");
return -1;
}
static void daemon_attach_signal_handler(int signal_number)
{
switch (signal_number)
{
case SIGINT:
case SIGTERM:
case SIGKILL:
printf("daemon_attach: Caught SIGINT/SIGTERM/SIGKILL signal. Terminating..\n");
if (!no_lineedit)
raw_terminal_mode_disable();
terminated = BCMOS_TRUE;
close(STDIN_FILENO);
break;
default:
printf("daemon_attach: Caught unexpected signal %d. Signal ignored\n", signal_number);
break;
}
}
int main(int argc, char *argv[])
{
bcmolt_daemon_parms daemon_parms = {};
bcmos_task_parm rd_task_parms =
{
.name = "fifo_read",
.priority = TASK_PRIORITY_CLI,
.handler = _fifo_read_handler,
.data = (long)&daemon_parms
};
bcmos_task fifo_rd_task;
int i;
int c;
char str[256];
struct sigaction act;
bcmos_errno rc;
/* Process command line parameters */
for (i = 1; i < argc; i++)
{
if (!strcmp(argv[i], "-global"))
{
daemon_parms.is_global = BCMOS_TRUE;
}
else if (!strcmp(argv[i], "-no-lineedit"))
{
no_lineedit = BCMOS_TRUE;
}
else if (!strcmp(argv[i], "-path"))
{
++i;
if (i >= argc)
return print_help(argv[0]);
daemon_parms.path = argv[i];
}
else if (argv[i][0] == '-')
{
return print_help(argv[0]);
}
else
{
if (daemon_parms.name)
return print_help(argv[0]);
daemon_parms.name = argv[i];
}
}
if (!daemon_parms.name)
return print_help(argv[0]);
/* Open FIFOs */
bcmolt_daemon_file_name(&daemon_parms, DAEMON_CLI_INPUT_FILE_SUFFIX, str, sizeof(str));
daemon_in_fifo = fopen(str, "w");
if (daemon_in_fifo == NULL)
{
printf("daemon_attach: couldn't open CLI FIFO %s. Error %s\n", str, strerror(errno));
return BCM_ERR_IO;
}
/* Create task that will read from the FIFO and print to stdout */
rc = bcmos_task_create(&fifo_rd_task, &rd_task_parms);
BUG_ON(rc != BCM_ERR_OK);
memset (&act, 0, sizeof (act));
act.sa_handler = (__sighandler_t)daemon_attach_signal_handler;
sigaction(SIGINT, &act, NULL);
sigaction(SIGTERM, &act, NULL);
bcmos_printf("Attached to %s Daemon. Enter CLI command\n", daemon_parms.name);
/* Try to switch the terminal into the raw mode and force linenoise to accept
the terminal as "smart" if successful. Otherwise, linenoise will refuse to do
line editing on a pipe file
*/
if (!no_lineedit && raw_terminal_mode_check())
{
bcmos_printf("Enhanced line editing is enabled\n");
fputs("/~ enable=yes multiline=yes force=yes\n", daemon_in_fifo);
fflush(daemon_in_fifo);
}
/* Read from stdin and write to the FIFO */
while (!terminated && (c = getchar()) >= 0)
{
if (fputc(c, daemon_in_fifo) < 0)
{
printf("daemon_attach: Failed to write to CLI FIFO (%s). Terminated\n", strerror(errno));
break;
}
fflush(daemon_in_fifo);
}
fclose(daemon_in_fifo);
bcmos_task_destroy(&fifo_rd_task);
if (!no_lineedit)
raw_terminal_mode_disable();
return 0;
}
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
/** TR-451 pOLT vendor service interface
* This header file declares functions and types provided in the common code that can be used
* by vendor-specific plugin
*/
#ifndef BCM_TR451_FOR_VENDOR__H
#define BCM_TR451_FOR_VENDOR__H
#ifdef __cplusplus
extern "C"
{
#endif
#include <bcmos_system.h>
#include <bcmcli.h>
#include <bcm_dev_log.h>
#ifdef __cplusplus
}
#include <grpc/grpc.h>
#include <grpcpp/channel.h>
using grpc::Status;
using grpc::StatusCode;
using std::string;
/* Translate Broadcom system error code to grpc::StatusCode */
grpc::Status tr451_bcm_errno_grpc_status(bcmos_errno err, const char *fmt, ...);
#endif
extern dev_log_id bcm_polt_log_id;
/* Log message */
#define BCM_POLT_LOG(level, fmt, ...) BCM_LOG(level, bcm_polt_log_id, fmt, ##__VA_ARGS__)
#endif /* #ifndef BCM_TR451_FOR_VENDOR__H */
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#include "bcmos_system.h"
/* task control blocks */
STAILQ_HEAD(task_list, bcmos_task) task_list = STAILQ_HEAD_INITIALIZER(task_list);
/* module control blocks */
bcmos_module *bcmos_modules[BCMOS_MODULE_ID__NUM_OF];
/* event control blocks */
bcmos_event *bcmos_events[BCMOS_EVENT_ID__NUM_OF];
/* Global trace level */
bcmos_trace_level bcmos_sys_trace_level = BCMOS_TRACE_LEVEL_ERROR;
/* Global OS mutex */
bcmos_mutex bcmos_res_lock;
/* Total memory occupied by block pools */
uint32_t bcmos_total_blk_pool_size;
/* Total memory occupied by message pools */
uint32_t bcmos_total_msg_pool_size;
f_bcmolt_sw_error_handler sw_error_handler;
/* Block pools */
static STAILQ_HEAD(blk_pool_list, bcmos_blk_pool) blk_pool_list = STAILQ_HEAD_INITIALIZER(blk_pool_list);
/* Message pools */
static STAILQ_HEAD(msg_pool_list, bcmos_blk_pool) msg_pool_list = STAILQ_HEAD_INITIALIZER(msg_pool_list);
/* Message queues */
static STAILQ_HEAD(msg_queue_list, bcmos_msg_queue) msg_queue_list = STAILQ_HEAD_INITIALIZER(msg_queue_list);
/* Message queue groups */
static STAILQ_HEAD(msg_qgroup_list, bcmos_msg_qgroup) msg_qgroup_list = STAILQ_HEAD_INITIALIZER(msg_qgroup_list);
/* Whether or not we should prevent any further dynamic memory allocation. */
static bcmos_bool bcmos_dynamic_memory_allocation_blocked;
static uint32_t bcmos_dynamic_memory_allocation_block_size_threshold;
/* Protection access to bcmos_dynamic_memory_allocation_block_suspended flag
from more than one task */
static bcmos_mutex dynamic_mem_alloc_suspend_mutex;
static uint32_t dynamic_alloc_suspend_usage_count;
#ifdef BCMOS_HEAP_DEBUG
static DLIST_HEAD(bcmos_heap_memblk_hdr_list, bcmos_heap_memblk_hdr) bcmos_heap_memblk_hdr_list =
DLIST_HEAD_INITIALIZER(bcmos_heap_memblk_hdr_list);
/* Lock used to protect memory blocks list */
static bcmos_mutex bcmos_heap_debug_lk;
static uint32_t bcmos_heap_debug_total_size;
static uint32_t bcmos_heap_debug_num_blocks;
/* Temporarily disable out of memory info print. This is typically used when it is expected that memory allocation may fail. */
bcmos_bool bcmos_heap_debug_out_of_memory_print_disabled;
/* Mark that initialization is done, in case we want to exclude initialization time allocations. */
bcmos_bool bcmos_heap_debug_init_done;
/* How many times to print out of memory info ? This will prevent re-printing of this info if there are multiple places that fail to allocate memory, thus reducing the amount of info we
* have go through when debugging. */
static uint8_t bcmos_heap_debug_out_of_memory_print_count = 1;
static void bcmos_alloc_debug_print_cb(void *context, const char *fmt, ...)__attribute__((format(__printf__, 2, 3)));
#endif
#ifdef BCMOS_HEALTH_CHECK_ENABLED
/* protecton of global health check data accessed by multiple modules */
static bcmos_mutex health_check_data_mutex;
/* Healthcheck prototypes */
/* Initialize the health check for a particular module. */
static bcmos_errno bcmos_module_health_check_init(const bcmos_module* module);
/* Clean up the health check for a particular module. */
static bcmos_errno bcmos_module_health_check_destroy(bcmos_module_id module_id);
#endif
/* Lock used to protect msg registration / deregistration */
static bcmos_fastlock bcmos_msg_register_lock;
/* Shutdown mode: when this is set, we expect message handler deregistration to happen while messages are still being
* sent/received. We should handle this gracefully. */
static bcmos_bool bcmos_msg_shutdown_mode = BCMOS_FALSE;
/* Timer management block */
typedef struct bcmos_timer_pool
{
bcmos_fastlock lock; /* Pool protection lock */
bcmos_sys_timer sys_timer; /* System timer handle */
bcmos_task *sys_timer_task; /* System timer task, if any */
bcmos_bool sys_timer_task_set;
uint32_t num_active_timers; /* Number of active timers in the pool */
#ifdef BCMOS_TIMER_RB_TREE
RB_HEAD(bcmos_timers, bcmos_timer) pool; /* Timer pool. RB tree */
#else
TAILQ_HEAD(bcmos_timers, bcmos_timer) pool; /* Timer pool: TAILQ */
#endif
} bcmos_timer_pool;
static int32_t _bcmos_timer_compare(bcmos_timer *t1, bcmos_timer *t2);
#ifdef BCMOS_TIMER_DEBUG
/* timer control blocks */
static STAILQ_HEAD(timer_list, bcmos_timer) timer_list = STAILQ_HEAD_INITIALIZER(timer_list);
#endif
/*
* Macros for RB-TREE and TAILQ-based timer tool implementations
*/
#ifdef BCMOS_TIMER_RB_TREE
/* ARM compiler doesn't like unused inline functions. Disable the warning */
#if defined(ARM_V7)
#pragma diag_suppress 177
#elif defined(__clang__)
#pragma clang diagnostic ignored "-Wunused-function"
#endif
/* Generate RB tree functions */
RB_GENERATE_INLINE(bcmos_timers, bcmos_timer, pool_entry, _bcmos_timer_compare)
#define TMR_POOL_INIT(tmr_pool) RB_INIT(&(tmr_pool)->pool)
#define TMR_POOL_INSERT(tmr_pool, tmr) RB_INSERT(bcmos_timers, &(tmr_pool)->pool, tmr)
#define TMR_POOL_REMOVE(tmr_pool, tmr) RB_REMOVE(bcmos_timers, &(tmr_pool)->pool, tmr)
#define TMR_POOL_FIRST(tmr_pool) RB_MIN(bcmos_timers, &(tmr_pool)->pool)
#else
#define TMR_POOL_INIT(tmr_pool) TAILQ_INIT(&(tmr_pool)->pool)
#define TMR_POOL_INSERT(tmr_pool, tmr) \
do \
{ \
bcmos_timer *_last = TAILQ_LAST(&(tmr_pool)->pool, bcmos_timers); \
if (_last) \
{ \
if (_bcmos_timer_compare(tmr, _last) >= 0) \
{ \
TAILQ_INSERT_TAIL(&(tmr_pool)->pool, tmr, pool_entry); \
} \
else \
{ \
bcmos_timer *_t; \
uint32_t iter = 0; \
TAILQ_FOREACH(_t, &(tmr_pool)->pool, pool_entry) \
{ \
BUG_ON(iter >= (tmr_pool)->num_active_timers);\
++iter; \
if (_bcmos_timer_compare(tmr, _t) <= 0) \
{ \
TAILQ_INSERT_BEFORE(_t, tmr, pool_entry); \
break; \
} \
} \
} \
} \
else \
{ \
TAILQ_INSERT_HEAD(&(tmr_pool)->pool, tmr, pool_entry); \
} \
++(tmr_pool)->num_active_timers; \
} while (0)
#define TMR_POOL_REMOVE(tmr_pool, tmr) \
do \
{ \
BUG_ON(!(tmr_pool)->num_active_timers); \
TAILQ_REMOVE(&(tmr_pool)->pool, tmr, pool_entry); \
TAILQ_NEXT(tmr, pool_entry) = NULL; \
--(tmr_pool)->num_active_timers; \
} while (0)
#define TMR_POOL_FIRST(tmr_pool) TAILQ_FIRST(&(tmr_pool)->pool)
#endif
#define BCMOS_TIMER_IS_RUNNING(tmr) ((tmr->flags & BCMOS_TIMER_FLAG_RUNNING) != 0)
#define BCMOS_TIMER_IS_EXPIRED(tmr) ((tmr->flags & BCMOS_TIMER_FLAG_EXPIRED) != 0)
#define BCMOS_TIMER_IS_VALID(tmr) ((tmr->flags & BCMOS_TIMER_FLAG_VALID) != 0)
#define BCMOS_TIMER_IS_ACTIVE(tmr) ((tmr->flags & BCMOS_TIMER_FLAG_ACTIVE) != 0)
static bcmos_bool bcmos_initialized;
static bcmos_timer_pool tmr_pool;
static void _sys_timer_handler(void *data);
/*
* Print variables
*/
static bcmos_print_redirect_mode print_redirect_mode;
static bcmos_print_redirect_cb print_redirect_cb;
static void *print_redirect_cb_data;
static bcmos_mutex bcmos_print_lock;
#ifdef BCMOS_BUF_POOL_SIZE
static bcmos_blk_pool sys_buf_pool;
#ifdef BCMOS_BIG_BUF_POOL_SIZE
static bcmos_blk_pool sys_big_buf_pool;
#endif
static bcmos_errno bcmos_buf_pool_create(uint32_t pool_size, uint32_t blk_size, bcmos_blk_pool *blk_pool);
#endif
/** Initialize system library
* \ingroup system
* Must be called before any other system function
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_init(void)
{
bcmos_errno rc;
if (bcmos_initialized)
return BCM_ERR_OK;
rc = bcmos_sys_init();
bcmos_mutex_create(&bcmos_res_lock, 0, "res_lock");
bcmos_mutex_create(&bcmos_print_lock, 0, "print_lock");
#ifdef BCMOS_HEAP_DEBUG
bcmos_mutex_create(&bcmos_heap_debug_lk, 0, "heap_debug_lock");
#endif
#ifdef BCMOS_HEALTH_CHECK_ENABLED
bcmos_mutex_create(&health_check_data_mutex, 0, "health_check_mutex");
#endif
bcmos_mutex_create(&dynamic_mem_alloc_suspend_mutex, 0, "dyn_alloc_susp_mutex");
/* coverity[missing_lock] - this happens during initialization so doesn't need to be locked */
dynamic_alloc_suspend_usage_count = 0;
TMR_POOL_INIT(&tmr_pool);
bcmos_fastlock_init(&tmr_pool.lock, 0);
bcmos_fastlock_init(&bcmos_msg_register_lock, 0);
rc = rc ? rc : bcmos_sys_timer_create(&tmr_pool.sys_timer, _sys_timer_handler, &tmr_pool);
/* Create default buffer pool if so requested by compilation options */
#ifdef BCMOS_BUF_POOL_SIZE
#ifndef BCMOS_BUF_POOL_BUF_SIZE
#error BCMOS_BUF_POOL_BUF_SIZE must be defined
#endif
rc = rc ? rc : bcmos_buf_pool_create(BCMOS_BUF_POOL_SIZE, BCMOS_BUF_POOL_BUF_SIZE, &sys_buf_pool);
#endif
/* Create BIG_BUF pool */
#ifdef BCMOS_BIG_BUF_POOL_SIZE
#ifndef BCMOS_BIG_BUF_POOL_BUF_SIZE
#error BCMOS_BUF_POOL_BUF_SIZE must be defined
#endif
rc = rc ? rc : bcmos_buf_pool_create(BCMOS_BIG_BUF_POOL_SIZE, BCMOS_BIG_BUF_POOL_BUF_SIZE, &sys_big_buf_pool);
#endif
if (!rc)
{
bcmos_initialized = BCMOS_TRUE;
}
return rc;
}
/** Cleanup system library
* \ingroup system
*/
void bcmos_exit(void)
{
if (!bcmos_initialized)
return;
#ifdef BCMOS_BUF_POOL_SIZE
bcmos_blk_pool_reset(&sys_buf_pool);
bcmos_blk_pool_destroy(&sys_buf_pool);
#endif
#ifdef BCMOS_BIG_BUF_POOL_SIZE
bcmos_blk_pool_reset(&sys_big_buf_pool);
bcmos_blk_pool_destroy(&sys_big_buf_pool);
#endif
bcmos_sys_timer_destroy(&tmr_pool.sys_timer);
bcmos_mutex_destroy(&bcmos_print_lock);
bcmos_mutex_destroy(&bcmos_res_lock);
#ifdef BCMOS_HEAP_DEBUG
bcmos_mutex_destroy(&bcmos_heap_debug_lk);
#endif
#ifdef BCMOS_HEALTH_CHECK_ENABLED
bcmos_mutex_destroy(&health_check_data_mutex);
#endif
bcmos_sys_exit();
bcmos_initialized = BCMOS_FALSE;
}
/*
* Heap debug service
*/
#ifdef BCMOS_HEAP_DEBUG
void bcmos_heap_debug_lock(void)
{
bcmos_mutex_lock(&bcmos_heap_debug_lk);
}
void bcmos_heap_debug_unlock(void)
{
bcmos_mutex_unlock(&bcmos_heap_debug_lk);
}
static inline void bcmos_heap_debug_memblk_set_hdr(bcmos_heap_memblk_hdr *hdr, uint32_t size, const char *fname, uint32_t line)
{
strncpy(hdr->fname, fname, sizeof(hdr->fname) - 1);
hdr->fname[sizeof(hdr->fname) - 1] = 0;
hdr->timestamp = bcmos_timestamp();
hdr->line = line;
hdr->size = size;
hdr->is_init_time = !bcmos_heap_debug_init_done;
hdr->magic = BCMOS_HEAP_DEBUG_ALLOC_MAGIC;
}
/* Add newly allocated memory block to heap debug list. Returns "user" pointer */
void *bcmos_heap_debug_memblk_add(void *hdr_ptr, uint32_t size, const char *fname, uint32_t line)
{
bcmos_heap_memblk_hdr *hdr = (bcmos_heap_memblk_hdr *)hdr_ptr;
void *user_ptr;
uint32_t magic = BCMOS_HEAP_DEBUG_ALLOC_MAGIC;
if (hdr_ptr == NULL)
return NULL;
bcmos_heap_debug_memblk_set_hdr(hdr, size, fname, line);
user_ptr = (void *)(hdr + 1);
/* Initialize magic tail. */
memcpy((void *)((long)user_ptr + size), &magic, sizeof(uint32_t));
bcmos_heap_debug_lock();
DLIST_INSERT_HEAD(&bcmos_heap_memblk_hdr_list, hdr, list);
bcmos_heap_debug_total_size += size;
++bcmos_heap_debug_num_blocks;
bcmos_heap_debug_unlock();
return user_ptr;
}
/* Check memory block. Returns BCMOS_TRUE if the block is OK */
static bcmos_bool _bcmos_heap_debug_memblk_check(void *user_ptr, const char *fname,
uint32_t line, bcmos_bool suppress_sw_err)
{
bcmos_heap_memblk_hdr *hdr = bcmos_heap_user_ptr_to_debug_hdr(user_ptr);
uint32_t magic;
/* Check for corruption */
if (hdr->magic != BCMOS_HEAP_DEBUG_ALLOC_MAGIC)
{
if (hdr->magic == BCMOS_HEAP_DEBUG_FREE_MAGIC)
{
if (suppress_sw_err)
{
BCMOS_TRACE(BCMOS_TRACE_LEVEL_ERROR, "The block is free %p (size %u). Freed in %s#%u at %u\n",
user_ptr, hdr->size, hdr->fname, hdr->line, hdr->timestamp);
}
else
{
BCMOS_TRACE_ERR("%s#%u: Double-free block %p (size %u). Already freed in %s#%u at \n",
fname, line, user_ptr, hdr->size, hdr->fname, hdr->line, hdr->timestamp);
}
}
else
{
if (suppress_sw_err)
{
BCMOS_TRACE(BCMOS_TRACE_LEVEL_ERROR,
"Memory block %p (size %u) head corruption detected. Allocated in %s#%u at %u\n",
user_ptr, hdr->size, hdr->fname, hdr->line, hdr->timestamp);
}
else
{
BCMOS_TRACE_ERR(
"%s#%u: Memory block %p (size %u) head corruption detected. Allocated in %s#%u at %u\n",
fname, line, user_ptr, hdr->size, hdr->fname, hdr->line, hdr->timestamp);
}
}
return BCMOS_FALSE;
}
/* Check for tail corruption */
memcpy(&magic, (void *)((long)user_ptr + hdr->size), sizeof(uint32_t));
if (magic != BCMOS_HEAP_DEBUG_ALLOC_MAGIC)
{
if (suppress_sw_err)
{
BCMOS_TRACE(BCMOS_TRACE_LEVEL_ERROR,
"Memory block %p (size %u) tail corruption detected. Allocated in %s#%u\n",
user_ptr, hdr->size, hdr->fname, hdr->line, hdr->timestamp);
}
else
{
BCMOS_TRACE_ERR(
"%s#%u: Memory block %p (size %u) tail corruption detected. Allocated in %s#%u at %u\n",
fname, line, user_ptr, hdr->size, hdr->fname, hdr->line, hdr->timestamp);
}
return BCMOS_FALSE;
}
return BCMOS_TRUE;
}
/* Check memory block. Returns BCMOS_TRUE if the block is OK */
bcmos_bool bcmos_heap_debug_memblk_check(void *user_ptr)
{
return _bcmos_heap_debug_memblk_check(user_ptr, "dummy", 0, BCMOS_TRUE);
}
/* Check memory block before freeing it. Returns BCMOS_TRUE if the block is OK */
bcmos_bool bcmos_heap_debug_memblk_check_and_del(void *user_ptr, const char *fname, uint32_t line)
{
bcmos_heap_memblk_hdr *hdr = bcmos_heap_user_ptr_to_debug_hdr(user_ptr);
uint32_t magic;
bcmos_bool valid;
if (user_ptr == NULL)
{
BCMOS_TRACE_ERR("Attempt to free NULL pointer in %s:%u\n", fname, line);
return BCMOS_FALSE;
}
bcmos_heap_debug_lock();
valid = _bcmos_heap_debug_memblk_check(user_ptr, fname, line, BCMOS_FALSE);
if (valid)
{
DLIST_REMOVE(hdr, list);
bcmos_heap_debug_total_size -= hdr->size;
--bcmos_heap_debug_num_blocks;
bcmos_heap_debug_unlock();
bcmos_heap_debug_memblk_set_hdr(hdr, hdr->size, fname, line);
magic = BCMOS_HEAP_DEBUG_FREE_MAGIC;
/* Change magic tail to BCMOS_HEAP_DEBUG_FREE_MAGIC. */
memcpy((void *)((long)user_ptr + hdr->size), &magic, sizeof(uint32_t));
}
else
{
bcmos_heap_debug_unlock();
}
return valid;
}
void *bcmos_heap_debug_memblk_get_next(void *prev)
{
bcmos_heap_memblk_hdr *prev_hdr = bcmos_heap_user_ptr_to_debug_hdr(prev);
bcmos_heap_memblk_hdr *hdr;
hdr = prev ? DLIST_NEXT(prev_hdr, list) : DLIST_FIRST(&bcmos_heap_memblk_hdr_list);
return bcmos_heap_debug_hdr_to_user_ptr(hdr);
}
void bcmos_heap_debug_info_get(uint32_t *num_blocks, uint32_t *total_size)
{
*num_blocks = bcmos_heap_debug_num_blocks;
*total_size = bcmos_heap_debug_total_size;
}
static void bcmos_alloc_debug_print_cb(void *context, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
bcmos_vprintf(fmt, ap);
va_end(ap);
}
static void *bcmos_alloc_debug_add(void *user_ptr, uint32_t size, const char *fname, uint32_t line)
{
if (!user_ptr)
{
if (!bcmos_heap_debug_out_of_memory_print_disabled && bcmos_heap_debug_out_of_memory_print_count--)
{
uint32_t num_blocks, total_size;
bcmos_printf("Out of memory !\n");
bcmos_heap_debug_info_get(&num_blocks, &total_size);
bcmos_printf("Heap info: %u allocated blocks, total size %u\n", num_blocks, total_size);
/* By default, we exclude initialization time allocations. */
bcmos_heap_debug_print(bcmos_alloc_debug_print_cb, NULL, NULL, BCMOS_TRUE, 0, 0, 0, 0, 0, NULL);
}
return user_ptr;
}
return bcmos_heap_debug_memblk_add(bcmos_heap_user_ptr_to_debug_hdr(user_ptr), size, fname, line);
}
void *bcmos_alloc_debug(uint32_t size, const char *fname, uint32_t line)
{
void *user_ptr = _bcmos_alloc(size + BCMOS_HEAP_DEBUG_OVERHEAD);
return bcmos_alloc_debug_add(user_ptr, size, fname, line);
}
void *bcmos_calloc_debug(uint32_t size, const char *fname, uint32_t line)
{
void *user_ptr = _bcmos_calloc(size + BCMOS_HEAP_DEBUG_OVERHEAD);
return bcmos_alloc_debug_add(user_ptr, size, fname, line);
}
void bcmos_free_debug(void *ptr, const char *fname, uint32_t line)
{
if (bcmos_heap_debug_memblk_check_and_del(ptr, fname, line))
_bcmos_free(ptr);
}
bcmos_errno bcmos_heap_debug_print(bcmos_msg_print_cb print_cb, bcmos_hexdump_cb hexdump_cb, void *context, bcmos_bool exclude_init_time, uint32_t num_skip, uint32_t num_print,
uint32_t data_bytes, uint32_t start_ts, uint32_t end_ts, const char *func)
{
void *ptr = NULL;
int n = 0;
int n_printed = 0;
print_cb(context, "Heap dump\n");
print_cb(context,
"Function Line Ptr Size Timestamp\n");
bcmos_heap_debug_lock();
while ((ptr = bcmos_heap_debug_memblk_get_next(ptr)) != NULL)
{
bcmos_heap_memblk_hdr *hdr = bcmos_heap_user_ptr_to_debug_hdr(ptr);
++n;
if (num_skip && n < num_skip)
continue;
if (func && strcmp(func, hdr->fname))
continue;
if (end_ts && (int32_t)(hdr->timestamp - end_ts) >= 0)
continue;
if (start_ts && (int32_t)(hdr->timestamp - start_ts) < 0)
break;
if (exclude_init_time && hdr->is_init_time)
continue;
print_cb(context, "%-40s %-5u %-16p %-8u %u\n",
hdr->fname, hdr->line, ptr, hdr->size, hdr->timestamp);
bcmos_heap_debug_memblk_check(ptr);
if (data_bytes)
{
uint32_t print_size = (data_bytes < hdr->size) ? data_bytes : hdr->size;
hexdump_cb(print_cb, context, ptr, 0, print_size, " ");
}
++n_printed;
if (num_print && n_printed >= num_print)
break;
}
bcmos_heap_debug_unlock();
print_cb(context, "%d blocks printed\n", n_printed);
return BCM_ERR_OK;
}
#endif /* #ifdef BCMOS_HEAP_DEBUG */
/*
* Common task services
*/
/* Query task info */
bcmos_errno bcmos_task_query(const bcmos_task *task, bcmos_task_parm *parm)
{
if (task == NULL || task->magic != BCMOS_TASK_MAGIC || parm == NULL)
{
return BCM_ERR_PARM;
}
*parm = task->parm;
return BCM_ERR_OK;
}
/** Task iterator
* \param[in] prev Previous task. *prev==NULL - get first
* \return: BCM_ERR_OK, BCM_ERR_NOENT, BCM_ERR_NO_MORE
*/
bcmos_errno bcmos_task_get_next(bcmos_task **prev)
{
bcmos_task *task;
if (prev == NULL)
{
return BCM_ERR_PARM;
}
task = *prev;
if (task && task->magic != BCMOS_TASK_MAGIC)
{
return BCM_ERR_PARM;
}
if (task)
{
task = STAILQ_NEXT(task, list);
}
else
{
task = STAILQ_FIRST(&task_list);
}
*prev = task;
if (!task)
{
return BCM_ERR_NO_MORE;
}
return BCM_ERR_OK;
}
/*
* Message queue
*/
static void _bcmos_msgq_notify(bcmos_msg_queue *q, const char *txt)
{
BCMOS_TRACE_INFO("Msg queue %s: %s\n", q->q.parm.name, txt);
}
/* Decrement in-queue statistics */
static inline void _bcmos_msgq_stat_dec(bcmos_msg_queue_nw *q)
{
bcmos_msg_queue_stat *stat = &q->stat;
uint32_t old_in = stat->msg_in;
if (stat->msg_in == 0)
{
BCMOS_TRACE_ERR("Attempt to decrement statistics for an empty queue ('%s')\n", q->parm.name);
}
else
{
--stat->msg_in;
++stat->msg_received;
}
if (old_in == q->parm.low_wm)
{
q->parm.notify((bcmos_msg_queue *)q, "becomes uncongested");
stat->is_congested = BCMOS_FALSE;
}
}
/* Increment in-queue statistics */
static inline void _bcmos_msgq_stat_inc(bcmos_msg_queue_nw *q)
{
bcmos_msg_queue_stat *stat = &q->stat;
uint32_t old_in = stat->msg_in;
++stat->msg_in;
++stat->msg_sent;
if (old_in == q->parm.high_wm)
{
q->parm.notify((bcmos_msg_queue *)q, "becomes congested");
stat->is_congested = BCMOS_TRUE;
}
if (stat->is_congested)
++stat->msg_almost_full;
}
static void _bcmos_qgroup_notify(bcmos_msg_qgroup *qgroup, const char *txt)
{
BCMOS_TRACE_INFO("Msg queue %s: %s\n", qgroup->parm.name, txt);
}
/* Decrement in-queue statistics for queue group */
static inline void _bcmos_qgroup_stat_dec(bcmos_msg_qgroup *qgroup)
{
bcmos_msg_queue_stat *stat = &qgroup->stat;
uint32_t old_in = stat->msg_in;
if (stat->msg_in == 0)
{
BCMOS_TRACE_ERR("Attempt to decrement statistics for an empty queue ('%s')\n", qgroup->parm.name);
}
else
{
--stat->msg_in;
++stat->msg_received;
}
if (old_in == qgroup->parm.low_wm)
{
qgroup->parm.notify(qgroup, "becomes uncongested");
stat->is_congested = BCMOS_FALSE;
}
}
/* Increment in-queue statistics */
static inline void _bcmos_qgroup_stat_inc(bcmos_msg_qgroup *qgroup)
{
bcmos_msg_queue_stat *stat = &qgroup->stat;
uint32_t old_in = stat->msg_in;
++stat->msg_in;
++stat->msg_sent;
if (old_in == qgroup->parm.high_wm)
{
qgroup->parm.notify(qgroup, "becomes congested");
stat->is_congested = BCMOS_TRUE;
}
if (stat->is_congested)
++stat->msg_almost_full;
}
/* Get message from queue.
* Urgent queue is checked 1st, then regular queue
* Must be called under lock!
* Returns msg or NULL if queue is empty
*/
static inline bcmos_msg *_bcmos_msg_get(bcmos_msg_queue_nw *q)
{
bcmos_msg *msg;
msg = STAILQ_FIRST(&q->msgl_urg);
if (msg)
{
STAILQ_REMOVE_HEAD(&q->msgl_urg, next);
_bcmos_msgq_stat_dec(q);
return msg;
}
msg = STAILQ_FIRST(&q->msgl);
if (msg)
{
STAILQ_REMOVE_HEAD(&q->msgl, next);
_bcmos_msgq_stat_dec(q);
}
return msg;
}
/* Put message on queue.
* Must be called under lock!
* Returns error in case of queue overflow
*/
static inline bcmos_errno _bcmos_msg_put(bcmos_msg_queue_nw *q, bcmos_msg *msg, bcmos_msg_send_flags flags)
{
/* Overflow check */
if (q->stat.msg_in >= q->parm.size)
{
if (!(flags & BCMOS_MSG_SEND_NOLIMIT))
{
++q->stat.msg_discarded;
return BCM_ERR_OVERFLOW;
}
}
/* Put onto the relevant queue */
if ((flags & BCMOS_MSG_SEND_URGENT))
STAILQ_INSERT_TAIL(&q->msgl_urg, msg, next);
else
STAILQ_INSERT_TAIL(&q->msgl, msg, next);
_bcmos_msgq_stat_inc(q);
return BCM_ERR_OK;
}
/* Create message queue without wait support */
static void bcmos_msg_queue_nw_init(bcmos_msg_queue_nw *q, const bcmos_msg_queue_parm *parm)
{
q->parm = *parm;
STAILQ_INIT(&q->msgl);
STAILQ_INIT(&q->msgl_urg);
bcmos_fastlock_init(&q->lock, parm->flags);
memset(&q->stat, 0, sizeof(q->stat));
q->flags = 0;
if (!q->parm.size)
q->parm.size = BCMOS_MSG_QUEUE_SIZE_UNLIMITED;
if (!q->parm.high_wm)
q->parm.high_wm = BCMOS_MSG_QUEUE_SIZE_UNLIMITED;
if (!q->parm.low_wm)
q->parm.low_wm = q->parm.high_wm;
if (!q->parm.notify)
q->parm.notify = _bcmos_msgq_notify;
}
/* Destroy message list */
static void bcmos_msg_list_destroy(bcmos_msg_list *l)
{
bcmos_msg *msg, *tmp;
STAILQ_FOREACH_SAFE(msg, l, next, tmp)
{
STAILQ_REMOVE_HEAD(l, next);
bcmos_msg_free(msg);
}
}
#ifdef BCMOS_MSG_QUEUE_REMOTE_SUPPORT
/* Remote queue support - common part of create/destroy */
static bcmos_errno _bcmos_msg_queue_destroy_remote_ep(bcmos_msg_queue *queue)
{
if (queue->q.parm.close)
queue->q.parm.close(queue);
bcmos_mutex_destroy(&queue->send_lock);
if (queue->send_buf)
bcmos_free(queue->send_buf);
if (queue->recv_buf)
bcmos_free(queue->recv_buf);
return BCM_ERR_OK;
}
static bcmos_errno _bcmos_msg_queue_create_remote_ep(bcmos_msg_queue *queue)
{
bcmos_errno rc;
/* Allocate tx and rx buffers */
if (!queue->q.parm.max_mtu)
{
queue->q.parm.max_mtu = BCMOS_MSG_QUEUE_DEFAULT_MAX_MTU;
}
queue->send_buf = bcmos_calloc(queue->q.parm.max_mtu);
if (!queue->send_buf)
{
BCMOS_TRACE_RETURN(BCM_ERR_NOMEM, "Can't allocate send_buf\n");
}
queue->recv_buf = bcmos_calloc(queue->q.parm.max_mtu);
if (!queue->recv_buf)
{
bcmos_free(queue->send_buf);
BCMOS_TRACE_RETURN(BCM_ERR_NOMEM, "Can't allocate recv_buf\n");
}
bcmos_mutex_create(&queue->send_lock, 0, queue->q.parm.name);
switch (queue->q.parm.ep_type)
{
#ifdef BCMOS_MSG_QUEUE_DOMAIN_SOCKET
case BCMOS_MSG_QUEUE_EP_DOMAIN_SOCKET:
rc = bcmos_sys_msg_queue_domain_socket_open(queue);
break;
#endif
#ifdef BCMOS_MSG_QUEUE_UDP_SOCKET
case BCMOS_MSG_QUEUE_EP_UDP_SOCKET:
rc = bcmos_sys_msg_queue_udp_socket_open(queue);
break;
#endif
#ifdef BCMOS_MSG_QUEUE_USER_DEFINED
case BCMOS_MSG_QUEUE_EP_USER_DEFINED:
if (parm.open == NULL || parm.close == NULL || parm.send==NULL || parm.recv == NULL)
{
rc = BCM_ERR_PARM;
break;
}
rc = parm.open(queue);
break;
#endif
default:
rc = BCM_ERR_PARM;
break;
}
if (rc)
{
_bcmos_msg_queue_destroy_remote_ep(queue);
}
return rc;
}
#endif /* #ifdef BCMOS_MSG_QUEUE_REMOTE_SUPPORT */
/* Create message queue. */
bcmos_errno bcmos_msg_queue_create(bcmos_msg_queue *queue, const bcmos_msg_queue_parm *parm)
{
bcmos_errno rc;
if (!queue || !parm)
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "queue %p, parm %p\n", queue, parm);
memset(queue, 0, sizeof(*queue));
queue->q.parm = *parm;
if (parm->ep_type == BCMOS_MSG_QUEUE_EP_LOCAL)
{
rc = bcmos_sem_create(&queue->m, 0, parm->flags, queue->q.parm.name);
if (!rc)
bcmos_msg_queue_nw_init(&queue->q, parm);
}
else
#ifdef BCMOS_MSG_QUEUE_REMOTE_SUPPORT
{
rc = _bcmos_msg_queue_create_remote_ep(queue);
}
#else
{
rc = BCM_ERR_PARM;
}
#endif
if (rc)
return rc;
queue->magic = BCMOS_MSG_QUEUE_VALID;
/* Copy name to make sure that it is not released - in case it was on the stack */
if (queue->q.parm.name)
{
strncpy(queue->name, queue->q.parm.name, sizeof(queue->name) - 1);
queue->q.parm.name = queue->name;
}
bcmos_mutex_lock(&bcmos_res_lock);
STAILQ_INSERT_TAIL(&msg_queue_list, queue, list);
bcmos_mutex_unlock(&bcmos_res_lock);
return BCM_ERR_OK;
}
/* Destroy queue */
bcmos_errno bcmos_msg_queue_destroy(bcmos_msg_queue *queue)
{
bcmos_errno rc = BCM_ERR_OK;
if (!queue || queue->magic != BCMOS_MSG_QUEUE_VALID)
{
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "queue handle is invalid\n");
}
queue->magic = BCMOS_MSG_QUEUE_DELETED;
bcmos_mutex_lock(&bcmos_res_lock);
STAILQ_REMOVE(&msg_queue_list, queue, bcmos_msg_queue, list);
bcmos_mutex_unlock(&bcmos_res_lock);
if (queue->q.parm.ep_type == BCMOS_MSG_QUEUE_EP_LOCAL)
{
bcmos_sem_destroy(&queue->m);
/* Release all pending messages */
bcmos_msg_list_destroy(&queue->q.msgl_urg);
bcmos_msg_list_destroy(&queue->q.msgl);
}
#ifdef BCMOS_MSG_QUEUE_REMOTE_SUPPORT
else
{
rc = _bcmos_msg_queue_destroy_remote_ep(queue);
}
#endif
return rc;
}
/* Get queue info */
bcmos_errno bcmos_msg_queue_query(const bcmos_msg_queue *queue, bcmos_msg_queue_info *info)
{
if (!queue || !info)
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "queue %p, info %p\n", queue, info);
info->stat = queue->q.stat;
info->parm = queue->q.parm;
return BCM_ERR_OK;
}
/* Message queue iterator */
bcmos_errno bcmos_msg_queue_get_next(const bcmos_msg_queue **prev)
{
const bcmos_msg_queue *queue;
if (prev == NULL)
{
return BCM_ERR_PARM;
}
queue = *prev;
if (queue && queue->magic != BCMOS_MSG_QUEUE_VALID)
{
return BCM_ERR_PARM;
}
if (queue)
{
queue = STAILQ_NEXT(queue, list);
}
else
{
queue = STAILQ_FIRST(&msg_queue_list);
}
*prev = queue;
if (!queue)
{
return BCM_ERR_NO_MORE;
}
return BCM_ERR_OK;
}
#ifdef BCMOS_MSG_QUEUE_REMOTE_SUPPORT
/* Pack / unpack message header.
* In the future we might adopt bcmolt_buf service into OS abstraction and use it
* for packing / unpacking.
*/
void bcmos_msg_hdr_pack(const bcmos_msg *msg, uint8_t *buf, uint32_t data_size)
{
uint16_t val16;
uint32_t val32;
val16 = BCMOS_ENDIAN_CPU_TO_BIG_U16(msg->type);
memcpy(buf, &val16, sizeof(val16));
buf[2] = (uint8_t)msg->instance;
buf[3] = (uint8_t)msg->sender;
val32 = BCMOS_ENDIAN_CPU_TO_BIG_U32(data_size);
memcpy(&buf[4], &val32, sizeof(val32));
}
void bcmos_msg_hdr_unpack(const uint8_t *buf, bcmos_msg *msg)
{
uint16_t val16;
uint32_t val32;
memcpy(&val16, buf, sizeof(val16));
val16 = BCMOS_ENDIAN_BIG_TO_CPU_U16(val16);
msg->type = (bcmos_msg_id)val16;
msg->instance = (bcmos_msg_instance)buf[2];
msg->sender = (bcmos_module_id)buf[3];
memcpy(&val32, &buf[4], sizeof(val32));
msg->size = BCMOS_ENDIAN_BIG_TO_CPU_U32(val32); /* can be overwritten by unpacker */
msg->handler = NULL;
msg->send_flags = 0;
}
/* Send message to remote EP wrapper */
static bcmos_errno _bcmos_msg_send_to_remote_ep(bcmos_msg_queue *queue, bcmos_msg *msg, bcmos_msg_send_flags flags)
{
uint8_t *buf = NULL;
uint32_t buf_length = 0;
bcmos_errno rc;
bcmos_mutex_lock(&queue->send_lock);
rc = queue->q.parm.pack(queue, msg, &buf, &buf_length);
rc = rc ? rc : queue->q.parm.send(queue, msg, buf, buf_length);
bcmos_mutex_unlock(&queue->send_lock);
/* Release if sent successfully or if auto-release flag is set */
if (rc == BCM_ERR_OK || !(flags & BCMOS_MSG_SEND_NO_FREE_ON_ERROR))
{
bcmos_msg_free(msg);
}
if (buf && queue->q.parm.free_packed)
{
queue->q.parm.free_packed(queue, buf);
}
if (rc)
{
++queue->q.stat.msg_discarded;
}
else
{
++queue->q.stat.msg_sent;
}
return rc;
}
/* Receive message from remote EP wrapper */
static bcmos_errno _bcmos_msg_recv_from_remote_ep(bcmos_msg_queue *queue, uint32_t timeout, bcmos_msg **msg)
{
uint8_t *buf = NULL;
uint32_t buf_length = 0;
bcmos_errno rc;
rc = queue->q.parm.recv(queue, timeout, &buf, &buf_length);
rc = rc ? rc : queue->q.parm.unpack(queue, buf, buf_length, msg);
if (buf && queue->q.parm.free_packed)
{
queue->q.parm.free_packed(queue, buf);
}
if (!rc)
{
++queue->q.stat.msg_received;
}
return rc;
}
#endif /* BCMOS_MSG_QUEUE_REMOTE_SUPPORT */
/* Send message to queue */
bcmos_errno bcmos_msg_send(bcmos_msg_queue *queue, bcmos_msg *msg, bcmos_msg_send_flags flags)
{
long lock_flags;
bcmos_errno rc;
#ifdef BCMOS_MSG_QUEUE_REMOTE_SUPPORT
if (queue->q.parm.ep_type != BCMOS_MSG_QUEUE_EP_LOCAL)
{
return _bcmos_msg_send_to_remote_ep(queue, msg, flags);
}
#endif
lock_flags = bcmos_fastlock_lock(&queue->q.lock);
rc = _bcmos_msg_put(&queue->q, msg, flags);
if (rc)
{
bcmos_fastlock_unlock(&queue->q.lock, lock_flags);
if (!(flags & BCMOS_MSG_SEND_NO_FREE_ON_ERROR))
{
bcmos_msg_free(msg);
}
BCMOS_TRACE_ERR("Overflow: Queue %s\n", queue->q.parm.name);
return rc;
}
/* Success */
if (queue->is_waiting)
{
/* Kick waiting task */
queue->is_waiting = BCMOS_FALSE;
bcmos_fastlock_unlock(&queue->q.lock, lock_flags);
bcmos_sem_post(&queue->m);
}
else
{
bcmos_fastlock_unlock(&queue->q.lock, lock_flags);
}
return BCM_ERR_OK;
}
/* Send message to module (internal) - doesn't post any semaphores so it's safe to call under a fastlock */
static bcmos_errno _bcmos_msg_send_to_module(
bcmos_module_id module_id,
bcmos_msg *msg,
bcmos_msg_send_flags flags,
bcmos_sem **sem_to_post)
{
bcmos_module *module = _bcmos_module_get(module_id);
bcmos_task *task;
long lock_flags, q_lock_flags;
uint32_t active_modules;
bcmos_errno rc;
*sem_to_post = NULL;
if (unlikely(!module || !msg->handler))
{
if (!module)
{
BCMOS_TRACE_ERR("Module %d doesn't exist\n", module_id);
rc = BCM_ERR_NOENT;
}
else
{
BCMOS_TRACE_ERR("msg->handler is not set. msg->type=%d\n", msg->type);
rc = BCM_ERR_PARM;
}
if (!(flags & BCMOS_MSG_SEND_NO_FREE_ON_ERROR))
{
bcmos_msg_free(msg);
}
return rc;
}
task = module->my_task;
lock_flags = bcmos_fastlock_lock(&task->active_lock);
/* Make sure that the module is not being destroyed */
if (unlikely(module->deleted))
{
BCMOS_TRACE_INFO("Module %d is being destroyed\n", module_id);
rc = BCM_ERR_NOENT;
if (!(flags & BCMOS_MSG_SEND_NO_FREE_ON_ERROR))
{
bcmos_msg_free(msg);
}
bcmos_fastlock_unlock(&task->active_lock, lock_flags);
return rc;
}
q_lock_flags = bcmos_fastlock_lock(&module->msgq.lock);
rc = _bcmos_msg_put(&module->msgq, msg, flags);
if (rc)
{
bcmos_fastlock_unlock(&module->msgq.lock, q_lock_flags);
bcmos_fastlock_unlock(&task->active_lock, lock_flags);
/* Queue overflow */
if (!(flags & BCMOS_MSG_SEND_NO_FREE_ON_ERROR))
bcmos_msg_free(msg);
BCMOS_TRACE_ERR("Overflow: Queue %s\n", module->parm.qparm.name);
return rc;
}
bcmos_fastlock_unlock(&module->msgq.lock, q_lock_flags);
/* Success. Update active_modules task and kick the task */
active_modules = task->active_modules;
task->active_modules |= (1 << module->idx);
bcmos_fastlock_unlock(&task->active_lock, lock_flags);
/* Notify caller to kick task if there is a chance it was waiting */
if (!active_modules)
*sem_to_post = &task->active_sem;
return BCM_ERR_OK;
}
/* Send message to module */
bcmos_errno bcmos_msg_send_to_module(bcmos_module_id module_id, bcmos_msg *msg, bcmos_msg_send_flags flags)
{
bcmos_sem *sem_to_post;
bcmos_errno err = _bcmos_msg_send_to_module(module_id, msg, flags, &sem_to_post);
if (sem_to_post)
bcmos_sem_post(sem_to_post);
return err;
}
/* Get message from the head of message queue */
bcmos_errno bcmos_msg_recv(bcmos_msg_queue *queue, uint32_t timeout, bcmos_msg **msg)
{
long lock_flags;
if (!queue || !msg)
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "queue %p, msg %p\n", queue, msg);
#ifdef BCMOS_MSG_QUEUE_REMOTE_SUPPORT
if (queue->q.parm.ep_type != BCMOS_MSG_QUEUE_EP_LOCAL)
{
return _bcmos_msg_recv_from_remote_ep(queue, timeout, msg);
}
#endif
lock_flags = bcmos_fastlock_lock(&queue->q.lock);
*msg = _bcmos_msg_get(&queue->q);
if (*msg)
{
bcmos_fastlock_unlock(&queue->q.lock, lock_flags);
return BCM_ERR_OK;
}
if (!timeout)
{
bcmos_fastlock_unlock(&queue->q.lock, lock_flags);
return BCM_ERR_NOENT;
}
/* Receive with wait */
queue->is_waiting = BCMOS_TRUE;
bcmos_fastlock_unlock(&queue->q.lock, lock_flags);
/* wait for it */
bcmos_sem_wait(&queue->m, timeout);
lock_flags = bcmos_fastlock_lock(&queue->q.lock);
*msg = _bcmos_msg_get(&queue->q);
queue->is_waiting = BCMOS_FALSE;
bcmos_fastlock_unlock(&queue->q.lock, lock_flags);
if (!*msg)
return BCM_ERR_TIMEOUT;
return BCM_ERR_OK;
}
/*
* Queue group support
*/
/* Create message queue group. */
bcmos_errno bcmos_msg_qgroup_create(bcmos_msg_qgroup *qgroup, const bcmos_msg_qgroup_parm *parm)
{
bcmos_errno rc;
bcmos_qgroup_prty prty;
if (!qgroup || !parm || !parm->nqueues || parm->nqueues>32)
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "queue %p, parm %p nqueues %u\n", qgroup, parm, parm ? parm->nqueues: 0);
memset(qgroup, 0, sizeof(*qgroup));
rc = bcmos_sem_create(&qgroup->m, 0, parm->flags, NULL);
if (rc)
return rc;
qgroup->parm = *parm;
bcmos_fastlock_init(&qgroup->lock, parm->flags);
if (!qgroup->parm.size)
qgroup->parm.size = BCMOS_MSG_QUEUE_SIZE_UNLIMITED;
if (!qgroup->parm.high_wm)
qgroup->parm.high_wm = BCMOS_MSG_QUEUE_SIZE_UNLIMITED;
if (!qgroup->parm.low_wm)
qgroup->parm.low_wm = qgroup->parm.high_wm;
if (!qgroup->parm.notify)
qgroup->parm.notify = _bcmos_qgroup_notify;
qgroup->msgl = bcmos_calloc(sizeof(bcmos_msg_list) * (uint32_t)parm->nqueues);
if (!qgroup->msgl)
{
bcmos_msg_qgroup_destroy(qgroup);
return BCM_ERR_NOMEM;
}
for (prty = 0; prty < qgroup->parm.nqueues; prty++)
{
STAILQ_INIT(&qgroup->msgl[prty]);
}
/* Copy name to make sure that it is not released - in case it was on the stack */
if (qgroup->parm.name)
{
strncpy(qgroup->name, qgroup->parm.name, sizeof(qgroup->parm.name) - 1);
qgroup->parm.name = qgroup->name;
}
qgroup->magic = BCMOS_MSG_QGROUP_VALID;
bcmos_mutex_lock(&bcmos_res_lock);
STAILQ_INSERT_TAIL(&msg_qgroup_list, qgroup, list);
bcmos_mutex_unlock(&bcmos_res_lock);
return BCM_ERR_OK;
}
/** Destroy queue group
*
* \param[in] qgroup Queue group handle
* \returns 0=OK or error code <0
*/
bcmos_errno bcmos_msg_qgroup_destroy(bcmos_msg_qgroup *qgroup)
{
bcmos_qgroup_prty prty;
if (!qgroup || qgroup->magic != BCMOS_MSG_QGROUP_VALID)
{
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "queue group handle is invalid\n");
}
qgroup->magic = BCMOS_MSG_QGROUP_DELETED;
bcmos_mutex_lock(&bcmos_res_lock);
STAILQ_REMOVE(&msg_qgroup_list, qgroup, bcmos_msg_qgroup, list);
bcmos_mutex_unlock(&bcmos_res_lock);
bcmos_sem_destroy(&qgroup->m);
/* Release all pending messages */
if (qgroup->msgl)
{
for (prty = 0; prty < qgroup->parm.nqueues; prty++)
{
bcmos_msg_list_destroy(&qgroup->msgl[prty]);
}
bcmos_free(qgroup->msgl);
}
return BCM_ERR_OK;
}
/** Get queue group info */
bcmos_errno bcmos_msg_qgroup_query(const bcmos_msg_qgroup *qgroup, bcmos_msg_qgroup_info *info)
{
if (!qgroup || !info)
return BCM_ERR_PARM;
info->parm = qgroup->parm;
info->stat = qgroup->stat;
return BCM_ERR_OK;
}
/** Message queue group iterator
* \param[in] prev Previous queue group. *prev==NULL - get first
* \return: BCM_ERR_OK, BCM_ERR_NOENT, BCM_ERR_NO_MORE
*/
bcmos_errno bcmos_msg_qgroup_get_next(const bcmos_msg_qgroup **prev)
{
const bcmos_msg_qgroup *qgrp;
if (prev == NULL)
{
return BCM_ERR_PARM;
}
qgrp = *prev;
if (qgrp && qgrp->magic != BCMOS_MSG_QGROUP_VALID)
{
return BCM_ERR_PARM;
}
if (qgrp)
{
qgrp = STAILQ_NEXT(qgrp, list);
}
else
{
qgrp = STAILQ_FIRST(&msg_qgroup_list);
}
*prev = qgrp;
if (!qgrp)
{
return BCM_ERR_NO_MORE;
}
return BCM_ERR_OK;
}
/* get message from non-empty queue group queue */
static inline bcmos_msg *_bcmos_qgroup_msg_get(bcmos_msg_qgroup *qgroup, bcmos_qgroup_prty prty)
{
bcmos_msg *msg;
msg = STAILQ_FIRST(&qgroup->msgl[prty]);
BUG_ON(!msg);
STAILQ_REMOVE_HEAD(&qgroup->msgl[prty], next);
if (STAILQ_EMPTY(&qgroup->msgl[prty]))
{
qgroup->active_mask &= ~(1 << prty);
}
return msg;
}
/* Send message to queue group */
bcmos_errno bcmos_msg_send_to_qgroup(bcmos_msg_qgroup *qgroup, bcmos_msg *msg, bcmos_qgroup_prty prty,
bcmos_msg_send_flags flags)
{
long lock_flags;
bcmos_errno rc = BCM_ERR_OK;
if (prty >= qgroup->parm.nqueues)
{
if (!(flags & BCMOS_MSG_SEND_NO_FREE_ON_ERROR))
{
bcmos_msg_free(msg);
}
return BCM_ERR_PARM;
}
msg->send_flags = flags;
lock_flags = bcmos_fastlock_lock(&qgroup->lock);
/* Put into the relevant queue */
STAILQ_INSERT_TAIL(&qgroup->msgl[prty], msg, next);
qgroup->active_mask |= (1 << prty);
_bcmos_qgroup_stat_inc(qgroup);
/* Overflow check */
if ((qgroup->stat.msg_in > qgroup->parm.size))
{
bcmos_msg *m;
bcmos_qgroup_prty i;
/* Find the lowest-priority queue with data and discard the head message.
* The loop always finds something because we've just added a message
*/
for (i = qgroup->parm.nqueues - 1; (qgroup->active_mask & (1 << i)) == 0; i--);
m = _bcmos_qgroup_msg_get(qgroup, i);
--qgroup->stat.msg_in;
++qgroup->stat.msg_discarded;
if (!(m->send_flags & BCMOS_MSG_SEND_NO_FREE_ON_ERROR))
{
bcmos_msg_free(m);
}
rc = BCM_ERR_OVERFLOW;
}
/* Kick waiting task */
if (qgroup->is_waiting)
{
qgroup->is_waiting = BCMOS_FALSE;
bcmos_fastlock_unlock(&qgroup->lock, lock_flags);
bcmos_sem_post(&qgroup->m);
}
else
{
bcmos_fastlock_unlock(&qgroup->lock, lock_flags);
}
return rc;
}
/* Get highest priority message from queue group */
bcmos_errno bcmos_msg_recv_from_qgroup(bcmos_msg_qgroup *qgroup, uint32_t timeout, bcmos_msg **msg)
{
long lock_flags;
bcmos_qgroup_prty prty;
if (!qgroup || !msg)
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "qgroup %p, msg %p\n", qgroup, msg);
lock_flags = bcmos_fastlock_lock(&qgroup->lock);
if (!qgroup->active_mask)
{
if (!timeout)
{
bcmos_fastlock_unlock(&qgroup->lock, lock_flags);
return BCM_ERR_NOENT;
}
/* Receive with wait */
qgroup->is_waiting = BCMOS_TRUE;
bcmos_fastlock_unlock(&qgroup->lock, lock_flags);
/* wait for it */
bcmos_sem_wait(&qgroup->m, timeout);
/* Done waiting. Either got a message or a timeout */
lock_flags = bcmos_fastlock_lock(&qgroup->lock);
qgroup->is_waiting = BCMOS_FALSE;
if (!qgroup->active_mask)
{
bcmos_fastlock_unlock(&qgroup->lock, lock_flags);
return BCM_ERR_TIMEOUT;
}
}
prty = (bcmos_qgroup_prty)(ffs(qgroup->active_mask) - 1);
BUG_ON(prty >= qgroup->parm.nqueues);
*msg = _bcmos_qgroup_msg_get(qgroup, prty);
_bcmos_qgroup_stat_dec(qgroup);
bcmos_fastlock_unlock(&qgroup->lock, lock_flags);
return BCM_ERR_OK;
}
/*
* Message registration and dispatch
*/
/* Hash entry */
typedef struct msg_hash_entry msg_hash_entry;
struct msg_hash_entry
{
/* Key */
uint32_t key; /* msg_type + instance */
/* Value */
bcmos_module_id module_id;
F_bcmos_msg_handler handler;
/* List of entries with the same key */
SLIST_ENTRY(msg_hash_entry) list;
};
/* Hash table */
static SLIST_HEAD(msg_hash, msg_hash_entry) msg_hash_table[BCMOS_MSG_HASH_SIZE];
/* Make hash key from msg_type and instance */
static inline uint32_t _bcmos_msg_hash_key(bcmos_msg_id msg_type, bcmos_msg_instance instance)
{
return ((uint32_t)instance << 16) | (uint32_t)msg_type;
}
/* Hash function */
static inline uint32_t _bcmos_msg_hash_func(uint32_t key)
{
key ^= (key >> 9);
key ^= (key << 3);
key ^= (key >> 15);
return key % BCMOS_MSG_HASH_SIZE;
}
/* Find entry in hash */
static inline msg_hash_entry *_bcmos_msg_hash_find(bcmos_msg_id msg_type, bcmos_msg_instance instance)
{
uint32_t key = _bcmos_msg_hash_key(msg_type, instance);
uint32_t hash = _bcmos_msg_hash_func(key);
msg_hash_entry *entry;
SLIST_FOREACH(entry, &msg_hash_table[hash], list)
{
if (entry->key == key)
break;
}
return entry;
}
/* Register message_type+instance --> module+handler */
bcmos_errno bcmos_msg_register(bcmos_msg_id msg_type, bcmos_msg_instance instance,
bcmos_module_id module_id, F_bcmos_msg_handler handler)
{
uint32_t key = _bcmos_msg_hash_key(msg_type, instance);
uint32_t hash = _bcmos_msg_hash_func(key);
msg_hash_entry *entry;
long lock_flags;
if (!handler)
return BCM_ERR_PARM;
entry = bcmos_calloc(sizeof(*entry));
if (!entry)
return BCM_ERR_NOMEM;
entry->key = key;
entry->module_id = module_id;
entry->handler = handler;
lock_flags = bcmos_fastlock_lock(&bcmos_msg_register_lock);
if (_bcmos_msg_hash_find(msg_type, instance) != NULL)
{
bcmos_fastlock_unlock(&bcmos_msg_register_lock, lock_flags);
bcmos_free(entry);
return BCM_ERR_ALREADY;
}
SLIST_INSERT_HEAD(&msg_hash_table[hash], entry, list);
bcmos_fastlock_unlock(&bcmos_msg_register_lock, lock_flags);
return BCM_ERR_OK;
}
bcmos_errno bcmos_msg_unregister(bcmos_msg_id msg_type, bcmos_msg_instance instance, bcmos_module_id module_id)
{
uint32_t key = _bcmos_msg_hash_key(msg_type, instance);
uint32_t hash = _bcmos_msg_hash_func(key);
msg_hash_entry *entry;
long lock_flags;
lock_flags = bcmos_fastlock_lock(&bcmos_msg_register_lock);
entry = _bcmos_msg_hash_find(msg_type, instance);
if (!entry)
{
bcmos_fastlock_unlock(&bcmos_msg_register_lock, lock_flags);
return BCM_ERR_NOENT;
}
if (entry->module_id != module_id)
{
bcmos_fastlock_unlock(&bcmos_msg_register_lock, lock_flags);
return BCM_ERR_INVALID_OP;
}
SLIST_REMOVE(&msg_hash_table[hash], entry, msg_hash_entry, list);
bcmos_fastlock_unlock(&bcmos_msg_register_lock, lock_flags);
bcmos_free(entry);
return BCM_ERR_OK;
}
void bcmos_msg_shutdown_mode_set(bcmos_bool shutdown_mode)
{
bcmos_msg_shutdown_mode = shutdown_mode;
}
bcmos_bool bcmos_msg_shutdown_mode_get(void)
{
return bcmos_msg_shutdown_mode;
}
/* Dispatch message to registered module */
bcmos_errno bcmos_msg_dispatch(bcmos_msg *msg, bcmos_msg_send_flags flags)
{
bcmos_errno err;
if (unlikely(bcmos_msg_shutdown_mode))
{
/* In shutdown mode, we need to acquire the same lock used to protect bcmos_msg_register() /
* bcmos_msg_unregister(), since we must support calling these functions concurrently. */
msg_hash_entry *entry;
bcmos_sem *sem_to_post = NULL;
long lock_flags = bcmos_fastlock_lock(&bcmos_msg_register_lock);
entry = _bcmos_msg_hash_find(msg->type, msg->instance);
if (entry)
{
msg->handler = entry->handler;
err = _bcmos_msg_send_to_module(entry->module_id, msg, flags, &sem_to_post);
}
else
{
/* Not found. Release automatically if requested. */
if (!(flags & BCMOS_MSG_SEND_NO_FREE_ON_ERROR))
bcmos_msg_free(msg);
err = BCM_ERR_OK;
}
bcmos_fastlock_unlock(&bcmos_msg_register_lock, lock_flags);
if (sem_to_post)
bcmos_sem_post(sem_to_post);
}
else
{
msg_hash_entry *entry = _bcmos_msg_hash_find(msg->type, msg->instance);
if (entry)
{
msg->handler = entry->handler;
err = bcmos_msg_send_to_module(entry->module_id, msg, flags);
}
else
{
/* Not found. Release automatically if requested. */
BCMOS_TRACE_ERR("Can't dispatch unregistered msg %d:%d\n", msg->type, msg->instance);
if (!(flags & BCMOS_MSG_SEND_NO_FREE_ON_ERROR))
bcmos_msg_free(msg);
err = BCM_ERR_NOENT;
}
}
return err;
}
/*
* Task management
*/
/*
* Default task handler
*/
/*lint -e{632,633,634}
* There are a few warnings about
* implicit bcmos_errno conversion to int. It is to bothersome now
* to change task handler prototype everywhere and the warning is harmless
*/
int bcmos_dft_task_handler(long data)
{
bcmos_task *task = (bcmos_task *)data;
long flags = 0, q_flags = 0;
uint32_t active_modules;
int last_module = 0; /* 1-based last handled module index */
bcmos_module *module;
bcmos_msg *msg;
bcmos_errno rc;
int rc_int;
/* Set / validate task timeout */
rc = bcmos_task_timeout_set(task, task->parm.msg_wait_timeout, task->parm.timeout_handler);
if (rc)
return (int)rc;
/* Call init callback if any */
if (task->parm.init_handler)
{
rc_int = task->parm.init_handler(task->parm.data);
if (rc_int)
{
BCMOS_TRACE_ERR("Task %s: init_handler returned error %s (%d)\n",
task->parm.name, bcmos_strerror((bcmos_errno)rc_int), rc_int);
bcmos_task_destroy(task);
return rc_int;
}
}
/* Wait for module activity */
while (!task->destroy_request)
{
task->current_module = BCMOS_MODULE_ID_NONE;
/* Wait for module activity */
rc = bcmos_sem_wait(&task->active_sem, task->parm.msg_wait_timeout);
if (rc == BCM_ERR_TIMEOUT)
{
F_bcmos_task_handler timeout_handler = task->parm.timeout_handler;
/* Handle possible race condition */
if (!timeout_handler)
continue;
rc_int = timeout_handler(data);
if (rc_int)
{
BCMOS_TRACE_ERR("Task %s: terminated by timeout_handler. error %s (%d)\n",
task->parm.name, bcmos_strerror((bcmos_errno)rc_int), rc_int);
break;
}
/* Keep waiting */
continue;
}
/* RR active modules */
do
{
flags = bcmos_fastlock_lock(&task->active_lock);
active_modules = (task->active_modules >> last_module);
if (!active_modules)
{
last_module = 0;
active_modules = task->active_modules;
if (!active_modules)
{
/* No modules with work to do */
bcmos_fastlock_unlock(&task->active_lock, flags);
continue;
}
}
last_module += ffs(active_modules);
BUG_ON(last_module > BCMOS_MAX_MODULES_PER_TASK);
module = task->modules[last_module - 1];
BUG_ON(!module);
q_flags = bcmos_fastlock_lock(&module->msgq.lock);
/* Get message from the module's message queue */
msg = _bcmos_msg_get(&module->msgq);
if (!msg)
{
bcmos_fastlock_unlock(&module->msgq.lock, q_flags);
task->active_modules &= ~(1 << (last_module - 1));
bcmos_fastlock_unlock(&task->active_lock, flags);
continue;
}
bcmos_fastlock_unlock(&module->msgq.lock, q_flags);
bcmos_fastlock_unlock(&task->active_lock, flags);
/* Handle the message */
if (msg->handler)
{
task->current_module = module->id;
msg->handler(module->id, msg);
}
else
{
BCMOS_TRACE_ERR("msg->handler is not set. msg->type=%d\n", msg->type);
bcmos_msg_free(msg);
}
} while (task->active_modules);
}
return 0;
}
/* Set task message timeout.
* The function is only supported in integration mode
*/
bcmos_errno bcmos_task_timeout_set(bcmos_task *task, uint32_t timeout, F_bcmos_task_handler timeout_handler)
{
if (task->parm.handler)
{
BCMOS_TRACE_ERR("%s: The function is only supported in integration mode (task handler == NULL)\n", task->parm.name);
return BCM_ERR_NOT_SUPPORTED;
}
if ((timeout && timeout != BCMOS_WAIT_FOREVER) && !timeout_handler)
{
BCMOS_TRACE_ERR("%s: timeout_handler is not set\n", task->parm.name);
return BCM_ERR_PARM;
}
/* 0 means FOREVER here */
if (!timeout)
timeout = BCMOS_WAIT_FOREVER;
task->parm.timeout_handler = timeout_handler;
task->parm.msg_wait_timeout = timeout;
return BCM_ERR_OK;
}
/*
* Module
*/
/* Register module */
bcmos_errno bcmos_module_create(bcmos_module_id module_id, bcmos_task *task, bcmos_module_parm *parm)
{
bcmos_module *module;
bcmos_errno rc = BCM_ERR_OK;
int i;
if ((unsigned)module_id >= (unsigned)BCMOS_MODULE_ID__NUM_OF || !parm)
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "module %d, parm %p\n", module_id, parm);
if (!task)
BCMOS_TRACE_RETURN(BCM_ERR_NOT_SUPPORTED, "No task\n");
if (bcmos_modules[module_id])
BCMOS_TRACE_RETURN(BCM_ERR_ALREADY, "module_id %d\n", module_id);
module = bcmos_calloc(sizeof(bcmos_module));
if (!module)
BCMOS_TRACE_RETURN(BCM_ERR_NOMEM, "module_id %d\n", module_id);
module->id = module_id;
module->my_task = task;
module->parm = *parm;
module->context = (void *)parm->data;
bcmos_msg_queue_nw_init(&module->msgq, &parm->qparm);
/* Copy name to make sure that it is not released - in case it was on the stack */
if (module->parm.qparm.name)
{
strncpy(module->name, module->parm.qparm.name, sizeof(module->name) - 1);
module->parm.qparm.name = module->name;
}
/* Assign module id */
for (i = 0; i < BCMOS_MAX_MODULES_PER_TASK; i++)
{
if (!task->modules[i])
{
task->modules[i] = module;
module->idx = i;
break;
}
}
if (i == BCMOS_MAX_MODULES_PER_TASK)
{
bcmos_free(module);
BCMOS_TRACE_RETURN(BCM_ERR_TOO_MANY, "module_id %d\n", module_id);
}
bcmos_modules[module_id] = module;
/* Init module */
if (parm->init)
{
rc = parm->init(parm->data);
}
#ifdef BCMOS_HEALTH_CHECK_ENABLED
if (rc == BCM_ERR_OK)
{
rc = bcmos_module_health_check_init(module);
}
#endif
if (rc)
{
bcmos_module_destroy(module_id);
}
return rc;
}
/* Un-register module */
bcmos_errno bcmos_module_destroy(bcmos_module_id module_id)
{
bcmos_module *module = _bcmos_module_get(module_id);
bcmos_task *task;
long lock_flags, q_lock_flags;
bcmos_msg_list msgl_urg, msgl;
if (!module)
BCMOS_TRACE_RETURN(BCM_ERR_NOENT, "module_id %d\n", module_id);
module->deleted = BCMOS_TRUE;
task = module->my_task;
lock_flags = bcmos_fastlock_lock(&task->active_lock);
task->modules[module->idx] = NULL;
task->active_modules &= ~(1 << module->idx);
/* Because we are not allowed to free memory (via bcmos_free()) when interrupts are locked, we only empty the linked list (via SLIST_INIT()) and the free comes outside the locked
* section. */
q_lock_flags = bcmos_fastlock_lock(&module->msgq.lock);
msgl_urg = module->msgq.msgl_urg;
msgl = module->msgq.msgl;
STAILQ_INIT(&module->msgq.msgl_urg);
STAILQ_INIT(&module->msgq.msgl);
bcmos_fastlock_unlock(&module->msgq.lock, q_lock_flags);
bcmos_fastlock_unlock(&task->active_lock, lock_flags);
bcmos_msg_list_destroy(&msgl_urg);
bcmos_msg_list_destroy(&msgl);
#ifdef BCMOS_HEALTH_CHECK_ENABLED
bcmos_module_health_check_destroy(module_id);
#endif
if (module->parm.exit)
module->parm.exit(module->parm.data);
bcmos_modules[module_id] = NULL;
bcmos_free(module);
return BCM_ERR_OK;
}
/* Get current module id in the current task */
bcmos_module_id bcmos_module_current(void)
{
bcmos_task *task = bcmos_task_current();
if (!task)
return BCMOS_MODULE_ID_NONE;
return task->current_module;
}
/* Get module context set by bcmos_module_context_set().
This function can be called even while module is being destroyed */
void *bcmos_module_context(bcmos_module_id module_id)
{
bcmos_module *module = _bcmos_module_get(module_id);
if (!module)
return NULL;
return module->context;
}
/* Set module context */
bcmos_errno bcmos_module_context_set(bcmos_module_id module_id, void *context)
{
bcmos_module *module = _bcmos_module_get(module_id);
if (!module)
BCMOS_TRACE_RETURN(BCM_ERR_NOENT, "module_id %d\n", module_id);
module->context = context;
return BCM_ERR_OK;
}
/* Query module info */
bcmos_errno bcmos_module_query(bcmos_module_id module_id, const bcmos_task **task, bcmos_msg_queue_info *info)
{
bcmos_module *module = _bcmos_module_get(module_id);
if (!module)
{
return BCM_ERR_NOENT;
}
if (task)
{
*task = module->my_task;
}
if (info)
{
info->parm = module->parm.qparm;
info->stat = module->msgq.stat;
}
return BCM_ERR_OK;
}
/* Check that all created modules have a name assigned*/
bcmos_errno bcmos_modules_name_check(void)
{
bcmos_errno rc = BCM_ERR_OK;
bcmos_module_id m;
/* Ensure that all registered modules have names */
for (m = (bcmos_module_id)(BCMOS_MODULE_ID_NONE + 1); m < BCMOS_MODULE_ID__NUM_OF; m++)
{
bcmos_module *module = _bcmos_module_get(m);
if (module != NULL && module->name[0] == '\0')
{
BCMOS_TRACE_ERR("Module %d does not have a name\n", m);
rc = BCM_ERR_PARM;
}
}
return rc;
}
/*
* Events
*/
/* This function handles event arrival in module context */
static void _bcmos_ev_in_module_handler(bcmos_module_id module_id, bcmos_msg *msg)
{
bcmos_event *ev = _bcmos_msg_to_event(msg);
uint32_t active_bits;
long lock_flags;
active_bits = ev->active_bits & ev->parm.mask;
lock_flags = bcmos_fastlock_lock(&ev->lock);
ev->active_bits &= ~active_bits;
ev->is_waiting = BCMOS_TRUE;
bcmos_fastlock_unlock(&ev->lock, lock_flags);
ev->parm.handler(ev->id, active_bits);
}
/* Release event message. Only called in exceptional situations,
* such as module queue destroy. Do nothing.
*/
static void _bcmos_ev_msg_release(bcmos_msg *msg)
{
}
/* Create event set */
bcmos_errno bcmos_event_create(bcmos_event_id event_id, bcmos_event_parm *parm)
{
bcmos_event *ev;
bcmos_module *module = NULL;
bcmos_errno rc;
if ((unsigned)event_id >= (unsigned)BCMOS_EVENT_ID__NUM_OF)
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "event_id %d\n", event_id);
if (_bcmos_event_get(event_id))
BCMOS_TRACE_RETURN(BCM_ERR_ALREADY, "event_id %d\n", event_id);
if (parm && parm->module_id != BCMOS_MODULE_ID_NONE)
{
module = _bcmos_module_get(parm->module_id);
if (!module)
BCMOS_TRACE_RETURN(BCM_ERR_NOENT, "module_id %d\n", parm->module_id);
if (!parm->handler || !parm->mask)
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "event_id %d, handler %p, mask %x\n", event_id, parm->handler, parm->mask);
}
ev = bcmos_calloc(sizeof(bcmos_event));
if (!ev)
BCMOS_TRACE_RETURN(BCM_ERR_NOMEM, "event_id %d\n", event_id);
ev->id = event_id;
if (parm)
ev->parm = *parm;
bcmos_fastlock_init(&ev->lock, ev->parm.flags);
{
rc = bcmos_sem_create(&ev->m, 0, ev->parm.flags, ev->parm.name);
if (rc)
{
bcmos_free(ev);
return rc;
}
}
/* Initialize event message in integration mode */
if (ev->parm.module_id != BCMOS_MODULE_ID_NONE)
{
ev->msg.handler = _bcmos_ev_in_module_handler;
ev->msg.release = _bcmos_ev_msg_release;
ev->msg.sender = BCMOS_MODULE_ID_NONE;
ev->msg.type = BCMOS_MSG_ID_INTERNAL_EVENT;
ev->is_waiting = BCMOS_TRUE;
}
/* Copy name to make sure that it is not released - in case it was on the stack */
if (ev->parm.name)
{
strncpy(ev->name, ev->parm.name, sizeof(ev->name) - 1);
ev->parm.name = ev->name;
}
bcmos_events[event_id] = ev;
return BCM_ERR_OK;
}
/* Destroy event set created by bcmos_event_create() */
bcmos_errno bcmos_event_destroy(bcmos_event_id event_id)
{
bcmos_event *ev = _bcmos_event_get(event_id);
if (!ev)
BCMOS_TRACE_RETURN(BCM_ERR_NOENT, "event_id %d\n", event_id);
bcmos_events[event_id] = NULL;
bcmos_sem_destroy(&ev->m);
bcmos_free(ev);
return BCM_ERR_OK;
}
/* Raise event */
bcmos_errno bcmos_event_raise(bcmos_event_id event_id, uint32_t active_bits)
{
bcmos_event *ev = _bcmos_event_get(event_id);
long lock_flags;
if (!ev)
BCMOS_TRACE_RETURN(BCM_ERR_NOENT, "event_id %d\n", event_id);
lock_flags = bcmos_fastlock_lock(&ev->lock);
ev->active_bits |= active_bits;
if (ev->is_waiting && (ev->active_bits & ev->parm.mask))
{
ev->is_waiting = BCMOS_FALSE;
bcmos_fastlock_unlock(&ev->lock, lock_flags);
if (ev->parm.module_id != BCMOS_MODULE_ID_NONE)
bcmos_msg_send_to_module(ev->parm.module_id, &ev->msg, (bcmos_msg_send_flags)(BCMOS_MSG_SEND_URGENT | BCMOS_MSG_SEND_NOLIMIT));
else
bcmos_sem_post(&ev->m);
}
else
{
bcmos_fastlock_unlock(&ev->lock, lock_flags);
}
return BCM_ERR_OK;
}
/* Wait for event */
bcmos_errno bcmos_event_recv(bcmos_event_id event_id, uint32_t mask,
uint32_t timeout, uint32_t *active_bits)
{
bcmos_event *ev = _bcmos_event_get(event_id);
long lock_flags;
BUG_ON(!active_bits);
if (!ev)
BCMOS_TRACE_RETURN(BCM_ERR_NOENT, "event_id %d is not registered\n", event_id);
lock_flags = bcmos_fastlock_lock(&ev->lock);
*active_bits = ev->active_bits & mask;
if (*active_bits)
{
ev->active_bits &= ~ *active_bits;
bcmos_fastlock_unlock(&ev->lock, lock_flags);
return BCM_ERR_OK;
}
if (!timeout)
{
bcmos_fastlock_unlock(&ev->lock, lock_flags);
return BCM_ERR_NOENT;
}
/* recv with wait */
ev->is_waiting = BCMOS_TRUE;
bcmos_fastlock_unlock(&ev->lock, lock_flags);
/* wait for it */
bcmos_sem_wait(&ev->m, timeout);
/* Either got event or timeout */
lock_flags = bcmos_fastlock_lock(&ev->lock);
*active_bits = ev->active_bits & mask;
ev->active_bits &= ~ *active_bits;
ev->is_waiting = BCMOS_FALSE;
bcmos_fastlock_unlock(&ev->lock, lock_flags);
/* If we wait forever and we got an event that does not match the mask we wait on (this is the only possible reason getting here if waiting forever), then we
* want to avoid returning BCM_ERR_TIMEOUT - it's not an error. */
if (timeout != BCMOS_WAIT_FOREVER && !*active_bits)
return BCM_ERR_TIMEOUT;
return BCM_ERR_OK;
}
/*
* Timer
*/
/* compare timestamps minding wrap-around
* returns delta >= 0 if ts1 >= ts2
*/
static inline int32_t _bcmos_timer_ts_delta(uint32_t ts1, uint32_t ts2)
{
int32_t delta = (int)(ts1 - ts2);
return delta;
}
static int32_t _bcmos_timer_compare(struct bcmos_timer *t1, struct bcmos_timer *t2)
{
int32_t delta = _bcmos_timer_ts_delta(t1->expire_at, t2->expire_at);
#if defined(BCMOS_TIMER_RB_TREE) && !defined(BCMOS_TIMER_RB_TREE_LIST)
/* FreeBSD RB tree implementation doesn't support 2 nodes with the same key */
if (!delta)
delta = 1;
#endif
return delta;
}
static inline void _bcmos_start_system_timer(bcmos_timer *head)
{
if (head)
{
int32_t delay = _bcmos_timer_ts_delta(head->expire_at, bcmos_timestamp());
/* Handle rare race condition when next timer expired while we were fiddling
* with the pool. Just give it 1 more "tick". System handler handles all timers
* expired (<now .. now + PRECISION/2)
*/
if (delay <= 0)
{
delay = BCMOS_TIMER_PRECISION_US / 2;
}
bcmos_sys_timer_start(&tmr_pool.sys_timer, delay);
}
else
{
bcmos_sys_timer_stop(&tmr_pool.sys_timer);
}
}
/*
* Timer pool: RB tree or TAILQ-based implementation
*/
static void _bcmos_timer_pool_insert(bcmos_timer *timer, uint32_t delay, bcmos_bool start_sys_timer)
{
long flags;
bcmos_timer *head;
flags = bcmos_fastlock_lock(&tmr_pool.lock);
if (BCMOS_TIMER_IS_RUNNING(timer))
{
bcmos_fastlock_unlock(&tmr_pool.lock, flags);
return;
}
timer->period = timer->parm.periodic ? delay : 0;
timer->expire_at = BCMOS_ROUND_UP(bcmos_timestamp() + delay, BCMOS_TIMER_PRECISION_US / 2);
TMR_POOL_INSERT(&tmr_pool, timer);
timer->flags &= ~BCMOS_TIMER_FLAG_EXPIRED;
timer->flags |= BCMOS_TIMER_FLAG_RUNNING;
/* If new timer is at the top - kick system timer */
if (start_sys_timer)
{
head = TMR_POOL_FIRST(&tmr_pool);
if (timer == head)
{
_bcmos_start_system_timer(head);
}
}
bcmos_fastlock_unlock(&tmr_pool.lock, flags);
}
static void _bcmos_timer_stop(bcmos_timer *timer)
{
long flags;
bcmos_bool was_top;
bcmos_msg_queue_nw *queue;
/* First take running timer out of the active pool */
flags = bcmos_fastlock_lock(&tmr_pool.lock);
timer->period = 0; /* Prevent periodic timer restart */
if (BCMOS_TIMER_IS_RUNNING(timer))
{
timer->flags &= ~BCMOS_TIMER_FLAG_RUNNING;
was_top = (timer == TMR_POOL_FIRST(&tmr_pool));
TMR_POOL_REMOVE(&tmr_pool, timer);
/* If timer was the top - stop/restart system timer */
if (was_top)
{
_bcmos_start_system_timer(TMR_POOL_FIRST(&tmr_pool));
}
}
bcmos_fastlock_unlock(&tmr_pool.lock, flags);
/* Now timer is not in the active pool. Perhaps it is already in
* destination module's queue. Take it out if yes.
*/
queue = timer->queue;
if (queue)
{
flags = bcmos_fastlock_lock(&queue->lock);
/* Check queue again because the previous check was unprotected */
if (timer->queue)
{
bcmos_msg_list *msg_list = ((timer->parm.flags & BCMOS_TIMER_PARM_FLAGS_NON_URGENT))
? &queue->msgl : &queue->msgl_urg;
if (STAILQ_REMOVE_SAFE(msg_list, &timer->msg, bcmos_msg, next) != NULL)
{
_bcmos_msgq_stat_dec(queue);
}
timer->queue = NULL;
}
timer->flags &= ~BCMOS_TIMER_FLAG_EXPIRED;
bcmos_fastlock_unlock(&queue->lock, flags);
}
/* If timer has already expired and we weren't able to stop it -
* wait for expiration callback to finish before leaving _bcmos_timer_stop()
*/
if (BCMOS_TIMER_IS_EXPIRED(timer))
{
bcmos_task *t = bcmos_task_current();
/* Skip wait if timer is being stopped from the owner's task context */
if (t != NULL && t != timer->owner_task && t != timer->task)
{
while (BCMOS_TIMER_IS_EXPIRED(timer) && BCMOS_TIMER_IS_VALID(timer))
{
bcmos_usleep(1000);
}
timer->flags &= ~BCMOS_TIMER_FLAG_EXPIRED;
}
}
}
/* System timer expiration handler.
* Execute all timers that expired and restart system timer
*/
static void _sys_timer_handler(void *data)
{
bcmos_timer_pool *pool = (bcmos_timer_pool *)data;
bcmos_timer *timer;
bcmos_timer_rc rc;
long flags;
BUG_ON(pool != &tmr_pool);
if (!pool->sys_timer_task_set)
{
pool->sys_timer_task = bcmos_task_current();
pool->sys_timer_task_set = BCMOS_TRUE;
}
flags = bcmos_fastlock_lock(&pool->lock);
while ((timer=TMR_POOL_FIRST(pool)) != NULL)
{
/* Stop when reached timer that hasn't expired yet */
if (_bcmos_timer_ts_delta(timer->expire_at, bcmos_timestamp()) > BCMOS_TIMER_PRECISION_US / 2)
break;
timer->flags |= BCMOS_TIMER_FLAG_EXPIRED;
timer->flags &= ~BCMOS_TIMER_FLAG_RUNNING;
timer->task = pool->sys_timer_task;
/* IT: Barrier here ? */
TMR_POOL_REMOVE(pool, timer);
/* Execute handler. Unlock first and re-lock in the end
* It is safe to unlock here because the top loop starts from MIN every time
*/
bcmos_fastlock_unlock(&pool->lock, flags);
rc = timer->handler(timer, timer->parm.data);
if (!timer->parm.owner)
{
if (rc == BCMOS_TIMER_OK && timer->period)
{
uint32_t interval = timer->period;
/* coverity[missing_lock] - it's OK to be unlocked here */
timer->period = 0;
_bcmos_timer_pool_insert(timer, interval, BCMOS_FALSE);
}
else
{
timer->flags &= ~BCMOS_TIMER_FLAG_EXPIRED;
}
}
flags = bcmos_fastlock_lock(&pool->lock);
}
/* Finally kick system timer */
_bcmos_start_system_timer(timer);
bcmos_fastlock_unlock(&pool->lock, flags);
}
/* Send timer expiration to the target module as urgent message.
* _bcmos_timer_in_module_handler() will get called in the module context
*/
static bcmos_timer_rc _bcmos_timer_send_to_module_handler(bcmos_timer *timer, long data)
{
bcmos_errno rc;
bcmos_module *module = _bcmos_module_get(timer->parm.owner);
bcmos_msg_send_flags send_flags;
if (!module)
{
/* Shouldn't happen, unless the module was destroyed */
BCMOS_TRACE_ERR("_bcmos_timer_send_to_module_handler() -- no module=%u (timer->parm.handler=0x%p)\n", timer->parm.owner, timer->parm.handler);
timer->flags &= ~BCMOS_TIMER_FLAG_EXPIRED;
return BCMOS_TIMER_STOP; /* will restart in module context if necessary */
}
timer->queue = &module->msgq;
send_flags = BCMOS_MSG_SEND_NOLIMIT;
if (!((timer->parm.flags & BCMOS_TIMER_PARM_FLAGS_NON_URGENT)))
send_flags |= BCMOS_MSG_SEND_URGENT;
rc = bcmos_msg_send_to_module(timer->parm.owner, &timer->msg, send_flags);
if (rc)
{
/* Shouldn't happen, unless the module was destroyed. Very short race condition here */
timer->queue = NULL;
timer->flags &= ~BCMOS_TIMER_FLAG_EXPIRED;
BCMOS_TRACE_INFO("_bcmos_timer_send_to_module_handler() --> %d\n", rc);
}
return BCMOS_TIMER_STOP; /* will restart in module context if necessary */
}
/* This function handles timer expiration in module context */
static void _bcmos_timer_in_module_handler(bcmos_module_id module_id, bcmos_msg *msg)
{
bcmos_timer *timer = _bcmos_msg_to_timer(msg);
bcmos_module *module = _bcmos_module_get(timer->parm.owner);
bcmos_task *prev_timer_task = timer->task;
bcmos_timer_rc rc;
/* Call timer's callback function and restart the timer if necessary */
timer->queue = NULL;
/* module can't be NULL here. it is checked anyway to keep static code analyzer happy */
if (module)
timer->task = module->my_task;
rc = timer->parm.handler(timer, timer->parm.data);
timer->task = prev_timer_task;
if (rc == BCMOS_TIMER_OK && timer->period)
_bcmos_timer_pool_insert(timer, timer->period, BCMOS_TRUE);
else
timer->flags &= ~BCMOS_TIMER_FLAG_EXPIRED;
}
/* Release timer message. Only called in exceptional situations,
* such as module queue destroy. Do nothing
*/
static void _bcmos_timer_msg_release(bcmos_msg *msg)
{
}
/* Create timer */
bcmos_errno bcmos_timer_create(bcmos_timer *timer, bcmos_timer_parm *parm)
{
if (!timer || !parm || !parm->handler)
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "timer %p, parm %p handler %p\n", timer, parm, parm ? parm->handler : NULL);
memset(timer, 0, sizeof(bcmos_timer));
timer->parm = *parm;
if (parm->owner == BCMOS_MODULE_ID_NONE)
timer->handler = parm->handler;
else
{
bcmos_module *m = _bcmos_module_get(parm->owner);
BCMOS_TRACE_CHECK_RETURN(m == NULL, BCM_ERR_NOENT, "module_id %d\n", parm->owner);
timer->owner_task = m->my_task;
timer->handler = _bcmos_timer_send_to_module_handler;
timer->msg.handler = _bcmos_timer_in_module_handler;
timer->msg.release = _bcmos_timer_msg_release;
timer->msg.sender = BCMOS_MODULE_ID_NONE;
timer->msg.type = BCMOS_MSG_ID_INTERNAL_TIMER;
}
timer->flags |= BCMOS_TIMER_FLAG_VALID;
#ifdef BCMOS_TIMER_DEBUG
bcmos_mutex_lock(&bcmos_res_lock);
timer->magic = BCMOS_TIMER_MAGIC;
STAILQ_INSERT_TAIL(&timer_list, timer, list);
bcmos_mutex_unlock(&bcmos_res_lock);
#endif
return BCM_ERR_OK;
}
/* Destroy timer */
void bcmos_timer_destroy(bcmos_timer *timer)
{
BUG_ON(!timer);
#ifdef BCMOS_TIMER_DEBUG
BUG_ON(timer->magic != BCMOS_TIMER_MAGIC);
#endif
bcmos_timer_stop(timer);
timer->flags &= ~BCMOS_TIMER_FLAG_VALID;
#ifdef BCMOS_TIMER_DEBUG
bcmos_mutex_lock(&bcmos_res_lock);
timer->magic = BCMOS_TIMER_MAGIC_DESTROYED;
STAILQ_REMOVE(&timer_list, timer, bcmos_timer, list);
bcmos_mutex_unlock(&bcmos_res_lock);
#endif
}
/* (Re)start timer */
void bcmos_timer_start(bcmos_timer *timer, uint32_t delay)
{
BUG_ON(!timer);
if (!BCMOS_TIMER_IS_VALID(timer))
{
BCMOS_TRACE_ERR("Timer is invalid\n");
return;
}
if ((int32_t)delay < 0)
{
BCMOS_TRACE_ERR("Attempt to start timer (%s) for period (%u) longer than 2^31-1. Reduced to 2^31-1\n",
timer->parm.name ? timer->parm.name : "*unnamed*", delay);
delay = 0x7fffffff;
}
if (BCMOS_TIMER_IS_RUNNING(timer) || BCMOS_TIMER_IS_EXPIRED(timer))
{
_bcmos_timer_stop(timer);
}
_bcmos_timer_pool_insert(timer, delay, BCMOS_TRUE);
}
/* Stop timer if running */
void bcmos_timer_stop(bcmos_timer *timer)
{
BUG_ON(!timer);
_bcmos_timer_stop(timer);
}
/** Set timer handler */
bcmos_errno bcmos_timer_handler_set(bcmos_timer *timer, F_bcmos_timer_handler handler, long data)
{
BUG_ON(!timer);
BUG_ON(!handler);
timer->parm.handler = handler;
timer->parm.data = data;
if (timer->parm.owner == BCMOS_MODULE_ID_NONE)
timer->handler = handler;
return BCM_ERR_OK;
}
#ifdef BCMOS_TIMER_DEBUG
/* Query timer info */
bcmos_errno bcmos_timer_query(const bcmos_timer *timer, bcmos_timer_parm *parm)
{
if (timer == NULL || timer->magic != BCMOS_TIMER_MAGIC || parm == NULL)
{
return BCM_ERR_PARM;
}
*parm = timer->parm;
return BCM_ERR_OK;
}
/** Timer iterator
* \param[in] prev Previous timer. *prev==NULL - get first
* \return: BCM_ERR_OK, BCM_ERR_NOENT, BCM_ERR_NO_MORE
*/
bcmos_errno bcmos_timer_get_next(bcmos_timer **prev)
{
bcmos_timer *timer;
if (prev == NULL)
{
return BCM_ERR_PARM;
}
timer = *prev;
if (timer && timer->magic != BCMOS_TIMER_MAGIC)
{
return BCM_ERR_PARM;
}
if (timer)
{
timer = STAILQ_NEXT(timer, list);
}
else
{
timer = STAILQ_FIRST(&timer_list);
}
*prev = timer;
if (!timer)
{
return BCM_ERR_NO_MORE;
}
return BCM_ERR_OK;
}
#endif
/*
* Block memory pool
*/
/* Memory block structure:
* - bcmos_memblk
* - blk_size bytes of user data
* - [magic - for block overflow-corruption check]
* - [padding to align to pointer size]
*/
struct bcmos_memblk
{
STAILQ_ENTRY(bcmos_memblk) next; /**< Next block pointer */
bcmos_blk_pool *pool; /** pool that owns the block */
#ifdef BCMOS_MEM_CHECK
uint32_t magic; /** magic number */
#define BCMOS_MEM_MAGIC_ALLOC (('m'<<24) | ('b' << 16) | ('l' << 8) | 'k')
#define BCMOS_MEM_MAGIC_FREE (('m'<<24) | ('b' << 16) | ('l' << 8) | '~')
#define BCMOS_MEM_MAGIC_SUFFIX (('m'<<24) | ('b' << 16) | ('l' << 8) | 's')
#endif
#ifdef BCMOS_BLK_POOL_DEBUG
DLIST_ENTRY(bcmos_memblk) list;
const char *func; /** function name where the block was allocated/released. */
int line; /** line number where the block was allocated/released. */
#endif
};
/* Create byte memory pool */
bcmos_errno bcmos_blk_pool_create(bcmos_blk_pool *pool, const bcmos_blk_pool_parm *parm)
{
uint32_t blk_size;
if (!pool || !parm || !parm->blk_size)
{
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "pool %p, parm %p, blk_size=%u, num_blks=%u\n",
pool, parm, parm ? parm->blk_size : 0, parm ? parm->num_blks : 0);
}
if (parm->num_blks & parm->pool_size)
{
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "One and only one of num_blks (%u) and pool_size (%u) must be set\n",
parm->num_blks, parm->pool_size);
}
if (parm->num_blks && parm->start != NULL)
{
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "num_blks!=0 can't be used with start!=NULL. Use byte size instead\n");
}
BCM_MEMZERO_STRUCT(pool);
pool->parm = *parm;
/* Copy name to make sure that it is not released - in case it was on the stack */
if (pool->parm.name)
{
strncpy(pool->name, pool->parm.name, sizeof(pool->name) - 1);
pool->parm.name = pool->name;
}
/*
* Calculate total block size in bytes, including overheads
*/
/* Round up block size to the nearest 32-bit word to make MAGIC check cheaper.
* It doesn't affect the actual overhead size because of the final
* rounding up to pointer size.
*/
pool->parm.blk_size = BCMOS_ROUND_UP(pool->parm.blk_size, sizeof(uint32_t));
blk_size = pool->parm.blk_size + sizeof(bcmos_memblk);
#ifdef BCMOS_MEM_CHECK
blk_size += sizeof(uint32_t); /* room for magic after user data block */
#endif
blk_size = BCMOS_ROUND_UP(blk_size, sizeof(void *));
/* Derive num_blks / pool_size from one another */
if (pool->parm.num_blks)
{
pool->parm.pool_size = parm->num_blks * blk_size;
}
else
{
pool->parm.num_blks = pool->parm.pool_size / blk_size;
if (!pool->parm.num_blks)
{
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "pool_size (%u) is too small\n", parm->pool_size);
}
}
/* Allocate memory for the pool if "start" is not set */
pool->start = pool->parm.start;
if (!pool->start)
{
pool->start = bcmos_alloc(pool->parm.pool_size);
if (!pool->start)
{
BCMOS_TRACE_RETURN(BCM_ERR_NOMEM, "Can't allocate memory for block pool %s\n", parm->name);
}
}
bcmos_fastlock_init(&pool->lock, parm->flags);
/* Put all blocks on free list */
bcmos_blk_pool_reset(pool);
pool->magic = BCMOS_BLK_POOL_VALID;
if (!(pool->parm.flags & BCMOS_BLK_POOL_FLAG_MSG_POOL))
{
bcmos_mutex_lock(&bcmos_res_lock);
STAILQ_INSERT_TAIL(&blk_pool_list, pool, list);
bcmos_total_blk_pool_size += pool->parm.pool_size;
bcmos_mutex_unlock(&bcmos_res_lock);
}
return BCM_ERR_OK;
}
/* Destroy memory pool */
bcmos_errno bcmos_blk_pool_destroy(bcmos_blk_pool *pool)
{
if (!pool || pool->magic != BCMOS_BLK_POOL_VALID)
{
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "pool handle is invalid\n");
}
if (pool->stat.free < pool->parm.num_blks)
{
BCMOS_TRACE_RETURN(BCM_ERR_STATE, "%i blocks are still allocated from the pool %s\n",
pool->parm.num_blks - pool->stat.free, pool->parm.name);
}
if (!(pool->parm.flags & BCMOS_BLK_POOL_FLAG_MSG_POOL))
{
bcmos_mutex_lock(&bcmos_res_lock);
STAILQ_REMOVE(&blk_pool_list, pool, bcmos_blk_pool, list);
bcmos_total_blk_pool_size -= pool->parm.pool_size;
bcmos_mutex_unlock(&bcmos_res_lock);
}
if (!pool->parm.start && pool->start)
{
bcmos_free(pool->start);
}
pool->magic = BCMOS_BLK_POOL_DELETED;
return BCM_ERR_OK;
}
/** Release all blocks in memory pool . Block content is not affected */
void bcmos_blk_pool_reset(bcmos_blk_pool *pool)
{
uint32_t blk_size;
bcmos_memblk *blk;
uint32_t i;
STAILQ_INIT(&pool->free_list);
#ifdef BCMOS_BLK_POOL_DEBUG
DLIST_INIT(&pool->allocated_list);
#endif
blk_size = pool->parm.blk_size + sizeof(bcmos_memblk);
#ifdef BCMOS_MEM_CHECK
blk_size += sizeof(uint32_t); /* room for magic after user data block */
#endif
blk_size = BCMOS_ROUND_UP(blk_size, sizeof(void *));
/* Put all blocks on free list */
blk = (bcmos_memblk *)pool->start;
for (i = 0; i < pool->parm.num_blks; i++)
{
blk->pool = pool;
STAILQ_INSERT_TAIL(&pool->free_list, blk, next);
#ifdef BCMOS_MEM_CHECK
*(uint32_t *)((long)blk + sizeof(bcmos_memblk) + pool->parm.blk_size) = BCMOS_MEM_MAGIC_SUFFIX;
blk->magic = BCMOS_MEM_MAGIC_FREE;
#endif
#ifdef BCMOS_BLK_POOL_DEBUG
blk->line = 0;
blk->func = NULL;
#endif
blk = (bcmos_memblk *)((long)blk + blk_size);
}
/* Init statistics */
memset(&pool->stat, 0, sizeof(pool->stat));
pool->stat.free = pool->parm.num_blks;
}
/* Allocate block from block memory pool */
#ifdef BCMOS_BLK_POOL_DEBUG
void *bcmos_blk_pool_alloc_func(bcmos_blk_pool *pool, const char *func, int line)
#else
void *bcmos_blk_pool_alloc(bcmos_blk_pool *pool)
#endif
{
bcmos_memblk *blk;
long flags;
#ifdef BCMOS_MEM_CHECK
BUG_ON(!pool);
BUG_ON(pool->magic != BCMOS_BLK_POOL_VALID);
#endif
flags = bcmos_fastlock_lock(&pool->lock);
blk = STAILQ_FIRST(&pool->free_list);
if (blk)
{
STAILQ_REMOVE_HEAD(&pool->free_list, next);
++pool->stat.allocated;
#ifdef BCMOS_MEM_CHECK
blk->magic = BCMOS_MEM_MAGIC_ALLOC;
#endif
#ifdef BCMOS_BLK_POOL_DEBUG
DLIST_INSERT_HEAD(&pool->allocated_list, blk, list);
blk->func = func;
blk->line = line;
#endif
bcmos_fastlock_unlock(&pool->lock, flags);
return (void *)(blk + 1);
}
/* No memory */
++pool->stat.alloc_failed;
bcmos_fastlock_unlock(&pool->lock, flags);
return NULL;
}
/* Allocate block from block memory pool and zero the block */
#ifdef BCMOS_BLK_POOL_DEBUG
void *bcmos_blk_pool_calloc_func(bcmos_blk_pool *pool, const char *func, int line)
{
void *ptr = bcmos_blk_pool_alloc_func(pool, func, line);
if (ptr)
{
memset(ptr, 0, pool->parm.blk_size);
}
return ptr;
}
#else
void *bcmos_blk_pool_calloc(bcmos_blk_pool *pool)
{
void *ptr = bcmos_blk_pool_alloc(pool);
if (ptr)
{
memset(ptr, 0, pool->parm.blk_size);
}
return ptr;
}
#endif
/* Release memory allocated using bcmos_pool_byte_alloc() or bcmos_pool_blk_alloc() */
#ifdef BCMOS_BLK_POOL_DEBUG
void bcmos_blk_pool_free_func(void *ptr, const char *func, int line)
#else
void bcmos_blk_pool_free(void *ptr)
#endif
{
bcmos_memblk *blk;
bcmos_blk_pool *pool;
long flags;
blk = (bcmos_memblk *)((long)ptr - sizeof(bcmos_memblk));
pool = blk->pool;
#ifdef BCMOS_MEM_CHECK
BUG_ON(pool == NULL);
#ifdef BCM_SUBSYSTEM_EMBEDDED
BUG_ON_PRINT(pool->magic != BCMOS_BLK_POOL_VALID, "BUG in %s %d! BLOCK name='%s' pool magic=%u\n", __FUNCTION__, __LINE__, pool->parm.name, pool->magic);
#endif
if (blk->magic != BCMOS_MEM_MAGIC_ALLOC)
{
#ifdef BCMOS_BLK_POOL_DEBUG
BCMOS_TRACE_ERR("bad magic 0x%08x instead of 0x%08x free=0x%08x. ptr=%p %s:%d prev %s:%d\n",
blk->magic, BCMOS_MEM_MAGIC_ALLOC, BCMOS_MEM_MAGIC_FREE,
ptr, func, line, blk->func, blk->line);
#else
BCMOS_TRACE_ERR("bad magic 0x%08x instead of 0x%08x free=0x%08x. ptr=%p\n",
blk->magic, BCMOS_MEM_MAGIC_ALLOC, BCMOS_MEM_MAGIC_FREE, ptr);
#endif
BUG();
}
if (*(uint32_t *)((long)ptr + pool->parm.blk_size) != BCMOS_MEM_MAGIC_SUFFIX)
{
#ifdef BCMOS_BLK_POOL_DEBUG
BCMOS_TRACE_ERR("tail corruption. magic 0x%08x. ptr=%p %s:%d allocated in %s:%d\n",
blk->magic, ptr, func, line, blk->func, blk->line);
#else
BCMOS_TRACE_ERR("tail corruption. magic 0x%08x. ptr=%p\n", blk->magic, ptr);
#endif
BUG();
}
blk->magic = BCMOS_MEM_MAGIC_FREE;
#endif
flags = bcmos_fastlock_lock(&pool->lock);
STAILQ_INSERT_HEAD(&pool->free_list, blk, next);
++pool->stat.released;
#ifdef BCMOS_BLK_POOL_DEBUG
DLIST_REMOVE(blk, list);
blk->func = func;
blk->line = line;
#endif
bcmos_fastlock_unlock(&pool->lock, flags);
}
/* Get pool info */
bcmos_errno bcmos_blk_pool_query(const bcmos_blk_pool *pool, bcmos_blk_pool_info *info)
{
if (!pool || !info)
{
return BCM_ERR_PARM;
}
info->parm = pool->parm;
info->stat = pool->stat;
info->stat.free = pool->parm.num_blks - (info->stat.allocated - info->stat.released);
return BCM_ERR_OK;
}
/* Block pool iterator */
bcmos_errno bcmos_blk_pool_get_next(const bcmos_blk_pool **prev)
{
const bcmos_blk_pool *pool;
if (prev == NULL)
{
return BCM_ERR_PARM;
}
pool = *prev;
if (pool && pool->magic != BCMOS_BLK_POOL_VALID)
{
return BCM_ERR_PARM;
}
if (pool)
{
pool = STAILQ_NEXT(pool, list);
}
else
{
pool = STAILQ_FIRST(&blk_pool_list);
}
*prev = pool;
if (!pool)
{
return BCM_ERR_NO_MORE;
}
return BCM_ERR_OK;
}
#ifdef BCMOS_BLK_POOL_DEBUG
bcmos_errno bcmos_blk_pool_allocated_blk_get_next(const bcmos_blk_pool *pool, const bcmos_memblk **prev, const char **func, int *line)
{
const bcmos_memblk *blk;
if (!pool || !prev)
{
return BCM_ERR_PARM;
}
blk = *prev;
if (blk)
{
blk = DLIST_NEXT(blk, list);
}
else
{
blk = DLIST_FIRST(&pool->allocated_list);
}
*prev = blk;
if (!blk)
{
return BCM_ERR_NO_MORE;
}
*func = blk->func;
*line = blk->line;
return BCM_ERR_OK;
}
#endif
/*
* Message pool
*/
/* release message callback */
static void _bcmos_msg_pool_release(bcmos_msg *msg)
{
if (msg->data_release)
msg->data_release(msg);
bcmos_blk_pool_free(msg);
}
/* Create message pool */
bcmos_errno bcmos_msg_pool_create(bcmos_msg_pool *pool, const bcmos_msg_pool_parm *parm)
{
bcmos_blk_pool_parm pool_parm = {};
bcmos_memblk *blk;
bcmos_errno err;
if (!pool || !parm || !parm->size)
{
return BCM_ERR_PARM;
}
BCM_MEMZERO_STRUCT(pool);
pool->parm = *parm;
pool_parm.num_blks = parm->size;
pool_parm.blk_size = parm->data_size + sizeof(bcmos_msg);
pool_parm.flags = parm->flags | BCMOS_BLK_POOL_FLAG_MSG_POOL;
pool_parm.name = parm->name;
/* Create underlying block pool */
err = bcmos_blk_pool_create(&pool->blk_pool, &pool_parm);
if (err)
{
return err;
}
pool->parm.name = pool->blk_pool.name;
/* Pre-initialize all messages */
STAILQ_FOREACH(blk, &pool->blk_pool.free_list, next)
{
bcmos_msg *msg = (bcmos_msg *)(blk + 1);
msg->data = (void *)(msg + 1);
msg->size = pool->parm.data_size;
msg->release = _bcmos_msg_pool_release;
msg->data_release = parm->data_release;
}
bcmos_mutex_lock(&bcmos_res_lock);
STAILQ_INSERT_TAIL(&msg_pool_list, &pool->blk_pool, list);
bcmos_total_msg_pool_size += pool->blk_pool.parm.pool_size;
bcmos_mutex_unlock(&bcmos_res_lock);
return BCM_ERR_OK;
}
/** Destroy message pool */
bcmos_errno bcmos_msg_pool_destroy(bcmos_msg_pool *pool)
{
bcmos_errno rc;
rc = bcmos_blk_pool_destroy(&pool->blk_pool);
if (rc)
return rc;
bcmos_mutex_lock(&bcmos_res_lock);
STAILQ_REMOVE(&msg_pool_list, &pool->blk_pool, bcmos_blk_pool, list);
bcmos_total_msg_pool_size -= pool->blk_pool.parm.pool_size;
bcmos_mutex_unlock(&bcmos_res_lock);
pool->parm.size = pool->parm.data_size = 0;
return BCM_ERR_OK;
}
/* Allocate message from pool */
#ifdef BCMOS_BLK_POOL_DEBUG
bcmos_msg *bcmos_msg_pool_alloc_func(bcmos_msg_pool *pool, const char *func, int line)
{
return bcmos_blk_pool_alloc_func(&pool->blk_pool, func, line);
}
#else
bcmos_msg *bcmos_msg_pool_alloc(bcmos_msg_pool *pool)
{
return bcmos_blk_pool_alloc(&pool->blk_pool);
}
#endif
/* Get pool info */
bcmos_errno bcmos_msg_pool_query(const bcmos_msg_pool *pool, bcmos_msg_pool_info *info)
{
bcmos_blk_pool_info pool_info;
bcmos_errno err;
if (!pool || !info)
{
return BCM_ERR_PARM;
}
err = bcmos_blk_pool_query(&pool->blk_pool, &pool_info);
if (err)
{
return err;
}
info->parm = pool->parm;
info->stat = pool_info.stat;
return BCM_ERR_OK;
}
/* Block pool iterator */
bcmos_errno bcmos_msg_pool_get_next(const bcmos_msg_pool **prev)
{
const bcmos_msg_pool *pool;
if (prev == NULL)
{
return BCM_ERR_PARM;
}
pool = *prev;
if (pool && pool->blk_pool.magic != BCMOS_BLK_POOL_VALID)
{
return BCM_ERR_PARM;
}
if (pool)
{
pool = container_of(STAILQ_NEXT(&pool->blk_pool, list), bcmos_msg_pool, blk_pool);
}
else
{
pool = container_of(STAILQ_FIRST(&msg_pool_list), bcmos_msg_pool, blk_pool);
}
*prev = pool;
if (!pool)
{
return BCM_ERR_NO_MORE;
}
return BCM_ERR_OK;
}
/** Lock all dynamic memory allocations. Any attempt to allocate memory from the heap after this is called will cause
* an error. This includes bcmos_alloc, bcmos_block_pool_create, etc.
*
* For embedded applications, runtime dynamic memory allocation is generally undesirable, so this should be called
* after system initialization.
*/
void bcmos_dynamic_memory_allocation_block(uint32_t allocation_block_size_threshold)
{
#ifndef ASPEN_VLSI_SIM
bcmos_dynamic_memory_allocation_blocked = BCMOS_TRUE;
#endif
bcmos_dynamic_memory_allocation_block_size_threshold = allocation_block_size_threshold;
}
void bcmos_dynamic_memory_allocation_unblock(void)
{
#ifndef ASPEN_VLSI_SIM
bcmos_dynamic_memory_allocation_blocked = BCMOS_FALSE;
#endif
}
void bcmos_dynamic_memory_allocation_blocking_suspend(void)
{
bcmos_mutex_lock(&dynamic_mem_alloc_suspend_mutex);
dynamic_alloc_suspend_usage_count++;
bcmos_mutex_unlock(&dynamic_mem_alloc_suspend_mutex);
}
void bcmos_dynamic_memory_allocation_blocking_resume(void)
{
bcmos_mutex_lock(&dynamic_mem_alloc_suspend_mutex);
if (dynamic_alloc_suspend_usage_count > 0)
dynamic_alloc_suspend_usage_count--;
else
BCMOS_TRACE_ERR("Dynamic memory allocation blocking is already resumed\n");
bcmos_mutex_unlock(&dynamic_mem_alloc_suspend_mutex);
}
void bcmos_dynamic_memory_allocation_block_check(uint32_t size)
{
if (bcmos_dynamic_memory_allocation_blocked
&& size < bcmos_dynamic_memory_allocation_block_size_threshold
&& !dynamic_alloc_suspend_usage_count)
{
BCMOS_TRACE_ERR("dynamic memory allocation requested at runtime\n");
}
}
/** Set up print redirection/cloning
* \param[in] mode redirection/cloning mode
* \param[in] cb redirection callback
* \param[in] data opaque data to be passed to cb
*/
bcmos_errno bcmos_print_redirect(bcmos_print_redirect_mode mode, bcmos_print_redirect_cb cb, void *data)
{
if (mode != BCMOS_PRINT_REDIRECT_MODE_NONE && cb == NULL)
{
BCMOS_TRACE_RETURN(BCM_ERR_PARM, "Redirection callback must be set\n");
}
print_redirect_mode = mode;
if (mode == BCMOS_PRINT_REDIRECT_MODE_NONE)
{
print_redirect_cb = NULL;
print_redirect_cb_data = NULL;
}
else
{
print_redirect_cb = cb;
print_redirect_cb_data = data;
}
return BCM_ERR_OK;
}
/* Print on the console with optional cloning / redirection */
/*lint -e{454}*/
int bcmos_vprintf(const char *format, va_list ap)
{
int rc = 0;
bcmos_bool protected_section = is_irq_mode() || is_irq_disabled() || !bcmos_initialized;
/* Only protect if in task context */
if (!protected_section)
{
bcmos_mutex_lock(&bcmos_print_lock);
}
if (print_redirect_mode != BCMOS_PRINT_REDIRECT_MODE_REDIRECT)
{
rc = bcmos_sys_vprintf(format, ap);
}
if (print_redirect_mode != BCMOS_PRINT_REDIRECT_MODE_NONE)
{
rc = print_redirect_cb(print_redirect_cb_data, format, ap);
}
if (!protected_section)
{
bcmos_mutex_unlock(&bcmos_print_lock);
}
return rc;
}
/*lint -e{454}*/
/* Print on the console with optional cloning / redirection */
int bcmos_printf(const char *format, ...)
{
va_list args;
int rc;
va_start(args, format);
rc = bcmos_vprintf(format, args);
va_end(args);
return rc;
}
#ifndef BCMOS_PUTCHAR_INLINE
/*lint -e{454}*/
void bcmos_putchar(int c)
{
bcmos_bool protected_section = is_irq_mode() || is_irq_disabled() || !bcmos_initialized;
/* Only protect if in task context */
if (!protected_section)
{
bcmos_mutex_lock(&bcmos_print_lock);
}
putchar(c);
fflush(stdout);
if (!protected_section)
{
bcmos_mutex_unlock(&bcmos_print_lock);
}
}
/*lint +e{454}*/
#endif
#ifndef BCMOS_BUF_OS_SPECIFIC
/*
* Buffer allocation/release
*/
#ifdef BCMOS_BUF_POOL_SIZE
/* Create buffer pool */
static bcmos_errno bcmos_buf_pool_create(uint32_t pool_size, uint32_t blk_size, bcmos_blk_pool *blk_pool)
{
char pool_name[32];
bcmos_blk_pool_parm pool_parm = {};
bcmos_errno rc;
snprintf(pool_name, sizeof(pool_name) - 1, "sysbuf_%u", blk_size);
pool_parm.name = pool_name;
/* If buffer memory should be allocated by bcmos_dma_alloc - allocate
* memory for the whole pool here */
pool_parm.blk_size = blk_size + sizeof(bcmos_buf) + BCMTR_BUF_EXTRA_HEADROOM +
2*BCMOS_BUF_DATA_ALIGNMENT + BCMOS_BUF_DATA_GUARD;
#ifdef BCMOS_BUF_IN_DMA_MEM
pool_parm.pool_size = (pool_parm.blk_size + sizeof(bcmos_memblk)) * pool_size;
pool_parm.start = bcmos_dma_alloc(0, pool_parm.pool_size, NULL);
if (!pool_parm.start)
return BCM_ERR_NOMEM;
#else
pool_parm.num_blks = pool_size;
#endif
rc = bcmos_blk_pool_create(blk_pool, &pool_parm);
if (rc)
{
#ifdef BCMOS_BUF_IN_DMA_MEM
if (pool_parm.start)
bcmos_dma_free(0, pool_parm.start);
#endif
}
return rc;
}
#endif
/* Allocate buffer */
bcmos_buf *__attribute__((weak)) bcmos_buf_alloc(uint32_t size)
{
/* Allocate extra 2 * BCMOS_BUF_DATA_ALIGNMENT to make sure that neither data start nor end
* end up in the middle of cache line
*/
bcmos_buf *buf;
/* Allocate from the pool */
#ifdef BCMOS_BUF_POOL_SIZE
bcmos_blk_pool *pool = &sys_buf_pool;
if (size > BCMOS_BUF_POOL_BUF_SIZE)
{
#ifdef BCMOS_BIG_BUF_POOL_SIZE
if (size <= BCMOS_BIG_BUF_POOL_BUF_SIZE)
{
/* size is to big for "normal" buffer pool, but not too big for "big buffer" pool */
pool = &sys_big_buf_pool;
}
else
#endif
pool = NULL;
}
if (pool != NULL)
buf = bcmos_blk_pool_alloc(pool);
else
#endif /* #ifdef BCMOS_BUF_POOL_SIZE */
{
/* Allocate from the heap */
uint32_t alloc_size = sizeof(bcmos_buf) + size + BCMTR_BUF_EXTRA_HEADROOM +
2 * BCMOS_BUF_DATA_ALIGNMENT - 1 + BCMOS_BUF_DATA_GUARD;
#ifdef BCMOS_BUF_DATA_UNIT_SIZE
#if BCMOS_BUF_DATA_UNIT_SIZE & (BCMOS_BUF_DATA_UNIT_SIZE - 1)
#error BCMOS_BUF_DATA_UNIT_SIZE must be a power of 2
#endif
alloc_size = BCMOS_ROUND_UP(alloc_size, BCMOS_BUF_DATA_UNIT_SIZE);
#endif
#ifdef BCMOS_BUF_IN_DMA_MEM
buf = bcmos_dma_alloc(0, alloc_size, NULL);
#else
buf = bcmos_alloc(alloc_size);
#endif
}
if (!buf)
return NULL;
buf->start = (uint8_t *)(buf + 1) + BCMOS_BUF_DATA_GUARD;
buf->data = (uint8_t *)(BCMOS_ROUND_UP((long)buf->start + BCMTR_BUF_EXTRA_HEADROOM, BCMOS_BUF_DATA_ALIGNMENT));
buf->size = size + (buf->data - buf->start);
buf->len = 0;
#ifdef BCMOS_BUF_POOL_SIZE
buf->pool = pool;
#else
buf->pool = NULL;
#endif
return buf;
}
/* Release buffer */
void __attribute__((weak)) bcmos_buf_free(bcmos_buf *buf)
{
#ifdef BCMOS_BUF_POOL_SIZE
/* Buffer might have been allocated from the system pool */
if (buf->pool)
{
bcmos_blk_pool_free(buf);
return;
}
#endif
#ifdef BCMOS_BUF_IN_DMA_MEM
bcmos_dma_free(0, buf);
#else
bcmos_free(buf);
#endif
}
/* Clone transport buffer */
bcmos_buf *bcmos_buf_clone(bcmos_buf *buf)
{
uint32_t len = bcmos_buf_length(buf);
bcmos_buf *clone = bcmos_buf_alloc(len);
if (!clone)
return NULL;
memcpy(bcmos_buf_data(clone), bcmos_buf_data(buf), len);
bcmos_buf_length_set(clone, len);
bcmos_buf_channel_set(clone, bcmos_buf_channel(buf));
return clone;
}
#endif
/* Compile flag to control which platforms healthcheck is run on */
#ifdef BCMOS_HEALTH_CHECK_ENABLED
/* Define healthcheck information */
#define BCMOS_HC_DEBUG 0
#if BCMOS_HC_DEBUG
#define BCMOS_HEALTHCHECK_MODULE_PERIOD 10000000 /* timer delay 10 seconds * 1000000 usecs/sec */
#else
#define BCMOS_HEALTHCHECK_MODULE_PERIOD 60000000 /* timer delay 1 minute = 60 seconds * 1000000 usecs/sec */
#endif
typedef struct
{
uint64_t last_timestamp;
bcmos_bool was_created;
} healthcheck_info;
/* health check data store */
static healthcheck_info module_health[BCMOS_MODULE_ID__NUM_OF];
/* keep track of whether module health array has been initialized */
static bcmos_bool hc_init = BCMOS_FALSE;
/* Define a health check timer for each module */
#define SIZE_OF_HC_TMR_STR 20
#define MAX_LENGTH_TMR_NAME (BCMOS_MAX_NAME_LENGTH + SIZE_OF_HC_TMR_STR + 1)
typedef struct
{
char timer_name[MAX_LENGTH_TMR_NAME];
bcmos_timer healthcheck_timer;
} timer_info;
static timer_info hc_timer_info[BCMOS_MODULE_ID__NUM_OF];
/* define healthcheck info data accessors */
static void healthcheck_was_created_set(bcmos_module_id module_id)
{
module_health[module_id].was_created = BCMOS_TRUE;
}
static bcmos_bool healthcheck_was_created_get(bcmos_module_id module_id)
{
return module_health[module_id].was_created;
}
static void healthcheck_last_timestamp_set(bcmos_module_id module_id)
{
bcmos_mutex_lock(&health_check_data_mutex);
module_health[module_id].last_timestamp = bcmos_timestamp64();
bcmos_mutex_unlock(&health_check_data_mutex);
}
static uint64_t healthcheck_last_timestamp_get(bcmos_module_id module_id)
{
uint64_t timestamp = 0;
bcmos_mutex_lock(&health_check_data_mutex);
timestamp = module_health[module_id].last_timestamp;
bcmos_mutex_unlock(&health_check_data_mutex);
return timestamp;
}
/**
* Function that returns whether a module is healthy. That is,
* has it responded to health check timer expiry messages by
* updating the last timestamp?
*
* @param period Time in microseconds since last query.
* @param module_id ID of module of interest
*
* @return True if healthy. False if not.
*/
bcmos_bool bcmos_module_is_healthy(uint32_t period, bcmos_module_id module_id)
{
bcmos_bool healthy = BCMOS_TRUE;
uint64_t now = bcmos_timestamp64();
/* use accessors */
uint64_t last_ts = healthcheck_last_timestamp_get(module_id);
bcmos_bool was_created = healthcheck_was_created_get(module_id);
if (was_created)
{
uint64_t time_since_last_ts = now - last_ts;
if (time_since_last_ts > period)
{
healthy = BCMOS_FALSE;
BCMOS_TRACE(BCMOS_TRACE_LEVEL_ERROR, "Healthcheck failure time_since_last_ts[%lu] = current_ts[%lu] - last_ts[%lu] > periodic[%lu] \n",
time_since_last_ts, now, last_ts, period);
}
}
return healthy;
}
void healthcheck_print(bcmos_module_id module_id)
{
bcmos_printf("\n");
bcmos_printf("Module ID | Created | Last Timestamp\n");
if (module_id == BCMOS_MODULE_ID__NUM_OF)
{
for (bcmos_module_id i = BCMOS_MODULE_ID_NONE; i < BCMOS_MODULE_ID__NUM_OF; i++)
{
bcmos_bool was_created = healthcheck_was_created_get(i);
uint64_t last_ts = healthcheck_last_timestamp_get(i);
if (last_ts != 0)
{
bcmos_printf(" %3d | %7s | %14llu\n", i, (was_created) ? "yes" : "no", last_ts);
}
}
}
else
{
bcmos_printf(" %3d | %7s | %14llu\n",
module_id, (healthcheck_was_created_get(module_id)) ? "yes" : "no", healthcheck_last_timestamp_get(module_id));
}
}
static bcmos_timer_rc bcmos_healthcheck_timer_expiry_handler (bcmos_timer * wdtimer, long data)
{
/* update timestamp */
bcmos_module_id module_id = wdtimer->parm.owner;
healthcheck_last_timestamp_set(module_id);
return BCMOS_TIMER_OK;
}
bcmos_errno bcmos_module_health_check_init(const bcmos_module* module)
{
bcmos_errno rc = BCM_ERR_OK;
bcmos_module_id module_id = module->id;
char health_check_str[SIZE_OF_HC_TMR_STR] = "health_check_timer";
/* initalize timer info array and timer name */
/* use snprintf for safety */
snprintf(hc_timer_info[module_id].timer_name, MAX_LENGTH_TMR_NAME, "%s%s", module->name, health_check_str);
bcmos_timer_parm wd_timerparms =
{
.name = hc_timer_info[module_id].timer_name,
.owner = module_id,
.periodic = BCMOS_TRUE, /* repeat */
.handler = bcmos_healthcheck_timer_expiry_handler,
.flags = BCMOS_TIMER_PARM_FLAGS_NON_URGENT
};
/* Check that modules data store has already been initialized */
if (hc_init == BCMOS_FALSE)
{
bcmos_printf("Health Check has not yet been properly initialized\n");
return BCM_ERR_INTERNAL;
}
/* do not do a health check of device_mgmt */
if (module_id == BCMOS_MODULE_ID_DEVICE_MGMT)
{
return rc;
}
/* initialize */
healthcheck_last_timestamp_set(module_id);
healthcheck_was_created_set(module_id);
/* create and start the timer */
rc = bcmos_timer_create(&hc_timer_info[module_id].healthcheck_timer, &wd_timerparms);
if (!rc)
{
bcmos_timer_start(&hc_timer_info[module_id].healthcheck_timer, BCMOS_HEALTHCHECK_MODULE_PERIOD);
}
return rc;
}
bcmos_errno bcmos_module_health_check_destroy(bcmos_module_id module_id)
{
bcmos_timer_destroy(&hc_timer_info[module_id].healthcheck_timer);
return BCM_ERR_OK;
}
bcmos_errno bcmos_modules_healthcheck_init(void)
{
/* initialize data store and timer info */
memset(&module_health, 0, sizeof(module_health));
memset(&hc_timer_info, 0, sizeof(hc_timer_info));
hc_init = BCMOS_TRUE;
return BCM_ERR_OK;
}
#endif
/* Copy string.
The copy is allocated using bcmos_alloc() and should be released using bcmos_free()
*/
char *bcmos_strdup(const char *s)
{
char *copy = (s != NULL) ? (char *)bcmos_alloc(strlen(s) + 1) : NULL;
if (copy != NULL )
strcpy(copy, s);
return copy;
}
bcmos_oops_complete_cb_t bcmos_oops_complete_cb;
EXPORT_SYMBOL(bcmos_init);
EXPORT_SYMBOL(bcmos_msg_queue_create);
EXPORT_SYMBOL(bcmos_msg_queue_destroy);
EXPORT_SYMBOL(bcmos_msg_queue_query);
EXPORT_SYMBOL(bcmos_msg_queue_get_next);
EXPORT_SYMBOL(bcmos_msg_send);
EXPORT_SYMBOL(bcmos_msg_send_to_module);
EXPORT_SYMBOL(bcmos_msg_recv);
EXPORT_SYMBOL(bcmos_msg_register);
EXPORT_SYMBOL(bcmos_msg_unregister);
EXPORT_SYMBOL(bcmos_msg_dispatch);
EXPORT_SYMBOL(bcmos_msg_qgroup_create);
EXPORT_SYMBOL(bcmos_msg_qgroup_destroy);
EXPORT_SYMBOL(bcmos_msg_qgroup_query);
EXPORT_SYMBOL(bcmos_msg_recv_from_qgroup);
EXPORT_SYMBOL(bcmos_msg_send_to_qgroup);
EXPORT_SYMBOL(bcmos_task_timeout_set);
EXPORT_SYMBOL(bcmos_task_get_next);
EXPORT_SYMBOL(bcmos_module_create);
EXPORT_SYMBOL(bcmos_module_destroy);
EXPORT_SYMBOL(bcmos_module_current);
EXPORT_SYMBOL(bcmos_module_context);
EXPORT_SYMBOL(bcmos_module_context_set);
EXPORT_SYMBOL(bcmos_module_query);
EXPORT_SYMBOL(bcmos_event_create);
EXPORT_SYMBOL(bcmos_event_destroy);
EXPORT_SYMBOL(bcmos_event_raise);
EXPORT_SYMBOL(bcmos_event_recv);
EXPORT_SYMBOL(bcmos_timer_create);
EXPORT_SYMBOL(bcmos_timer_destroy);
EXPORT_SYMBOL(bcmos_timer_start);
EXPORT_SYMBOL(bcmos_timer_stop);
EXPORT_SYMBOL(bcmos_timer_handler_set);
#ifdef BCMOS_TIMER_DEBUG
EXPORT_SYMBOL(bcmos_timer_query);
EXPORT_SYMBOL(bcmos_timer_get_next);
#endif
EXPORT_SYMBOL(bcmos_blk_pool_create);
EXPORT_SYMBOL(bcmos_blk_pool_destroy);
EXPORT_SYMBOL(bcmos_blk_pool_reset);
#ifdef BCMOS_BLK_POOL_DEBUG
EXPORT_SYMBOL(bcmos_blk_pool_alloc_func);
EXPORT_SYMBOL(bcmos_blk_pool_calloc_func);
#else
EXPORT_SYMBOL(bcmos_blk_pool_alloc);
EXPORT_SYMBOL(bcmos_blk_pool_calloc);
#endif
EXPORT_SYMBOL(bcmos_blk_pool_free);
EXPORT_SYMBOL(bcmos_blk_pool_query);
EXPORT_SYMBOL(bcmos_blk_pool_get_next);
#ifdef BCMOS_BLK_POOL_DEBUG
EXPORT_SYMBOL(bcmos_blk_pool_allocated_blk_get_next);
#endif
EXPORT_SYMBOL(bcmos_msg_pool_create);
#ifdef BCMOS_BLK_POOL_DEBUG
EXPORT_SYMBOL(bcmos_msg_pool_alloc_func);
#else
EXPORT_SYMBOL(bcmos_msg_pool_alloc);
#endif
EXPORT_SYMBOL(bcmos_msg_pool_query);
EXPORT_SYMBOL(bcmos_msg_pool_destroy);
EXPORT_SYMBOL(bcmos_msg_pool_get_next);
EXPORT_SYMBOL(bcmos_print_redirect);
EXPORT_SYMBOL(bcmos_printf);
EXPORT_SYMBOL(bcmos_vprintf);
#ifndef BCMOS_BUF_OS_SPECIFIC
EXPORT_SYMBOL(bcmos_buf_alloc);
EXPORT_SYMBOL(bcmos_buf_free);
EXPORT_SYMBOL(bcmos_buf_clone);
#endif
EXPORT_SYMBOL(bcmos_oops_complete_cb);
EXPORT_SYMBOL(bcmos_dynamic_memory_allocation_block);
EXPORT_SYMBOL(bcmos_dynamic_memory_allocation_block_check);
EXPORT_SYMBOL(bcmos_strdup);
<file_sep>/*
* <:copyright-BRCM:2016-2020:Apache:standard
*
* Copyright (c) 2016-2020 Broadcom. All Rights Reserved
*
* The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* :>
*
*****************************************************************************/
/*
* netconf_module_utils.c
*
* Created on: 31 Aug 2017
* Author: igort
*/
#define _GNU_SOURCE
#include <bcmolt_netconf_module_utils.h>
#include <sysrepo/values.h>
#include <sys/stat.h>
/* datastore suffix */
static const char *nc_ds_suffix[] = {
[NC_DATASTORE_RUNNING] = "running",
[NC_DATASTORE_STARTUP] = "startup",
[NC_DATASTORE_CANDIDATE] = "candidate",
[NC_DATASTORE_PENDING] = "pending",
};
/*
* Serialization primitives. Lock/unlock configuration
*/
static bcmos_mutex nc_config_lock_mutex;
void nc_config_lock(void)
{
static bcmos_bool is_initialized = BCMOS_FALSE;
if (!is_initialized)
{
bcmos_mutex_create(&nc_config_lock_mutex, 0, NULL);
is_initialized = BCMOS_TRUE;
}
bcmos_mutex_lock(&nc_config_lock_mutex);
}
void nc_config_unlock(void)
{
bcmos_mutex_unlock(&nc_config_lock_mutex);
}
/* Get leaf node name in the xpath.
* It is the node that follows the last /
*/
const char *nc_xpath_leaf_get(const char *xpath, char *leaf, uint32_t leaf_size)
{
const char *last_slash;
const char *p_leaf;
char *p_bra;
if (!xpath)
return NULL;
last_slash = strrchr(xpath, '/');
p_leaf = last_slash ? last_slash + 1 : xpath;
strncpy(leaf, p_leaf, leaf_size);
leaf[leaf_size - 1] = 0;
p_bra = strchr(leaf, '[');
if (p_bra)
*p_bra = 0;
return leaf;
}
static bcmos_bool nc_file_exist(const char *path)
{
struct stat s;
if (stat(path, &s) != 0)
return BCMOS_FALSE;
if ((s.st_mode & S_IFMT) != S_IFREG)
return BCMOS_FALSE;
return BCMOS_TRUE;
}
/* Get the key value from xpath
*
* xpath = node/node[keyname='keyvalue']/node/node
*
* Returns
* - BCM_ERR_OK
* - BCM_ERR_PARM - malformed xpath
* - BCM_ERR_NOENT - no key in []
* - BCM_ERR_OVERFLOW - key value parameter is too short
*/
bcmos_errno nc_xpath_key_get(const char *xpath, const char *keyname, char *value, uint32_t value_size)
{
const char *bra, *ket, *eq;
const char *name, *val, *val_last;
const char *path;
uint32_t keyname_len;
bcmos_errno err = BCM_ERR_NOENT;
if (!xpath)
return BCM_ERR_NOENT;
if (!keyname)
return BCM_ERR_PARM;
keyname_len = strlen(keyname);
for (path = xpath, ket = NULL;
(err != BCM_ERR_OK) && (bra = strchr(path, '[')) != NULL;
path = ket)
{
name = bra + 1;
eq = strchr(name, '=');
if (!eq)
return BCM_ERR_PARM;
ket = strchr(eq, ']');
if (!ket)
return BCM_ERR_PARM;
if (memcmp(keyname, name, keyname_len) || (keyname_len != (eq - name)))
continue;
/* Found the key */
val = eq + 1;
val_last = ket - 1;
if (*val == '\'' || *val == '\"')
++val;
if (*val_last == '\'' || *val_last == '\"')
--val_last;
if (val_last - val + 1 >= value_size)
return BCM_ERR_OVERFLOW;
memcpy(value, val, val_last - val + 1);
value[val_last - val + 1] = 0;
err = BCM_ERR_OK;
}
return err;
}
/* Copy configuration from 1 datastore to another */
void nc_cfg_copy(sr_session_ctx_t *srs, const char *model, nc_datastore_type from, nc_datastore_type to)
{
char *src_path = NULL;
char *cmd = NULL;
int n1, n2;
n1 = asprintf(&src_path, SR_DATA_SEARCH_DIR "/%s.%s", model, nc_ds_suffix[from]);
n2 = asprintf(&cmd, "cp -f " SR_DATA_SEARCH_DIR "/%s.%s " SR_DATA_SEARCH_DIR "/%s.%s",
model, nc_ds_suffix[from], model, nc_ds_suffix[to]);
if (!cmd || !src_path || n1 < 0 || n2 < 0)
{
NC_LOG_ERR("%s: failed to copy configuration from %s to %s: no memory\n",
model, nc_ds_suffix[from], nc_ds_suffix[to]);
if (cmd)
free(cmd);
if (src_path)
free(src_path);
return;
}
/* Reset destination datastore if source doesn't exist */
if (!nc_file_exist(src_path))
{
NC_LOG_INFO("File %s doesn't exist\n", src_path);
nc_cfg_reset(srs, model, to);
free(cmd);
free(src_path);
return;
}
if (system(cmd))
{
NC_LOG_ERR("%s: failed to copy configuration from %s to %s: IO error\n",
model, nc_ds_suffix[from], nc_ds_suffix[to]);
}
else
{
NC_LOG_INFO("%s: %s configuration copied to %s\n", model, nc_ds_suffix[from], nc_ds_suffix[to]);
}
free(cmd);
free(src_path);
}
/* Reset startup configuration */
void nc_cfg_reset(sr_session_ctx_t *srs, const char *model, nc_datastore_type ds)
{
char *fname = NULL, *cmd = NULL;
int rc = -1;
int n1, n2;
n1 = asprintf(&fname, SR_DATA_SEARCH_DIR "/%s.%s", model, nc_ds_suffix[ds]);
n2 = asprintf(&cmd, "touch %s", fname);
if (!fname || !cmd || n1 < 0 || n2 < 0)
{
NC_LOG_ERR("%s: failed to reset %s configuration: no memory\n", model, nc_ds_suffix[ds]);
if (fname)
free(fname);
if (cmd)
free(cmd);
return;
}
/* Do nothing if file doesn't exist */
if (!nc_file_exist(fname))
{
free(fname);
free(cmd);
return;
}
if (!unlink(fname))
rc = system(cmd);
free(fname);
free(cmd);
if (rc)
{
NC_LOG_ERR("%s: failed to reset %s configuration: IO error\n", model, nc_ds_suffix[ds]);
}
else
{
NC_LOG_INFO("%s: %s configuration has been reset\n", model, nc_ds_suffix[ds]);
}
}
/* Error log */
void nc_error_reply(sr_session_ctx_t *srs, const char *xpath, const char *format, ...)
{
va_list args;
char *msg = NULL;
int n;
va_start(args, format);
n = vasprintf(&msg, format, args);
va_end(args);
if (msg && n > 0)
{
sr_set_error(srs, xpath, msg);
free(msg);
}
}
/* Add value to the list of values */
int nc_sr_value_add(
const char *xpath,
sr_type_t type,
const char *string_val,
sr_val_t **values,
size_t *values_cnt)
{
size_t new_count = *values_cnt + 1;
sr_val_t *new_val;
uint64_t num_val;
int sr_rc;
if (*values_cnt)
{
sr_rc = sr_realloc_values(*values_cnt, new_count, values);
}
else
{
sr_rc = sr_new_values(new_count, values);
}
if (sr_rc)
return SR_ERR_NOMEM;
new_val = &((*values)[*values_cnt]);
num_val = strtoull(string_val, NULL, 0);
do {
sr_rc = sr_val_set_xpath(new_val, xpath);
if (sr_rc)
break;
switch (type)
{
case SR_BINARY_T:
case SR_BITS_T:
case SR_ENUM_T:
case SR_IDENTITYREF_T:
case SR_INSTANCEID_T:
case SR_STRING_T:
sr_rc = sr_val_set_str_data(new_val, type, string_val);
break;
case SR_CONTAINER_PRESENCE_T:
case SR_BOOL_T:
new_val->data.bool_val = !strcmp(string_val, "true");
break;
case SR_INT8_T:
new_val->data.int8_val = (int8_t)num_val;
break;
case SR_INT16_T:
new_val->data.int16_val = (int16_t)num_val;
break;
case SR_INT32_T:
new_val->data.int32_val = (int32_t)num_val;
break;
case SR_INT64_T:
new_val->data.int64_val = (int64_t)num_val;
break;
case SR_UINT8_T:
new_val->data.uint8_val = (uint8_t)num_val;
break;
case SR_UINT16_T:
new_val->data.uint16_val = (uint16_t)num_val;
break;
case SR_UINT32_T:
new_val->data.uint32_val = (uint32_t)num_val;
break;
case SR_UINT64_T:
new_val->data.uint64_val = (uint64_t)num_val;
break;
default:
sr_rc = SR_ERR_INVAL_ARG;
}
} while (0);
if (sr_rc)
{
sr_val_t *dup_values = NULL;
/* Create a copy of values array in order to shrink it */
if (*values_cnt)
sr_dup_values(*values, *values_cnt, &dup_values);
sr_free_values(*values, new_count);
*values = dup_values;
if (dup_values == NULL)
*values_cnt = 0;
return sr_rc;
}
new_val->type = type;
*values_cnt = new_count;
return SR_ERR_OK;
}
/* Add sub-value to the list of values.
* The difference from nc_sr_value_add is that xpath is built internally
* from 2 components: xpath_base and value_name
*/
int nc_sr_sub_value_add(
const char *xpath_base,
const char *value_name,
sr_type_t type,
const char *string_val,
sr_val_t **values,
size_t *values_cnt)
{
char xpath_buf[256];
char *xpath = xpath_buf;
int sr_rc;
if (snprintf(xpath, sizeof(xpath_buf), "%s/%s", xpath_base, value_name) > sizeof(xpath_buf) - 1)
{
if (asprintf(&xpath, "%s/%s", xpath_base, value_name) <= 0)
return SR_ERR_NOMEM;
}
sr_rc = nc_sr_value_add(xpath, type, string_val, values, values_cnt);
if (sr_rc != SR_ERR_OK)
{
NC_LOG_ERR("Failed to add attribute %s. Error %s\n", xpath, sr_strerror(sr_rc));
}
if (xpath != xpath_buf)
free(xpath);
return sr_rc;
}
/* Add sub-value to the list of values.
* The difference from nc_sr_value_add is that xpath is built internally
* from 2 components: xpath_base and value_name
*/
struct lyd_node *nc_ly_sub_value_add(
const struct ly_ctx *ctx,
struct lyd_node *parent,
const char *xpath_base,
const char *value_name,
const char *string_val)
{
char xpath_buf[256];
char *xpath = xpath_buf;
struct lyd_node *result;
if (snprintf(xpath, sizeof(xpath_buf), "%s/%s", xpath_base, value_name) > sizeof(xpath_buf) - 1)
{
if (asprintf(&xpath, "%s/%s", xpath_base, value_name) <= 0)
return parent;
}
result = lyd_new_path(parent, ctx, xpath, (void *)(long)string_val, LYD_ANYDATA_CONSTSTRING, 0);
NC_LOG_DBG("lyd_new_path(%s, ctx, \"%s\", \"%s\", 0, 0) -> %s\n",
(parent && parent->schema) ? parent->schema->name : "NULL",
xpath, string_val ? string_val : "NULL", (result && result->schema) ? result->schema->name : "NULL");
if (result == NULL)
{
NC_LOG_ERR("Error '%s'. Failed to add attribute %s.\n", ly_errmsg(ctx), xpath);
}
if (xpath != xpath_buf)
free(xpath);
return result ? result : parent;
}
/* Add value to array of values.
* Return SR_SRR_...
*/
int nc_sr_values_set(sr_session_ctx_t *srs, sr_val_t *values, size_t values_cnt)
{
size_t i;
int sr_rc = SR_ERR_OK;
for (i=0; i<values_cnt; i++)
{
sr_rc = sr_set_item(srs, values[i].xpath, &values[i], SR_EDIT_DEFAULT);
if (sr_rc != SR_ERR_OK)
{
NC_LOG_ERR("Failed to set value for xpath %s. Error %s\n", values[i].xpath, sr_strerror(sr_rc));
break;
}
}
return sr_rc;
}
/* Free value pair
* Variables *p_val1 and *p_val2 are released.
* *p_val1 and *p_val2 are set =NULL
*/
void nc_sr_free_value_pair(sr_val_t **p_val1, sr_val_t **p_val2)
{
if (*p_val1)
{
sr_free_val(*p_val1);
*p_val1 = NULL;
}
if (*p_val2)
{
sr_free_val(*p_val2);
*p_val2 = NULL;
}
}
/*
* Transaction support utilities
*/
void nc_transact_init(nc_transact *tr, sr_event_t event)
{
tr->event = event;
tr->plugin_elem_type = NC_TRANSACT_PLUGIN_ELEM_TYPE_INVALID;
STAILQ_INIT(&tr->elems);
}
bcmos_errno nc_transact_add(nc_transact *tr, sr_val_t **p_old_val, sr_val_t **p_new_val)
{
nc_transact_elem *elem = bcmos_alloc(sizeof(nc_transact_elem));
if (elem == NULL)
{
NC_LOG_ERR("Can't collect transaction for %s\n",
(*p_old_val && (*p_old_val)->xpath) ? (*p_old_val)->xpath :
(*p_new_val && (*p_new_val)->xpath) ? (*p_new_val)->xpath : "Unknown");
return BCM_ERR_NOMEM;
}
elem->old_val = *p_old_val;
elem->new_val = *p_new_val;
STAILQ_INSERT_TAIL(&tr->elems, elem, next);
*p_old_val = NULL;
*p_new_val = NULL;
return BCM_ERR_OK;
}
void nc_transact_free(nc_transact *tr)
{
nc_transact_elem *elem;
while ((elem=STAILQ_FIRST(&tr->elems)))
{
if (!tr->do_not_free_values)
{
if (elem->old_val)
sr_free_val(elem->old_val);
if (elem->new_val)
sr_free_val(elem->new_val);
}
STAILQ_REMOVE_HEAD(&tr->elems, next);
bcmos_free(elem);
}
}
/* Map error code from bcmos --> sysrepo */
int nc_bcmos_errno_to_sr_errno(bcmos_errno err)
{
int sr_rc = SR_ERR_INTERNAL;
switch(err)
{
case BCM_ERR_OK: sr_rc = SR_ERR_OK;
break;
case BCM_ERR_PARM: sr_rc = SR_ERR_INVAL_ARG;
break;
case BCM_ERR_NOMEM: sr_rc = SR_ERR_NOMEM;
break;
case BCM_ERR_NOT_SUPPORTED: sr_rc = SR_ERR_UNSUPPORTED;
break;
case BCM_ERR_IN_PROGRESS: sr_rc = SR_ERR_OPERATION_FAILED;
break;
case BCM_ERR_NOENT: sr_rc = SR_ERR_NOT_FOUND;
break;
case BCM_ERR_ALREADY: sr_rc = SR_ERR_EXISTS;
break;
default: sr_rc = SR_ERR_INTERNAL;
break;
}
return sr_rc;
}
/* Map sysrepo errno to BAL */
bcmos_errno nc_sr_errno_to_bcmos_errno(int sr_rc)
{
bcmos_errno err;
switch (sr_rc)
{
case SR_ERR_OK: err = BCM_ERR_OK;
break;
case SR_ERR_INVAL_ARG: err = BCM_ERR_PARM;
break;
case SR_ERR_NOMEM: err = BCM_ERR_NOMEM;
break;
case SR_ERR_UNSUPPORTED: err = BCM_ERR_NOT_SUPPORTED;
break;
default: err = BCM_ERR_INTERNAL;
break;
}
return err;
}
/* Translate binary data to hexadeciumal string.
* hex buffer size must be at least (len*2 + 1)
*/
#define BIN_TO_HEX(_n) ((_n) >= 0 && (_n) <= 9) ? '0' + (_n) : 'A' + ((_n) - 10)
void nc_bin_to_hex(const uint8_t *bin, uint32_t len, char *hex)
{
int i;
char *p = hex;
for (i=0; i<len; i++)
{
*(p++) = BIN_TO_HEX((bin[i] >> 4) & 0x0f);
*(p++) = BIN_TO_HEX(bin[i] & 0x0f);
}
*p = 0;
}
/* Translate binary data from hexadecimal string to binary.
*/
int nc_hex_to_bin(const char *hex, uint8_t *bin, uint32_t bin_len)
{
int src_len = (int)strlen(hex);
int i = src_len, j, shift = 0;
if (!bin || !bin_len || (src_len%2))
return BCM_ERR_PARM;
if (src_len > 2*bin_len)
return BCM_ERR_OVERFLOW;
/* Calculate hex buffer length and fill it up from right-to-left
* in order to start the process from LS nibble
*/
memset(bin, 0, bin_len);
bin_len = src_len / 2;
j = bin_len - 1;
while( i )
{
int c = hex[--i];
if ( (c>='0') && (c<='9') )
c = c - '0';
else if ( (c>='a') && (c<='f') )
c = 0xA + c - 'a';
else if ( (c>='A') && (c<='F') )
c = 0xA + c - 'A';
else
return BCM_ERR_PARM;
bin[j] |= (uint8_t)(c<<shift); /* shift can have 1 of 2 values: 0 and 4 */
j -= shift>>2; /* move to the next byte if we've just filled the ms nibble */
shift ^= 4; /* alternate nibbles */
}
return bin_len;
}
/* sysrepo operation name */
const char *sr_op_name(sr_change_oper_t op)
{
static const char *op_name[] = {
[SR_OP_CREATED] = "CREATED", /**< The item has been created by the change. */
[SR_OP_MODIFIED] = "MODIFIED", /**< The value of the item has been modified by the change. */
[SR_OP_DELETED] = "DELETED", /**< The item has been deleted by the change. */
[SR_OP_MOVED] = "MOVED" /**< The item has been moved in the subtree by the change (applicable for leaf-lists and user-ordered lists). */
};
return op_name[op];
}
/* find a sibling node by name */
const struct lyd_node *nc_ly_get_sibling_node(const struct lyd_node *node, const char *name)
{
const struct lyd_node *n;
/* Go over prev siblings */
n = node->prev;
while (n && n != node && strcmp(n->schema->name, name))
n = n->prev;
if (n != NULL && n != node)
return n;
/* Go over next siblings */
n = node->next;
while (n && n != node && strcmp(n->schema->name, name))
n = n->next;
return (n == node) ? NULL : n;
}
/* find a sibling or a parent+siblings node by name */
const struct lyd_node *nc_ly_get_sibling_or_parent_node(const struct lyd_node *node, const char *name)
{
const struct lyd_node *n;
const struct lyd_node *parent;
n = nc_ly_get_sibling_node(node, name);
if (n != NULL)
return n;
parent = node->parent;
if (parent && !strcmp(parent->schema->name, name))
return parent;
while (parent && n == NULL)
{
n = nc_ly_get_sibling_node(parent, name);
parent = parent->parent;
}
return n;
}
/*
* Save / restore transaction error
*/
void nc_sr_error_save(sr_session_ctx_t *srs, char **xpath, char **message)
{
const sr_error_info_t *sr_err_info=NULL;
*xpath = NULL;
*message = NULL;
sr_get_error(srs, &sr_err_info);
if (sr_err_info != NULL && sr_err_info->err != NULL)
{
if (sr_err_info->err->xpath)
*xpath = bcmos_strdup(sr_err_info->err->xpath);
if (sr_err_info->err->message)
*message = bcmos_strdup(sr_err_info->err->message);
}
}
void nc_sr_error_restore(sr_session_ctx_t *srs, char *xpath, char *message)
{
if (message != NULL)
sr_set_error(srs, xpath, message);
if (xpath != NULL)
bcmos_free(xpath);
if (message != NULL)
bcmos_free(message);
}
<file_sep>/*
* <:copyright-BRCM:2016-2020:Apache:standard
*
* Copyright (c) 2016-2020 Broadcom. All Rights Reserved
*
* The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* :>
*
*****************************************************************************/
/*
* bcmolt_netconf_notifications.c
*/
#define _GNU_SOURCE
#include <bcmos_system.h>
#include <sysrepo.h>
#include <libyang/libyang.h>
#include <sysrepo/values.h>
#include <bcmolt_netconf_module_utils.h>
#include <bcmolt_netconf_notifications.h>
extern bcmos_bool xpon_cterm_is_onu_state_notifiable(const char *cterm_name, const char *state);
/* change onu state change event
serial_number_string is 4 ASCII characters vendor id followed by 8 hex numbers
representing 4-byte vendor-specific id
*/
bcmos_errno bcmolt_xpon_v_ani_state_change(const char *cterm_name, uint16_t onu_id,
const uint8_t *serial_number, xpon_onu_presence_flags presence_flags)
{
#ifdef TR385_ISSUE2
sr_session_ctx_t *session = bcm_netconf_session_get();
const struct ly_ctx *ctx = sr_get_context(sr_session_get_connection(session));
struct lyd_node *notif = NULL;
time_t t = time(NULL);
struct tm tm = *localtime(&t);
char date_time_string[64];
char serial_number_string[13];
const char *presence_state;
char notif_xpath[200];
int sr_rc = SR_ERR_INVAL_ARG;
/* Don't send notification if ONU was discovered, but not yet activated and v-ani is present.
In this case NETCONF server will attempt to activate the ONU, so this discovery state is transitional.
*/
if (presence_flags == (XPON_ONU_PRESENCE_FLAG_V_ANI | XPON_ONU_PRESENCE_FLAG_ONU) &&
(onu_id != XPON_ONU_ID_UNDEFINED))
{
NC_LOG_INFO("Transient discovery state for ONU %s:%u. NOT sending a state-change notification\n",
cterm_name, onu_id);
return BCM_ERR_OK;
}
do
{
if ((presence_flags & XPON_ONU_PRESENCE_FLAG_ONU) != 0)
{
if ((presence_flags & XPON_ONU_PRESENCE_FLAG_V_ANI) != 0)
{
presence_state = ((presence_flags & XPON_ONU_PRESENCE_FLAG_ONU_IN_O5) != 0) ?
"bbf-xpon-onu-types:onu-present-and-on-intended-channel-termination" :
((onu_id != XPON_ONU_ID_UNDEFINED) ?
"bbf-xpon-onu-types:onu-present-and-v-ani-known-and-o5-failed" :
"bbf-xpon-onu-types:onu-present-and-v-ani-known-and-o5-failed-no-onu-id");
}
else
{
presence_state = ((presence_flags & XPON_ONU_PRESENCE_FLAG_ONU_ACTIVATION_FAILED) != 0) ?
"bbf-xpon-onu-types:onu-present-and-no-v-ani-known-and-o5-failed-undefined" :
"bbf-xpon-onu-types:onu-present-and-no-v-ani-known-and-o5-failed-no-onu-id";
}
}
else
{
presence_state = ((presence_flags & XPON_ONU_PRESENCE_FLAG_V_ANI) != 0) ?
"bbf-xpon-onu-types:onu-not-present-with-v-ani" :
"bbf-xpon-onu-types:onu-not-present-without-v-ani";
}
/* Check if the new state has to be notified */
if (!xpon_cterm_is_onu_state_notifiable(cterm_name, presence_state))
{
NC_LOG_INFO("cterm %s onu_id %u: skipping state transition report into presence state %s\n",
cterm_name, onu_id, presence_state);
return BCM_ERR_OK;
}
snprintf(notif_xpath, sizeof(notif_xpath),
"/ietf-interfaces:interfaces-state/interface[name='%s']/"
"bbf-xpon:channel-termination/bbf-xpon-onu-state:onu-presence-state-change", cterm_name);
notif = lyd_new_path(NULL, ctx, notif_xpath, NULL, 0, 0);
if (notif == NULL)
{
NC_LOG_ERR("Failed to create notification %s.\n", notif_xpath);
break;
}
snprintf(serial_number_string, sizeof(serial_number_string),
"%c%c%c%c%02X%02X%02X%02X",
serial_number[0], serial_number[1], serial_number[2], serial_number[3],
serial_number[4], serial_number[5], serial_number[6], serial_number[7]);
if (nc_ly_sub_value_add(NULL, notif, notif_xpath, "detected-serial-number", serial_number_string) == NULL)
{
break;
}
snprintf(date_time_string, sizeof(date_time_string),
"%.4d-%.2d-%.2dT%.2d:%.2d:%.2dZ",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
if (nc_ly_sub_value_add(NULL, notif, notif_xpath, "last-change", date_time_string) == NULL)
{
break;
}
if (nc_ly_sub_value_add(NULL, notif, notif_xpath, "onu-presence-state", (void *)(long)presence_state) == NULL)
{
break;
}
if (onu_id != XPON_ONU_ID_UNDEFINED)
{
char onu_id_str[16];
snprintf(onu_id_str, sizeof(onu_id_str), "%u", onu_id);
if (nc_ly_sub_value_add(NULL, notif, notif_xpath, "onu-id", onu_id_str) == NULL)
{
break;
}
}
sr_rc = sr_event_notif_send_tree(session, notif);
if (sr_rc != SR_ERR_OK)
{
NC_LOG_ERR("Failed to sent %s notification. Error '%s'\n",
notif_xpath, sr_strerror(sr_rc));
break;
}
NC_LOG_INFO("Sent '%s' notification for ONU %s on %s\n", presence_state, serial_number_string, cterm_name);
} while (0);
#else /* #ifdef TR385_ISSUE2 */
/* TR-385 issue 1 */
#define BBF_XPON_ONU_STATES_MODULE_NAME "bbf-xpon-onu-states"
sr_val_t values[5] = {};
uint32_t num_values;
time_t t = time(NULL);
struct tm tm = *localtime(&t);
char date_time_string[64];
char serial_number_string[13];
char *presence_state;
int sr_rc;
snprintf(serial_number_string, sizeof(serial_number_string),
"%c%c%c%c%02X%02X%02X%02X",
serial_number[0], serial_number[1], serial_number[2], serial_number[3],
serial_number[4], serial_number[5], serial_number[6], serial_number[7]);
values[0].xpath = "/" BBF_XPON_ONU_STATES_MODULE_NAME ":onu-state-change/detected-serial-number";
values[0].type = SR_STRING_T;
values[0].data.string_val = serial_number_string;
snprintf(date_time_string, sizeof(date_time_string),
"%.4d-%.2d-%.2dT%.2d:%.2d:%.2dZ",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
values[1].xpath = "/" BBF_XPON_ONU_STATES_MODULE_NAME ":onu-state-change/onu-state-last-change";
values[1].type = SR_STRING_T;
values[1].data.string_val = date_time_string;
values[2].xpath = "/" BBF_XPON_ONU_STATES_MODULE_NAME ":onu-state-change/onu-state";
values[2].type = SR_IDENTITYREF_T;
if ((presence_flags & XPON_ONU_PRESENCE_FLAG_ONU) != 0)
{
presence_state = ((presence_flags & XPON_ONU_PRESENCE_FLAG_V_ANI) != 0) ?
"bbf-xpon-onu-types:onu-present-and-on-intended-channel-termination" :
"bbf-xpon-onu-types:onu-present-and-unexpected";
}
else
{
presence_state = ((presence_flags & XPON_ONU_PRESENCE_FLAG_V_ANI) != 0) ?
"bbf-xpon-onu-types:onu-not-present-with-v-ani" :
"bbf-xpon-onu-types:onu-not-present-without-v-ani";
}
values[2].data.string_val = presence_state;
num_values = 3;
if (onu_id != XPON_ONU_ID_UNDEFINED)
{
values[3].xpath = "/" BBF_XPON_ONU_STATES_MODULE_NAME ":onu-state-change/onu-id";
values[3].type = SR_UINT32_T;
values[3].data.uint32_val = onu_id;
++num_values;
}
if (cterm_name != NULL)
{
values[num_values].xpath = "/" BBF_XPON_ONU_STATES_MODULE_NAME ":onu-state-change/channel-termination-ref";
values[num_values].type = SR_STRING_T;
values[num_values].data.string_val = (char *)(long)cterm_name;
++num_values;
}
sr_rc = sr_event_notif_send(bcm_netconf_session_get(), "/" BBF_XPON_ONU_STATES_MODULE_NAME ":onu-state-change",
values, num_values);
if (sr_rc == SR_ERR_OK)
{
NC_LOG_INFO("Sent '%s' notification for ONU %s on %s\n", presence_state, serial_number_string, cterm_name);
}
else
{
NC_LOG_DBG("Failed to sent state change notification for ONU %s on %s. Error '%s'\n",
serial_number_string, cterm_name, sr_strerror(sr_rc));
}
#endif
return (sr_rc == SR_ERR_OK) ? BCM_ERR_OK : BCM_ERR_INTERNAL;
}
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#ifndef BCMOS_COMMON2_H_
#define BCMOS_COMMON2_H_
#ifndef BCMOS_SYSTEM_H_
#error Please do not include bcmos_common2.h directly. Include bcmos_system.h
#endif
/* \addtogroup system
* @{
*/
#ifndef likely
#define likely(x) (x)
#endif
#ifndef unlikely
#define unlikely(x) (x)
#endif
#define BCMOS_MAX_NAME_LENGTH 48
/** \addtogroup system_task
* @{
*/
/** Task control block */
struct bcmos_task
{
/* OS independent fields */
bcmos_task_parm parm; /**< Task creation parameters */
bcmos_module *modules[BCMOS_MAX_MODULES_PER_TASK];
uint32_t active_modules; /**< Bitmask of modules for which events are pending */
bcmos_sem active_sem; /**< Semaphore used to wait for module activity */
bcmos_fastlock active_lock; /**< Lock protecting active_modules */
bcmos_module_id current_module; /**< Current module */
bcmos_bool destroy_request; /**< Task destroy request pending */
bcmos_bool destroyed; /**< Set by task handler before it terminates */
STAILQ_ENTRY(bcmos_task) list; /**< Next task pointer */
char name[BCMOS_MAX_NAME_LENGTH]; /**< Task name */
bcmos_sys_task sys_task; /**< OS-specific task extension */
uint32_t magic; /* magic number */
#define BCMOS_TASK_MAGIC (('t' << 24) | ('a' << 16) | ('s' << 8) | 'k')
#define BCMOS_TASK_MAGIC_DESTROYED (('t' << 24) | ('a' << 16) | ('s' << 8) | '~')
};
/** \addtogroup system_mem
* @{
*/
#ifndef BCMOS_CALLOC_INLINE
/** Allocate memory from the main heap and clear it
* \ingroup system_heap
* \param[in] size
* \returns memory block pointer or NULL
*/
#ifndef BCMOS_HEAP_DEBUG
static inline void *bcmos_calloc(uint32_t size)
{
void *ptr = bcmos_alloc(size);
#else
static inline void *_bcmos_calloc(uint32_t size)
{
void *ptr = _bcmos_alloc(size);
#endif
if (ptr)
{
/* If using heap debug feature, the pointer returned by _bcmos_alloc() is the user pointer, meaning after the debug header. */
#ifdef BCMOS_HEAP_DEBUG
size -= BCMOS_HEAP_DEBUG_OVERHEAD;
#endif
memset(ptr, 0, size);
}
return ptr;
}
#endif /* #ifndef BCMOS_CALLOC_INLINE */
#ifndef BCMOS_DMA_ADDR_T_DEFINED
typedef unsigned long dma_addr_t;
#endif
#ifndef BCMOS_DMA_ALLOC_FREE_INLINE
/** Allocate DMA-able memory
* \param[in] device Device id
* \param[in] size Block size (bytes)
* \param[out] dma_addr DMA address
* \returns memory block pointer or NULL
*/
void *bcmos_dma_alloc(uint8_t device, uint32_t size, dma_addr_t *dma_addr);
/** Release DMA-able memory
* \param[in] device Device id
* \param[in] ptr Block pointer
*/
void bcmos_dma_free(uint8_t device, void *ptr);
#endif /* #ifndef BCMOS_DMA_ALLOC_FREE_INLINE */
#ifndef BCMOS_VIRT_TO_PHYS_INLINE
/** Convert virtual address to physical address
*
* \param[in] va Virtual address
* \returns - physical address va is mapped to
*/
unsigned long bcmos_virt_to_phys(void *va);
#endif /* #ifndef BCMOS_VIRT_TO_PHYS_INLINE */
/** @} */
/** \addtogroup blk_pool
* @{
*/
/* Memory block header */
typedef struct bcmos_memblk bcmos_memblk;
/* Memory block list */
typedef STAILQ_HEAD(, bcmos_memblk) bcmos_memblk_list;
/* Block memory pool control block */
struct bcmos_blk_pool
{
bcmos_fastlock lock; /**< Pool protection lock */
bcmos_memblk_list free_list;/**< Free block list */
#ifdef BCMOS_BLK_POOL_DEBUG
DLIST_HEAD(, bcmos_memblk) allocated_list; /**< Allocated block list */
#endif
bcmos_blk_pool_parm parm; /**< Pool parameters */
bcmos_blk_pool_stat stat; /**< Pool statistics */
void *start; /**< Pool start pointer */
char name[BCMOS_MAX_NAME_LENGTH]; /**< Pool name */
uint32_t magic; /**< magic number */
#define BCMOS_BLK_POOL_VALID (('b'<<24) | ('l' << 16) | ('p' << 8) | 'o')
#define BCMOS_BLK_POOL_DELETED (('b'<<24) | ('l' << 16) | ('p' << 8) | '~')
STAILQ_ENTRY(bcmos_blk_pool) list; /* Pool list */
};
/* Total memory occupied by all block pools */
extern uint32_t bcmos_total_blk_pool_size;
/** @} blk_pool */
/** \addtogroup system_msg
* @{
*/
/** Release message
* \param[in] msg Message handle
*/
static inline void bcmos_msg_free(bcmos_msg *msg)
{
if (msg->release)
{
msg->release(msg);
}
else
{
bcmos_free(msg);
}
}
typedef STAILQ_HEAD(, bcmos_msg) bcmos_msg_list;
/** Simple Message queue control block.
* Simple message queue doesn't support waiting on.
* It is used in module queue mechanisms.
*/
typedef struct bcmos_msg_queue_nw
{
bcmos_msg_queue_parm parm; /**< Queue parameters */
bcmos_msg_queue_stat stat; /**< Queue statistics */
bcmos_fastlock lock; /**< Queue protection lock */
bcmos_msg_list msgl; /**< Message list */
bcmos_msg_list msgl_urg; /**< Urgent message list */
uint32_t flags; /**< Queue flags */
} bcmos_msg_queue_nw;
/** Message queue control block */
struct bcmos_msg_queue
{
bcmos_msg_queue_nw q; /**< Queue control block */
bcmos_sem m; /**< Mutex to suspend waiting task on */
bcmos_bool is_waiting; /**< TRUE if task is waiting on queue */
char name[BCMOS_MAX_NAME_LENGTH]; /**< Queue name */
#ifdef BCMOS_MSG_QUEUE_REMOTE_SUPPORT
long ep; /**< Endpoint handle (e.g., socket) */
void *ep_extra_data; /**< Extra data - depending on ep type */
uint32_t ep_extra_data_size;/**< Extra data size */
uint8_t *send_buf; /**< Send buffer */
uint8_t *recv_buf; /**< Receive buffer */
bcmos_msg_addr last_addr; /**< Sender address of the last received message */
#define BCMOS_MSG_MAX_ADDR_LENGTH 256 /**< Max sender address length */
bcmos_mutex send_lock; /**< Mutex that protects send_buf */
#endif
uint32_t magic; /**< magic number */
#define BCMOS_MSG_QUEUE_VALID (('m'<<24) | ('q' << 16) | ('u' << 8) | 'e')
#define BCMOS_MSG_QUEUE_DELETED (('m'<<24) | ('q' << 16) | ('u' << 8) | '~')
STAILQ_ENTRY(bcmos_msg_queue) list; /* Queue list */
};
/** Message queue group control block */
struct bcmos_msg_qgroup
{
bcmos_msg_qgroup_parm parm; /**< Queue group parameters */
bcmos_msg_list *msgl; /**< Array of parm.nqueues message lists */
bcmos_msg_queue_stat stat; /**< Queue group statistics */
bcmos_sem m; /**< Mutex to suspend waiting task on */
bcmos_fastlock lock; /**< Queue group protection lock */
uint32_t active_mask; /**< Bitmask of queues containing messages */
bcmos_bool is_waiting; /**< TRUE if task is waiting on queue group */
char name[BCMOS_MAX_NAME_LENGTH]; /**< Queue group name */
uint32_t magic; /**< magic number */
#define BCMOS_MSG_QGROUP_VALID (('m'<<24) | ('q' << 16) | ('g' << 8) | 'r')
#define BCMOS_MSG_QGROUP_DELETED (('m'<<24) | ('q' << 16) | ('g' << 8) | '~')
STAILQ_ENTRY(bcmos_msg_qgroup) list; /* Queue group list */
};
/** Message pool control block */
struct bcmos_msg_pool
{
bcmos_blk_pool blk_pool; /**< Underlying block memory pool */
bcmos_msg_pool_parm parm; /**< Pool parameters */
};
/* Total memory occupied by all message pools */
extern uint32_t bcmos_total_msg_pool_size;
/** @} system_msg */
/** \addtogroup system_timer */
/* Timer precision. Must be a multiple of 2.
* Timed expiration timestamp is rounded up to the nearest multiple of timer precision
*/
#define BCMOS_TIMER_PRECISION_US 32
#if (BCMOS_TIMER_PRECISION_US & (BCMOS_TIMER_PRECISION_US - 1))
#error BCMOS_TIMER_PRECISION_US must be a multiple of 2
#endif
/* There are 2 timer implementations
* - DLIST-based - works well when most of active timers have the same duration
* - RB-tree based - more expensive in simple case, but scales better for large number of timers
* with arbitrary durations
*/
#define BCMOS_TIMER_RB_TREE
/** Timer control block */
struct bcmos_timer
{
bcmos_msg msg; /**< Timer message */
bcmos_timer_parm parm; /**< Timer parameters */
F_bcmos_timer_handler handler; /**< Timer handler */
uint32_t period; /**< Timer period (us) if periodic */
uint32_t expire_at; /**< Timestamp when timer should expire */
uint32_t flags; /* Internal flags */
#define BCMOS_TIMER_FLAG_RUNNING 0x00000001 /* Timer is running */
#define BCMOS_TIMER_FLAG_EXPIRED 0x00000002 /* Timer has expired, but not yet handled */
#define BCMOS_TIMER_FLAG_ACTIVE (BCMOS_TIMER_FLAG_RUNNING | BCMOS_TIMER_FLAG_EXPIRED)
#define BCMOS_TIMER_FLAG_VALID 0x00000004
bcmos_msg_queue_nw *queue; /**< Queue expired timer is on */
bcmos_task *task; /**< Task that executes timer handler (switches between module and system) */
bcmos_task *owner_task; /**< Task that owns the timer (owner of the module at creation time) */
#ifdef BCMOS_TIMER_RB_TREE
RB_ENTRY(bcmos_timer) pool_entry; /**< Timer pool entry */
#else
TAILQ_ENTRY(bcmos_timer) pool_entry;
#endif
#ifdef BCMOS_TIMER_DEBUG
uint32_t magic; /* magic number */
#define BCMOS_TIMER_MAGIC (('t' << 24) | ('i' << 16) | ('m' << 8) | 'r')
#define BCMOS_TIMER_MAGIC_DESTROYED (('t' << 24) | ('i' << 16) | ('m' << 8) | '~')
/* Unlike the above entries, which the timer enters only when it is started, we need a separate entry (linked list)
* for all timer, so in debug time we can traverse all system timers. */
STAILQ_ENTRY(bcmos_timer) list; /**< Next timer pointer */
#endif
};
/** Check if timer is valid
* \param[in] timer Timer handle
* \returns TRUE if timer is valid
*/
static inline bcmos_bool bcmos_timer_is_valid(const bcmos_timer *timer)
{
return (timer->flags & BCMOS_TIMER_FLAG_VALID) != 0;
}
/** Check if timer is running
* \param[in] timer Timer handle
* \returns TRUE if timer is running
*/
static inline bcmos_bool bcmos_timer_is_running(const bcmos_timer *timer)
{
return ((timer->flags & BCMOS_TIMER_FLAG_RUNNING) != 0) ||
(timer->parm.periodic && ((timer->flags & BCMOS_TIMER_FLAG_EXPIRED) != 0));
}
static inline bcmos_timer *_bcmos_msg_to_timer(bcmos_msg *msg)
{
BUG_ON(msg->type != BCMOS_MSG_ID_INTERNAL_TIMER);
return (bcmos_timer *)msg;
}
/** @} */
/** \addtogroup system_module
* @{
*/
/** Module control block */
struct bcmos_module
{
bcmos_module_parm parm; /**< Module parameters */
bcmos_module_id id; /**< Module id */
int idx; /**< Module index in task control block */
bcmos_msg_queue_nw msgq; /**< Message queue */
bcmos_task *my_task; /**< Task the module is associated with */
void *context; /**< User-defined context */
char name[BCMOS_MAX_NAME_LENGTH]; /**< Module name */
bcmos_bool deleted; /**< TRUE=module is being deleted */
};
/** @} system_module */
/** \addtogroup system_event
* @{
*/
/** Event control block */
struct bcmos_event
{
bcmos_msg msg; /**< Message header. Used to deliver event to module's queue */
bcmos_event_id id; /**< Event set id */
bcmos_event_parm parm; /**< Event parameters */
bcmos_fastlock lock; /**< Protects event control block */
uint32_t active_bits; /**< Active event bits */
bcmos_sem m; /**< Mutex to suspend task on. Traditional mode only */
bcmos_bool is_waiting; /**< TRUE if task is waiting for event */
char name[BCMOS_MAX_NAME_LENGTH]; /**< Event name */
};
static inline bcmos_event *_bcmos_msg_to_event(bcmos_msg *msg)
{
BUG_ON(msg->type != BCMOS_MSG_ID_INTERNAL_EVENT);
return (bcmos_event *)msg;
}
/** @} system_event */
/*
* Low level services
*/
/** \addtogroup system_buf
* @{
*/
#if !defined(BCMOS_BUF_OS_SPECIFIC) && !defined(BCMOS_BUF_DO_NOT_INLINE)
#define BCMOS_BUF_DATA_INLINE
#endif
#ifdef BCMOS_BUF_INLINE
#define BCMOS_BUF_ALLOC_FREE_INLINE
#define BCMOS_BUF_DATA_INLINE
#endif
#ifndef BCMOS_BUF_DATA_GUARD
#define BCMOS_BUF_DATA_GUARD 0
#endif
#ifndef BCMOS_BUF_DATA_ALIGNMENT
#define BCMOS_BUF_DATA_ALIGNMENT 64
#endif
#ifndef BCMOS_BUF_OS_SPECIFIC
/* Generic (not os-specific) sysb implementation */
/*
* Network / transport buffer
*/
/* Memory block list */
typedef STAILQ_HEAD(, bcmos_buf) bcmos_buf_list_head;
typedef struct
{
bcmos_buf_list_head head; /**< Buffer list head */
} bcmos_buf_queue;
/* System buffer. We probably can use mbuf as well. */
struct bcmos_buf
{
uint8_t *start;
uint8_t *data;
bcmos_blk_pool *pool;
uint32_t size;
uint32_t len;
STAILQ_ENTRY(bcmos_buf) list; /**< Next buffer pointer */
uint8_t channel;
};
#endif /* #ifndef BCMOS_BUF_OS_SPECIFIC */
#ifndef BCMTR_BUF_EXTRA_HEADROOM
#define BCMTR_BUF_EXTRA_HEADROOM 64
#endif
#ifndef BCMOS_BUF_ALLOC_FREE_INLINE
/** Allocate transport buffer.
* The buffer can accommodate up to size bytes of data.
* In addition it reserves BCMTR_BUF_EXTRA_HEADROOM headroom bytes
* for extra headers.
*
* \param[in] size Data size
* \returns buffer pointer or NULL if no memory
*/
bcmos_buf *bcmos_buf_alloc(uint32_t size);
/** Release transport buffer allocated by bcmos_buf_alloc()
*
* \param[in] buf Buffer to be released
*/
void bcmos_buf_free(bcmos_buf *buf);
/** Clone transport buffer
*
* \param[in] buf Buffer to be cloned
* \returns buffer pointer or NULL if no memory
*/
bcmos_buf *bcmos_buf_clone(bcmos_buf *buf);
#endif /* BCMOS_BUF_ALLOC_FREE_INLINE */
#ifndef BCMOS_BUF_DATA_INLINE
/** Get data length
*
* \param[in] buf Buffer
* \returns data length
*/
uint32_t bcmos_buf_length(bcmos_buf *buf);
/** Set data length
*
* \param[in] buf Buffer
* \param[in] length Data length
* \returns 0=OK, or BCM_ERR_OVERFLOW if length exceeds size
*/
bcmos_errno bcmos_buf_length_set(bcmos_buf *buf, uint32_t length);
/** Get buffer data pointer.
* \param[in] buf Buffer
* \returns data pointer
*/
uint8_t *bcmos_buf_data(bcmos_buf *buf);
/* Add data block to the end of buffer data.
* It is up to the caller to ensure that there is room in the buffer
* Returns pointer of the beginning of the added block
*/
uint8_t *bcmos_buf_tail_push(bcmos_buf *buf, uint32_t length);
/* Add data block to the end of buffer data.
* It is up to the caller to ensure that there is room in the buffer
* Returns pointer of the beginning of the added block
*/
uint8_t * bcmos_buf_head_push(bcmos_buf *buf, uint32_t length);
/* Pull data from the head of the buffer
* Returns pointer to the old head
*/
uint8_t *bcmos_buf_head_pull(bcmos_buf *buf, uint32_t length);
/* Get buffer channel. */
uint8_t bcmos_buf_channel(bcmos_buf *buf);
/* Set buffer channel. */
void bcmos_buf_channel_set(bcmos_buf *buf, uint8_t channel);
/** Initialize buffer queue
* \param[in] q Buffer queue
*/
void bcmos_buf_queue_init(bcmos_buf_queue *q);
/* Check if buffer queue is empty
* \param[in] q Buffer queue
* \returns TRUE if the queue is empty
*/
bcmos_bool bcmos_buf_queue_is_empty(bcmos_buf_queue *q);
/** Enqueue buffer
*
* Must be called under lock, e.g., q->lock
*
* \param[in] q Buffer queue
* \param[in] buf Buffer
*/
void bcmos_buf_queue_put(bcmos_buf_queue *q, bcmos_buf *buf);
/* Dequeue buffer
*
* Must be called under lock, e.g., q->lock
*
* Remove and return the 1st queued buffer.
* \param[in] q Buffer queue
* \returns the buffer pointer
*/
bcmos_buf *bcmos_buf_queue_get(bcmos_buf_queue *q);
/* Peek into queue and return the 1st buffer without dequeing it
*
* Must be called under lock, e.g., q->lock
* \param[in] q Buffer queue
* \returns the buffer pointer
*/
bcmos_buf *bcmos_buf_queue_peek(bcmos_buf_queue *q);
#else /* #ifndef BCMOS_BUF_DATA_INLINE */
#ifndef BCMOS_BUF_OS_SPECIFIC
/** Initialize buffer queue
* \param[in] q Buffer queue
*/
static inline void bcmos_buf_queue_init(bcmos_buf_queue *q)
{
STAILQ_INIT(&q->head);
}
/* Check if buffer queue is empty
* \param[in] q Buffer queue
* \returns TRUE if the queue is empty
*/
static inline bcmos_bool bcmos_buf_queue_is_empty(bcmos_buf_queue *q)
{
return (bcmos_bool)STAILQ_EMPTY(&q->head);
}
/** Enqueue buffer
*
* Must be called under lock, e.g., q->lock
*
* \param[in] q Buffer queue
* \param[in] buf Buffer
*/
static inline void bcmos_buf_queue_put(bcmos_buf_queue *q, bcmos_buf *buf)
{
STAILQ_INSERT_TAIL(&q->head, buf, list);
}
/* Dequeue buffer
*
* Must be called under lock, e.g., q->lock
*
* Remove and return the 1st queued buffer.
* \param[in] q Buffer queue
* \returns the buffer pointer
*/
static inline bcmos_buf *bcmos_buf_queue_get(bcmos_buf_queue *q)
{
bcmos_buf *buf;
buf = STAILQ_FIRST(&q->head);
if (buf)
STAILQ_REMOVE_HEAD(&q->head, list);
return buf;
}
/* Peek into queue and return the 1st buffer without dequeing it
*
* Must be called under lock, e.g., q->lock
* \param[in] q Buffer queue
* \returns the buffer pointer
*/
static inline bcmos_buf *bcmos_buf_queue_peek(bcmos_buf_queue *q)
{
return STAILQ_FIRST(&q->head);
}
/* Initialize buffer */
static inline bcmos_buf *bcmos_buf_init(bcmos_buf *buf, uint8_t *start,
uint8_t *data, uint32_t size, uint32_t len)
{
BUG_ON((void *)(buf +1) != start);
buf->start = start;
buf->data = data;
buf->size = size;
buf->len = len;
buf->pool = NULL;
return buf;
}
/* Get data length */
static inline uint32_t bcmos_buf_length(bcmos_buf *buf)
{
return buf->len;
}
/* Set data length */
static inline bcmos_errno bcmos_buf_length_set(bcmos_buf *buf, uint32_t length)
{
if (unlikely(length > buf->size - (buf->data - buf->start)))
{
BCMOS_TRACE_ERR("!!!%s: length=%u size=%u data=%p start=%p data-start=%u\n",
__FUNCTION__, length, buf->size, buf->data, buf->start, (uint32_t)(buf->data - buf->start));
return BCM_ERR_OVERFLOW;
}
buf->len = length;
return BCM_ERR_OK;
}
/* Get buffer data pointer. */
static inline uint8_t *bcmos_buf_data(bcmos_buf *buf)
{
return buf->data;
}
/* Add data block to the end of buffer data.
* It is up to the caller to ensure that there is room in the buffer
* Returns pointer of the beginning of the added block
*/
static inline uint8_t *bcmos_buf_tail_push(bcmos_buf *buf, uint32_t length)
{
uint8_t *end = buf->start + buf->size;
uint8_t *tail = buf->data + buf->len;
BUG_ON(tail + length > end);
buf->len += length;
return tail;
}
/* Add data block to beginning of buffer data.
* It is up to the caller to ensure that there is sufficient headroom in the buffer
* Returns pointer to the new head
*/
static inline uint8_t *bcmos_buf_head_push(bcmos_buf *buf, uint32_t length)
{
BUG_ON(buf->data - buf->start < length);
buf->data -= length;
buf->len += length;
return buf->data;
}
/* Pull data from the head of the buffer
* Returns pointer to the old head
*/
static inline uint8_t *bcmos_buf_head_pull(bcmos_buf *buf, uint32_t length)
{
uint8_t *old_head = buf->data;
BUG_ON(buf->len < length);
buf->data += length;
buf->len -= length;
return old_head;
}
/* Get buffer channel. */
static inline uint8_t bcmos_buf_channel(bcmos_buf *buf)
{
return buf->channel;
}
/* Set buffer channel. */
static inline void bcmos_buf_channel_set(bcmos_buf *buf, uint8_t channel)
{
buf->channel = channel;
}
#endif /* #ifndef BCMOS_BUF_OS_SPECIFIC */
#endif /* #ifdef BCMOS_BUF_DATA_INLINE */
/** @} bcmos_buf */
/** \addtogroup system_cache
* @{
*/
#ifndef BCMOS_CACHE_INLINE
/** Invalidate address area in data cache. Dirty cache lines content is discarded.
* \param[in] start Address area start
* \param[in] size Address area size
*/
void bcmos_dcache_inv(void *start, uint32_t size);
/** Flush address area in data cache. Dirty cache lines are committed to memory.
* \param[in] start Address area start
* \param[in] size Address area size
*/
void bcmos_dcache_flush(void *start, uint32_t size);
#endif /* BCMOS_CACHE_INLINE */
/** Prepare for DMA write.
* On h/w platforms that support DMA-cache coherency, this function should
* perform write barrier.
* On platforms that don't support DMA cache coherency this function should
* flush the relevant dcache area
*
* \param[in] start DMA buffer start address
* \param[in] size DMA buffer size
*/
static inline void bcmos_prepare_for_dma_write(void *start, uint32_t size)
{
#ifdef BCMOS_DMA_CACHE_COHERENCY
bcmos_barrier();
#else
bcmos_dcache_flush(start, size);
#endif
}
/** Prepare for DMA read.
* On h/w platforms that support DMA-cache coherency, this function should
* perform write barrier.
* On platforms that don't support DMA cache coherency this function should
* invalidate the relevant dcache area
*
* \param[in] start DMA buffer start address
* \param[in] size DMA buffer size
*/
static inline void bcmos_prepare_for_dma_read(void *start, uint32_t size)
{
#ifdef BCMOS_DMA_CACHE_COHERENCY
bcmos_barrier();
#else
bcmos_dcache_inv(start, size);
#endif
}
/** @} system_cache */
/** \addtogroup system_interrupt
* @{
*/
#ifdef BCMOS_INTERRUPT_INLINE
#define BCMOS_INTERRUPT_CONNECT_DISCONNECT_INLINE
#define BCMOS_INTERRUPT_ENABLE_DISABLE_INLINE
#endif
#ifndef BCMOS_INTERRUPT_CONNECT_DISCONNECT_INLINE
/** Connect system interrupt
* \param[in] irq IRQ number
* \param[in] cpu CPU number (for SMP)
* \param[in] flags IRQ flags
* \param[in] isr ISR
* \param[in] name device name
* \param[in] priv Private cookie
* \returns 0=OK, <0- error
*/
int bcmos_int_connect(int irq, int cpu, int flags,
int (*isr)(int irq, void *priv), const char *name, void *priv);
/** Disconnect system interrupt
* \param[in] irq IRQ number
* \param[in] priv Private cookie passed in bcmos_int_connect()
* \returns 0=OK, <0- error
*/
void bcmos_int_disconnect(int irq, void *priv);
#endif
#ifndef BCMOS_INTERRUPT_ENABLE_DISABLE_INLINE
/** Unmask IRQ
* \param[in] irq IRQ
*/
void bcmos_int_enable(int irq);
/** Mask IRQ
* \param[in] irq IRQ
*/
void bcmos_int_disable(int irq);
#endif
#ifndef IRQ_HANDLED
#define IRQ_HANDLED (1 << 0)
#endif
/** @} */
/* Get char, put char support */
#ifndef BCMOS_GETCHAR_INLINE
static inline int bcmos_getchar(void)
{
return getchar();
}
#endif
#ifndef BCMOS_PUTCHAR_INLINE
void bcmos_putchar(int c);
#endif
#ifndef BCMOS_SEM_POST_IS_ALLOWED_INLINE
static inline bcmos_bool bcmos_sem_post_is_allowed(void)
{
return BCMOS_TRUE;
}
#endif
/*
* File IO
*/
typedef struct bcmos_file bcmos_file;
typedef enum
{
BCMOS_FILE_FLAG_NONE = 0,
BCMOS_FILE_FLAG_READ = 0x1,
BCMOS_FILE_FLAG_WRITE = 0x2,
BCMOS_FILE_FLAG_APPEND = 0x4,
} bcmos_file_flag;
#ifdef BCMOS_FILE_IO_OS_SPECIFIC
bcmos_file *bcmos_file_open(const char *path, bcmos_file_flag flags);
bcmos_errno bcmos_file_seek(bcmos_file *file, unsigned long offset);
int bcmos_file_read(bcmos_file *file, void *data, uint32_t size);
int bcmos_file_write(bcmos_file *file, const void *data, uint32_t size);
void bcmos_file_close(bcmos_file *file);
char *bcmos_file_gets(bcmos_file *file, char *s, int size);
#else
static inline bcmos_file *bcmos_file_open(const char *path, bcmos_file_flag flags)
{
return NULL;
}
static inline int bcmos_file_read(bcmos_file *file, void *data, uint32_t size)
{
return BCM_ERR_NOT_SUPPORTED;
}
static inline int bcmos_file_write(bcmos_file *file, const void *data, uint32_t size)
{
return BCM_ERR_NOT_SUPPORTED;
}
static inline bcmos_errno bcmos_file_seek(bcmos_file *file, unsigned long offset)
{
return BCM_ERR_NOT_SUPPORTED;
}
static inline void bcmos_file_close(bcmos_file *file)
{
}
static inline char *bcmos_file_gets(bcmos_file *file, char *s, int size)
{
return NULL;
}
#endif
#endif /* BCMOS_COMMON2_H_ */
<file_sep>/*
* <:copyright-BRCM:2016-2020:Apache:standard
*
* Copyright (c) 2016-2020 Broadcom. All Rights Reserved
*
* The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* :>
*
*****************************************************************************/
/*
* Init all module libraries
*/
#include <bcmolt_netconf_module_init.h>
#include <bcmolt_netconf_module_utils.h>
#ifdef NETCONF_MODULE_BBF_XPON
#include <bbf-xpon.h>
#endif
#ifdef NETCONF_MODULE_BBF_POLT_VOMCI
#include <bbf-vomci.h>
#endif
static nc_startup_options startup_options;
static sr_session_ctx_t *netconf_session;
bcmos_errno bcm_netconf_modules_init(sr_session_ctx_t *srs, struct ly_ctx *ly_ctx, const nc_startup_options *startup_opts)
{
bcmos_errno err = BCM_ERR_OK;
startup_options = *startup_opts;
netconf_session = srs;
/*
* Initialize modules
*/
#ifdef NETCONF_MODULE_BBF_XPON
#ifdef DUMMY_BBF_XPON
if (startup_options.dummy_tr385_management)
#endif
err = err ? err : bbf_xpon_module_init(srs, ly_ctx);
#endif
#ifdef NETCONF_MODULE_BBF_POLT_VOMCI
if (bcm_tr451_onu_management_is_enabled())
err = err ? err : bbf_polt_vomci_module_init(srs, ly_ctx);
#endif
/*
* Start modules
*/
#ifdef NETCONF_MODULE_BBF_XPON
#ifdef DUMMY_BBF_XPON
if (startup_options.dummy_tr385_management)
#endif
err = err ? err : bbf_xpon_module_start(srs, ly_ctx);
#endif
#ifdef NETCONF_MODULE_BBF_POLT_VOMCI
if (bcm_tr451_onu_management_is_enabled())
err = err ? err : bbf_polt_vomci_module_start(srs, ly_ctx);
#endif
return err;
}
void bcm_netconf_modules_exit(sr_session_ctx_t *srs, struct ly_ctx *ly_ctx)
{
#ifdef NETCONF_MODULE_BBF_XPON
#ifdef DUMMY_BBF_XPON
if (startup_options.dummy_tr385_management)
#endif
bbf_xpon_module_exit(srs, ly_ctx);
#endif
#ifdef NETCONF_MODULE_BBF_POLT_VOMCI
if (bcm_tr451_onu_management_is_enabled())
bbf_polt_vomci_module_exit(srs, ly_ctx);
#endif
}
const nc_startup_options *netconf_agent_startup_options_get(void)
{
return &startup_options;
}
uint8_t netconf_agent_olt_id(void)
{
return startup_options.olt;
}
/* TR-451 support */
bcmos_bool bcm_tr451_onu_management_is_enabled(void)
{
#ifdef NETCONF_MODULE_BBF_POLT_VOMCI
return startup_options.tr451_onu_management;
#else
return BCMOS_FALSE;
#endif
}
sr_session_ctx_t *bcm_netconf_session_get(void)
{
return netconf_session;
}
<file_sep>/*
<:copyright-BRCM:2016-2019:Apache:standard
Copyright (c) 2016-2019 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
* :>
*/
#ifndef BCMOS_PACK_H_
#define BCMOS_PACK_H_
/*
* Packing macros
*
* Usage:
* struct __PACKED_ATTR_START__ my_packed_struct
* {
* ...
* } __PACKED_ATTR_END__ ;
*
*/
#ifdef __GNUC__
#define __PACKED_ATTR_START__
#define __PACKED_ATTR_END__ __attribute__ ((packed))
#else
#error define __PACKED_ATTR_START__, __PACKED_ATTR_END__ for this compiler
#endif
/*
* Macros for bit-field manipulation
* For each field F requires 2 constants
* - F_S - field shift
* - F_W - field width
*/
#define BCM_FIELD_GET(_w, _f) (((_w)>>_f ## _S) & ((1 << _f ## _W) - 1))
#define BCM_FIELD(_f, _v) ((_v & ((1 << _f ## _W) - 1)) << _f ## _S)
#define BCM_FIELD_SET(_w, _f, _v) (_w) |= BCM_FIELD(_f, _v)
#endif /* BCMOS_PACK_H_ */
<file_sep># Make option for enabling/disabling CLI
bcm_make_normal_option(CLI BOOL "Enable host side CLI" y)
bcm_module_name(cli)
bcm_module_header_paths(PUBLIC .)
# ENABLE_CLI is always set in embedded side.
if("${SUBSYSTEM}" STREQUAL "embedded")
bcm_module_definitions(PUBLIC -DENABLE_CLI)
set(CLI "y" PARENT_SCOPE)
set(CLI "y")
endif()
if(${CLI})
bcm_module_dependencies(PUBLIC os utils)
if(NOT OPEN_SOURCE)
bcm_module_dependencies(PUBLIC metadata)
endif()
bcm_module_definitions(PUBLIC -DENABLE_CLI)
bcm_make_normal_option(CLI_LINENOISE BOOL "Enable linenoise CLI integration" y)
if(${CLI_LINENOISE})
bcm_module_dependencies(PRIVATE linenoise)
endif()
bcm_module_srcs(bcmcli_session.c bcmcli.c)
endif()
bcm_create_lib_target()
# Add files to the GitHub part of the release tree.
bcm_github_install(./*
RELEASE github/cli
EXCLUDE_FROM_RELEASE unitest)
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#include <bcm_tr451_polt.h>
#include <bcm_tr451_polt_internal.h>
/* Print OMCI send/receive statistics */
static bcmos_errno polt_cli_stats(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t nparms)
{
VomciConnectionStats stats = {};
const char *ep_name = nullptr;
const char *peer_name = nullptr;
do
{
bcm_tr451_stats_get(&ep_name, &peer_name, &stats);
if (ep_name == nullptr)
break;
bcmcli_print(session,
"Endpoint %s peer=%s: to-ONU: gRPC=%u OMCI=%u discarded=%u from-ONU: OMCI=%u gRPC=%u discarded=%u\n",
ep_name, peer_name,
stats.packets_vomci_to_onu_recv, stats.packets_vomci_to_onu_sent, stats.packets_vomci_to_onu_disc,
stats.packets_onu_to_vomci_recv, stats.packets_onu_to_vomci_sent, stats.packets_onu_to_vomci_disc);
} while (BCMOS_TRUE);
return BCM_ERR_OK;
}
/* Create client/server endpoint */
static bcmos_errno polt_cli_endpoint_create(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t nparms)
{
bcmos_bool is_server = (bcmos_bool)parm[0].value.number;
tr451_endpoint ep = {
.name = (const char *)parm[1].value.string,
.host_name = bcmcli_parm_is_set(session, &parm[3]) ? (const char *)parm[3].value.string : NULL,
.port = (uint16_t)parm[2].value.number
};
bcmos_errno rc;
if (is_server)
{
tr451_server_endpoint server_ep = { .endpoint = ep };
rc = bcm_tr451_polt_grpc_server_create(&server_ep);
}
else
{
tr451_client_endpoint *client_ep;
if (ep.host_name == NULL)
{
bcmcli_print(session, "Hostname is required for client endpoint\n");
return BCM_ERR_PARM;
}
client_ep = bcm_tr451_client_endpoint_alloc(ep.name);
rc = bcm_tr451_client_endpoint_add_entry(client_ep, &ep);
rc = rc ? rc : bcm_tr451_polt_grpc_client_create(client_ep);
bcm_tr451_client_endpoint_free(client_ep);
}
return rc;
}
/* Delete client/server endpoint */
static bcmos_errno polt_cli_endpoint_delete(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t nparms)
{
bcmos_bool is_server = (bcmos_bool)parm[0].value.number;
const char *name = (const char *)parm[1].value.string;
bcmos_errno rc;
if (is_server)
{
rc = bcm_tr451_polt_grpc_server_delete(name);
}
else
{
rc = bcm_tr451_polt_grpc_client_delete(name);
}
return rc;
}
/* Create client/server filter */
static bcmos_errno polt_cli_create_filter(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t nparms)
{
tr451_polt_filter filter = {
.name = (const char *)parm[0].value.string,
.type = (tr451_polt_filter_type)parm[3].value.number,
.priority = (uint16_t)parm[1].value.number,
};
const char *ep_name = (const char *)parm[2].value.string;
uint16_t vendor_id = (uint16_t)parm[4].value.number;
uint16_t vendor_specific = (uint16_t)parm[5].value.number;
bcmos_errno rc;
if (filter.type == TR451_FILTER_TYPE_ANY)
{
if (bcmcli_parm_is_set(session, &parm[4]) || bcmcli_parm_is_set(session, &parm[5]))
{
bcmcli_print(session, "vendor_id and/or vendor_specific parameters are incompatible with filter mode ANY\n");
return BCM_ERR_PARM;
}
}
else if (filter.type == TR451_FILTER_TYPE_VENDOR_ID)
{
if (!bcmcli_parm_is_set(session, &parm[4]))
{
bcmcli_print(session, "vendor_id is required for filter mode vendor_id\n");
return BCM_ERR_PARM;
}
if (bcmcli_parm_is_set(session, &parm[5]))
{
bcmcli_print(session, "vendor_specific is incompatible with filter mode vendor_id\n");
return BCM_ERR_PARM;
}
filter.serial_number[0] = (vendor_id >> 24) & 0xff;
filter.serial_number[1] = (vendor_id >> 16) & 0xff;
filter.serial_number[2] = (vendor_id >> 8) & 0xff;
filter.serial_number[3] = vendor_id & 0xff;
}
else if (filter.type == TR451_FILTER_TYPE_SERIAL_NUMBER)
{
if (!bcmcli_parm_is_set(session, &parm[4]) || !bcmcli_parm_is_set(session, &parm[5]))
{
bcmcli_print(session, "vendor_id and vendor_specific are required for filter mode vendor_id\n");
return BCM_ERR_PARM;
}
filter.serial_number[0] = (vendor_id >> 24) & 0xff;
filter.serial_number[1] = (vendor_id >> 16) & 0xff;
filter.serial_number[2] = (vendor_id >> 8) & 0xff;
filter.serial_number[3] = vendor_id & 0xff;
filter.serial_number[4] = (vendor_specific >> 24) & 0xff;
filter.serial_number[5] = (vendor_specific >> 16) & 0xff;
filter.serial_number[6] = (vendor_specific >> 8) & 0xff;
filter.serial_number[7] = vendor_specific & 0xff;
}
rc = bcm_tr451_polt_filter_set(&filter, ep_name);
return rc;
}
/* Enable/disable client/server subsystem */
static bcmos_errno polt_cli_set_state(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t nparms)
{
bcmos_bool is_server = (bcmos_bool)parm[0].value.number;
bcmos_bool is_enable = (bcmos_bool)parm[1].value.number;
bcmos_errno rc;
if (is_server)
rc = bcm_tr451_polt_grpc_server_enable_disable(is_enable);
else
rc = bcm_tr451_polt_grpc_client_enable_disable(is_enable);
return rc;
}
/* Set authentication names */
static bcmos_errno polt_cli_set_auth_keys(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t nparms)
{
return bcm_tr451_auth_set(parm[0].value.string, parm[1].value.string, parm[2].value.string);
}
void bcm_tr451_polt_cli_init(void)
{
bcmcli_entry *dir;
static bcmcli_enum_val client_server_enum_table[] = {
{ .name = "client", .val = (long)BCMOS_FALSE },
{ .name = "server", .val = (long)BCMOS_TRUE },
BCMCLI_ENUM_LAST
};
static bcmcli_enum_val filter_enum_table[] = {
{ .name = "any", .val = (long)TR451_FILTER_TYPE_ANY },
{ .name = "vendor_id", .val = (long)TR451_FILTER_TYPE_VENDOR_ID },
{ .name = "serial_number", .val = (long)TR451_FILTER_TYPE_SERIAL_NUMBER },
BCMCLI_ENUM_LAST
};
dir = bcmcli_dir_add(NULL, "polt", "pOLT Debug", BCMCLI_ACCESS_ADMIN, NULL);
/* Enable/disable client/server subsystem */
{
static bcmcli_cmd_parm cmd_parms[] = {
BCMCLI_MAKE_PARM("client_server", "Client/Server", BCMCLI_PARM_ENUM, 0),
BCMCLI_MAKE_PARM("enable", "Enable", BCMCLI_PARM_ENUM, 0),
{ 0 }
} ;
cmd_parms[0].enum_table = client_server_enum_table;
cmd_parms[1].enum_table = bcmcli_enum_bool_table;
bcmcli_cmd_add(dir, "set_state", polt_cli_set_state, "Enable/disable client/server subsystem",
BCMCLI_ACCESS_ADMIN, NULL, cmd_parms);
}
/* Create an endpoint */
{
static bcmcli_cmd_parm cmd_parms[] = {
BCMCLI_MAKE_PARM("client_server", "Client/Server", BCMCLI_PARM_ENUM, 0),
BCMCLI_MAKE_PARM("name", "Endpoint name", BCMCLI_PARM_STRING, 0),
BCMCLI_MAKE_PARM("port", "port to listen at/connect to", BCMCLI_PARM_NUMBER, 0),
BCMCLI_MAKE_PARM("host", "host to listen at/connect to", BCMCLI_PARM_STRING, BCMCLI_PARM_FLAG_OPTIONAL),
{ 0 }
} ;
cmd_parms[0].enum_table = client_server_enum_table;
bcmcli_cmd_add(dir, "endpoint_create", polt_cli_endpoint_create, "Create a client/server endpoint",
BCMCLI_ACCESS_ADMIN, NULL, cmd_parms);
}
/* Delete an endpoint */
{
static bcmcli_cmd_parm cmd_parms[] = {
BCMCLI_MAKE_PARM("client_server", "Client/Server", BCMCLI_PARM_ENUM, 0),
BCMCLI_MAKE_PARM("name", "Endpoint name", BCMCLI_PARM_STRING, 0),
{ 0 }
} ;
cmd_parms[0].enum_table = client_server_enum_table;
bcmcli_cmd_add(dir, "endpoint_Delete", polt_cli_endpoint_delete, "Delete a client/server endpoint",
BCMCLI_ACCESS_ADMIN, NULL, cmd_parms);
}
/* Create a filter */
{
static bcmcli_cmd_parm cmd_parms[] = {
BCMCLI_MAKE_PARM("name", "Filter name", BCMCLI_PARM_STRING, 0),
BCMCLI_MAKE_PARM("priority", "Filter priority", BCMCLI_PARM_NUMBER, 0),
BCMCLI_MAKE_PARM("ep_name", "Endpoint name", BCMCLI_PARM_STRING, 0),
BCMCLI_MAKE_PARM("type", "Filter mode", BCMCLI_PARM_ENUM, 0),
BCMCLI_MAKE_PARM("vendor_id", "Vendor id", BCMCLI_PARM_HEX, BCMCLI_PARM_FLAG_OPTIONAL),
BCMCLI_MAKE_PARM("vendor_specific", "Vendor specific id", BCMCLI_PARM_HEX, BCMCLI_PARM_FLAG_OPTIONAL),
{ 0 }
};
cmd_parms[3].enum_table = filter_enum_table;
bcmcli_cmd_add(dir, "filter", polt_cli_create_filter, "Create a client/server filter",
BCMCLI_ACCESS_ADMIN, NULL, cmd_parms);
}
/* Authentication keys */
{
static bcmcli_cmd_parm cmd_parms[] = {
BCMCLI_MAKE_PARM("priv_key", "Private key file name", BCMCLI_PARM_STRING, 0),
BCMCLI_MAKE_PARM("local_cert", "Local certificate file name", BCMCLI_PARM_STRING, 0),
BCMCLI_MAKE_PARM("peer_cert", "Peer certificate file name", BCMCLI_PARM_STRING, 0),
{ 0 }
} ;
bcmcli_cmd_add(dir, "auth", polt_cli_set_auth_keys, "Set authentication keys",
BCMCLI_ACCESS_ADMIN, NULL, cmd_parms);
}
/* Display statistics */
BCMCLI_MAKE_CMD_NOPARM(dir, "stats", "Print statistics", polt_cli_stats);
#ifdef TR451_POLT_ENABLE_VENDOR_CLI
/* Initialize vendor CLI */
tr451_vendor_cli_init(dir);
#endif
}
<file_sep># libredblack - red-black tree sort
#
include(third_party)
bcm_3rdparty_module_name(libredblack "1.3")
bcm_3rdparty_download_wget("https://sourceforge.net/projects/libredblack/files/libredblack/1.3" "libredblack-${LIBREDBLACK_VERSION}.tar.gz")
bcm_3rdparty_add_build_options(--without-rbgen --without-python)
if(BCM_CONFIG_HOST MATCHES ".*aarch64.*")
set(${_MOD_NAME_UPPER}_CONFIG_HOST arm-linux)
endif()
bcm_3rdparty_build_automake()
bcm_3rdparty_export()
<file_sep># Utilities macros and functions available to the CMake users
# The following are available:
# - bcm_create_global_compile_definition - Creates a global compile option created from CMake settings
# - bcm_message - Wrapper on CMake 'message' that provides debug output
# - bcm_find_absolute_path - Find the absolute path for the given absolute or relative path
# - bcm_find_relative_path - Find the relative path for the given absolute or relative path
# - bcm_prepend_source_path - Prepend a path to a list of directories
# - bcm_get_target_property - Run the CMake 'get_target_property', but return 'unset' if not found
# - bcm_find_cmake_script - Finds a path to the requested script in any of the CMake module dirs
# - bcm_string_remove_duplicates - Convert the given string to a list and remove dups, then back to string
# - bcm_append_additional_clean_files - Append additional clean files in the directory, used for artifact clean
#====
# Macro to create a compile definition by taking the variable given, making it uppercase and appending to the
# given value. For example: BCM_OS_POSIX would be created by passing BCM_OS as the preamble and "posix" as the
# append string.
#
# @param PREAM [in] Preamble to the definition
# @param APPEND_STR [in] String to capatiliza and append to the PREAM
#====
macro(bcm_create_global_compile_definition PREAM APPEND_STR)
string(TOUPPER ${APPEND_STR} _CAP_APPEND_STR)
add_definitions(-D${PREAM}_${_CAP_APPEND_STR})
endmacro(bcm_create_global_compile_definition)
#====
# Macro for Broadcom messages. These messages will have a common preamble for easy parsing of CMake output
# to find things specific to what we've done. The parameters are the same as CMake's 'message' function.
# These messages will only come out when the V=y is used (CMAKE_VERBOSE_MAKEFILE).
#
# @param TYPE [in] Message type (e.g. INFO, STATUS) as defined by CMake 'message()'
# @param STR [in] Message string
#====
macro(bcm_message TYPE STR)
if(${CMAKE_VERBOSE_MAKEFILE} OR ("${TYPE}" STREQUAL "FATAL_ERROR"))
# If the type is not "INFO", the message call does not put a space between type and mesage.
# we take care of that here.
if(NOT "${TYPE}" STREQUAL "STATUS")
set(SPACE " ")
endif()
message(${TYPE} "${SPACE}BCM ${PLATFORM} ${SUBSYSTEM}: ${STR}")
endif()
endmacro(bcm_message)
#====
# Get the absolute path to the given directory or file. The given directory can either already be absolute
# or relative.
#
# @param ABSOLUTE_PATH [out] Resulting path
# @param DIR_OR_FILE [in] Directory or file we want to have an absolute path to
#====
macro(bcm_find_absolute_path ABSOLUTE_PATH DIR_OR_FILE)
if(IS_ABSOLUTE "${DIR_OR_FILE}")
set(${ABSOLUTE_PATH} ${DIR_OR_FILE})
else()
set(${ABSOLUTE_PATH} ${CMAKE_CURRENT_SOURCE_DIR}/${DIR_OR_FILE})
endif()
endmacro(bcm_find_absolute_path)
#====
# Get the relative path to the given directory or file. The given directory can either already be absolute
# or relative. This will return relative to CMAKE_CURRENT_SOURCE_DIR.
#
# @param RELATIVE_PATH [out] Resulting path
# @param DIR_OR_FILE [in] Directory or file we want to have an absolute path to
#====
macro(bcm_find_relative_path RELATIVE_PATH DIR_OR_FILE)
if(IS_ABSOLUTE "${DIR_OR_FILE}")
file(RELATIVE_PATH ${RELATIVE_PATH} ${CMAKE_CURRENT_SOURCE_DIR} ${DIR_OR_FILE})
else()
set(${RELATIVE_PATH} ${DIR_OR_FILE})
endif()
endmacro(bcm_find_relative_path)
#====
# Macro to prepend a directory to a list of files. Useful for things like prepending the ASIC revision to a
# list of driver source files.
#
# @param RESULT_LIST [out] List of source paths relative to the SRC_PATH.
# @param SRC_PATH [in] Preamble source path to apply to each list entry.
# @param ARGN [in] Variable List of source files
#====
macro(bcm_prepend_source_path RESULT_LIST SRC_PATH)
string(REGEX REPLACE "([^;]+)" "${SRC_PATH}/\\1" ${RESULT_LIST} "${ARGN}")
endmacro(bcm_prepend_source_path)
#======
# Macro to get a property and make it unset if not found
#
# @param OUTPUT [out] variable to fill in
# @param MOD [in] module to get property for
# @param PROPERTY [in] property to retrieve
#======
macro(bcm_get_target_property OUTPUT MOD PROPERTY)
get_target_property(_OUTPUT ${MOD} ${PROPERTY})
if("${_OUTPUT}" MATCHES ".*-NOTFOUND")
unset(${OUTPUT})
else()
set(${OUTPUT} ${_OUTPUT})
endif()
endmacro(bcm_get_target_property)
#======
# Find the path to a CMake support script. We look at all the CMAKE_MODULE_PATH entries to find it.
#
# @param SCRIPT_PATH [out] Apsolute path to the CMake support script
# @param SCRIPT_NAME [in] Script to find
#======
macro(bcm_find_cmake_script SCRIPT_PATH SCRIPT_NAME)
string(REGEX REPLACE "([^;]+)" "\\1/../scripts/${SCRIPT_NAME}" CMAKE_MODULE_SCRIPT_PATH "${CMAKE_MODULE_PATH}")
file(GLOB ${SCRIPT_PATH} LIST_DIRECTORIES FALSE ${CMAKE_MODULE_SCRIPT_PATH})
endmacro(bcm_find_cmake_script)
#======
# Convert the given string to a list and remove duplicates. After done, convert back to a string and return.
# This is used for things like compile flags where we want to append flags that are string based. By using
# this function we can avoid duplicates.
#
# @param OUTPUT_STRING [out] String to return
# @param INPUT_STRING [in] String to remove duplicates from
#======
function(bcm_string_remove_duplicates OUTPUT_STRING INPUT_STRING)
# Convert the input string to a list and remove duplicates
string(REPLACE " " ";" _INPUT_STRING_LIST "${INPUT_STRING}")
list(REMOVE_DUPLICATES _INPUT_STRING_LIST)
# Convert the list back to a string
string(REPLACE ";" " " _OUTPUT_STRING "${_INPUT_STRING_LIST}")
set(${OUTPUT_STRING} ${_OUTPUT_STRING} PARENT_SCOPE)
endfunction(bcm_string_remove_duplicates)
#======
# Add the software version for embedded or host to the CMake cache. This will also create the release info log
# used in the release package creation.
#
# @param SRC_FILE [in] Header file containing the version information.
# @param LOG_FILE [in] Where to write the log information in the artifacts.
#======
function(bcm_cache_sw_version SRC_FILE LOG_FILE)
set(_VALUES_TO_GET _MAJOR_VER _MINOR_VER _REVISION_VER)
foreach(_MY_VALUE ${_VALUES_TO_GET})
execute_process(COMMAND grep ${_MY_VALUE} ${SRC_FILE}
COMMAND awk "{print $3}"
OUTPUT_VARIABLE ${_MY_VALUE})
string(STRIP ${${_MY_VALUE}} ${_MY_VALUE})
endforeach(_MY_VALUE)
set(SW_VERSION_MAJOR ${_MAJOR_VER} CACHE STRING "SW Version Major" FORCE)
set(SW_VERSION_MINOR ${_MINOR_VER} CACHE STRING "SW Version Minor" FORCE)
set(SW_VERSION_REVISION ${_REVISION_VER} CACHE STRING "SW Version Revision" FORCE)
file(WRITE ${LOG_FILE}
"SW_VERSION_MAJOR=${SW_VERSION_MAJOR}\n"
"SW_VERSION_MINOR=${SW_VERSION_MINOR}\n"
"SW_VERSION_REVISION=${SW_VERSION_REVISION}\n")
endfunction(bcm_cache_sw_version)
#======
# Append to the current directories list of additional files to clean when 'make clean' is done. This is used
# for files that CMake is not aware of.
#
# @param ARGN [in] Additional files/directories to clean in the current binary directory.
#======
function(bcm_append_additional_clean_files)
get_directory_property(_MY_PROPS ADDITIONAL_MAKE_CLEAN_FILES)
list(APPEND _MY_PROPS ${ARGN})
set_directory_properties(PROPERTIES ADDITIONAL_MAKE_CLEAN_FILES "${_MY_PROPS}")
endfunction(bcm_append_additional_clean_files)
#======
# Convert the given flag list to a string. Used for setting CMAKE_<LANG>_FLAGS
#
# @param OUT_VAR [out] Variable to set with the string
# @param ARGN [in] List to stringify
#======
macro(bcm_stringify_flags OUT_VAR)
string(REPLACE ";" " " ${OUT_VAR} "${ARGN}")
endmacro(bcm_stringify_flags)
#======
# This function will create a target from the given output files and then apply that as a dependency to the
# master target. The individual targets are named with an increasing index. To avoid issues with parallel builds
# we make each new target dependent on the previous one. That way one codegen has to complete before the next.
#
# @param MASTER_TARGET [in] Master target relying on the given files
# @param ARGN [in] Files that we want to add as a dependency
#======
function(bcm_add_output_file_dependency MASTER_TARGET)
set(_MY_FILES ${ARGN})
# If this is the first time in the master target is not present. Use this to reset the index count
if(TARGET ${MASTER_TARGET})
set(_MY_INDEX ${_BCM_${MASTER_TARGET}_INDEX})
set(_LAST_TARGET ${MASTER_TARGET}_${_MY_INDEX})
math(EXPR _MY_INDEX ${_MY_INDEX}+1)
else()
set(_MY_INDEX 1)
set(_LAST_TARGET ${MASTER_TARGET})
add_custom_target(${MASTER_TARGET})
endif()
set(_THIS_TARGET ${MASTER_TARGET}_${_MY_INDEX})
# Add the target that contains these files. We do this because files can not be added to a target with
# 'add_dependencies'. Only targets can be added that way.
add_custom_target(${_THIS_TARGET} DEPENDS ${_MY_FILES})
add_dependencies(${_LAST_TARGET} ${_THIS_TARGET})
# Update the index and write to the cache.
set(_BCM_${MASTER_TARGET}_INDEX ${_MY_INDEX} CACHE INTERNAL "Count for ${MASTER_TARGET} dependencies" FORCE)
endfunction(bcm_add_output_file_dependency)
#======
# Macro to remove language flags for a module. This allows overrides of flags for a particular module.
#
# @param LANG [in] Language for the flags (e.g. C, CXX)
# @param ARGN [in] List of flags to remove (Can be regular expressions)
#======
macro(bcm_module_remove_flags LANG)
foreach(_FLAG ${ARGN})
string(REGEX REPLACE ${_FLAG} "" CMAKE_${LANG}_FLAGS ${CMAKE_${LANG}_FLAGS})
endforeach(_FLAG)
endmacro(bcm_module_remove_flags)
<file_sep>/*
* <:copyright-BRCM:2016-2020:Apache:standard
*
* Copyright (c) 2016-2020 Broadcom. All Rights Reserved
*
* The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* :>
*
*****************************************************************************/
#include <bcmos_system.h>
#include <bcmcli.h>
#include <bcmolt_daemon.h>
#include <bcm_dev_log.h>
#include <bcm_dev_log_cli.h>
#ifndef BCM_OPEN_SOURCE_SIM
#include <bcmolt_host_api.h>
#include <bcmtr_interface.h>
#endif
#ifndef BCM_OPEN_SOURCE
#include <bcmtr_transport_cli.h>
#include <bcmos_cli.h>
#include <bcmtr_debug_cli.h>
#include <onu_mgmt_cli.h>
#include <bcm_api_cli.h>
#include <bcmolt_olt_selector.h>
#endif
#include <bcmolt_netconf_module_init.h>
#include <libyang/libyang.h>
#include <sysrepo.h>
#ifdef NETCONF_MODULE_BBF_POLT_VOMCI
#include <bcm_tr451_polt.h>
#endif
#define BCM_NETCONF_LOG_SIZE (10*1000*1000)
dev_log_id log_id_netconf;
static dev_log_id log_id_sysrepo;
static sr_conn_ctx_t *sr_conn;
static sr_session_ctx_t *sr_sess;
static struct ly_ctx *ly_ctx; /**< libyang's context */
static bcmcli_session *current_session;
static nc_startup_options startup_opts;
static bcmos_task netconf_task;
/* We only need to allow one -config_log entry per logging level. The user
* can group all log ids together in a single entry per logging level, and
* specify several config_log entries for different logging levels,
* like:
* -config_log debug ACCESS_CONTROL,TOPOLOGY -config_log error FLOW,OLT_AGENT -config_log none SW_UTIL,CORE_CTRL
*/
#define NUM_LOG_CONFIG_SELECTIONS (DEV_LOG_LEVEL_NUM_OF)
static int print_help(const char *cmd)
{
const char *p;
while ((p = strchr(cmd, '/')))
{
cmd = p + 1;
}
fprintf(stderr,
"%s"
#ifndef BCM_OPEN_SOURCE_SIM
" -device ip:port"
#endif
#ifdef NETCONF_MODULE_BBF_POLT_VOMCI
" [-tr451_polt]"
#endif
" [-f init_script]"
" [-d]"
" [-log level]"
" [-srlog level]"
#ifdef NETCONF_MODULE_BBF_POLT_VOMCI
" [-tr451_polt_log level]"
#endif
" [-syslog]"
"\n"
,cmd);
fprintf(stderr,
#ifndef BCM_OPEN_SOURCE_SIM
"\t\t -device ip:port - IP address and port OLT is listening on\n"
#endif
"\t\t -f init_script\trun CLI script\n"
"\t\t -d - debug mode. Stay in the foreground\n"
"\t\t -syslog - Log to syslog\n"
#ifdef BCM_OPEN_SOURCE_SIM
"\t\t -dummy_tr385 - Dummy TR-385 management. Register for some TR-385 events\n"
#endif
#ifdef NETCONF_MODULE_BBF_POLT_VOMCI
#ifndef BCM_OPEN_SOURCE_SIM
"\t\t -tr451_polt - ONU management is done by TR-451 vOMCI. Enable pOLT support\n"
#endif
"\t\t -tr451_polt_log error|info|debug TR-451 pOLT log level\n"
#endif
"\t\t -log error|info|debug - netconf server log level\n"
#ifdef ENABLE_LOG
"\t\t -config_log\tlogging level with comma-delimited-list-of-log-type-name or ALL\t\tEnable specified logging level at startup for the specified modules, or ALL for all modules\n"
"\t\t One or more -config_log entries may be specified\n"
"\t\t Logging level is one of:\n"
"\t\t d (for debug), e (for error), w (for warn), f (for fatal), i (for info), n (for none)\n"
"\t\t Example 1: -config_log d NETCONF -config_log d api\n"
"\t\t Example 2: -config_log e ALL\n"
#endif
"\t\t -srlog error|info|debug - sysrepo log level\n"
);
return -EINVAL;
return -1;
}
#ifndef BCM_OPEN_SOURCE_SIM
/* parse ip:port */
static bcmos_errno _parse_ip_port(const char *s, uint32_t *ip, uint16_t *port)
{
int n;
uint32_t ip1, ip2, ip3, ip4, pp;
n = sscanf(s, "%u.%u.%u.%u:%u", &ip1, &ip2, &ip3, &ip4, &pp);
if (n != 5 || ip1 > 0xff || ip2 > 0xff || ip3 > 0xff || ip4 > 0xff || pp > 0xffff)
{
fprintf(stderr, "Can't parse %s. Must be ip_address:port\n", s);
return BCM_ERR_PARM;
}
*ip = (ip1 << 24) | (ip2 << 16) | (ip3 << 8) | ip4;
*port = pp;
return BCM_ERR_OK;
}
#endif
// Shutdown server
static void bcm_netconf_shutdown(void)
{
bcm_netconf_modules_exit(sr_sess, ly_ctx);
sr_session_stop(sr_sess);
sr_disconnect(sr_conn);
#ifndef BCM_OPEN_SOURCE_SIM
bcmtr_exit();
#endif
bcmcli_stop(current_session);
bcmcli_session_close(current_session);
bcmcli_token_destroy(NULL);
bcmos_exit();
}
/* sysrepo log callback */
static void _sr_log_cb(sr_log_level_t level, const char *msg)
{
bcm_dev_log_level log_level = DEV_LOG_LEVEL_NO_LOG;
switch(level)
{
case SR_LL_NONE:
log_level = DEV_LOG_LEVEL_NO_LOG;
break;
case SR_LL_ERR: /**< Print only error messages. */
log_level = DEV_LOG_LEVEL_ERROR;
break;
case SR_LL_WRN: /**< Print error and warning messages. */
log_level = DEV_LOG_LEVEL_WARNING;
break;
case SR_LL_INF: /**< Besides errors and warnings, print some other informational messages. */
log_level = DEV_LOG_LEVEL_INFO;
break;
case SR_LL_DBG: /**< Print all messages including some development debug messages. */
log_level = DEV_LOG_LEVEL_DEBUG;
break;
default:
break;
}
/* Log */
#define MAX_LOG_STRING_LEN (MAX_DEV_LOG_STRING_SIZE - 64)
if (log_id_sysrepo)
{
uint32_t len = strlen(msg);
const char *p = msg;
uint32_t flags = BCM_LOG_FLAG_NONE;
while (len > MAX_LOG_STRING_LEN)
{
char buf[MAX_LOG_STRING_LEN];
memcpy(buf, p, MAX_LOG_STRING_LEN - 1);
buf[MAX_LOG_STRING_LEN - 1] = 0;
bcm_dev_log_log(log_id_sysrepo, log_level, flags, "%s", buf);
p += MAX_LOG_STRING_LEN - 1;
len -= MAX_LOG_STRING_LEN - 1;
flags = BCM_LOG_FLAG_NO_HEADER;
}
bcm_dev_log_log(log_id_sysrepo, log_level, flags, "%s\n", p);
}
}
/* Run CLI script */
static bcmos_errno _run_cli_script(bcmcli_session *session, const char *fname, bcmos_bool stop_on_error)
{
bcmos_file *script_file;
char line_buf[4096];
int line = 0;
bcmos_errno err = BCM_ERR_OK;
script_file = bcmos_file_open(fname, BCMOS_FILE_FLAG_READ);
if (script_file == NULL)
{
bcmcli_print(session, "Can't open file %s for reading\n", fname);
return BCM_ERR_NOENT;
}
while (bcmos_file_gets(script_file, line_buf, sizeof(line_buf)) != NULL)
{
++line;
/* Echo */
bcmcli_print(session, "%d: %s\n", line, line_buf);
if (line_buf[0] == '#')
continue;
/* Execute */
err = bcmcli_parse(session, line_buf);
if (err != BCM_ERR_OK && stop_on_error)
break;
}
bcmos_file_close(script_file);
return err;
}
/* Run script command handler
BCMCLI_MAKE_PARM("name", "Script file name", BCMCLI_PARM_STRING, 0),
BCMCLI_MAKE_PARM_ENUM_DEFVAL("stop_on_error", "Stop on error", bcmcli_enum_bool_table, 0, "no"));
*/
static int _cmd_run_script(bcmcli_session *sess, const bcmcli_cmd_parm parm[], uint16_t nParms)
{
const char *filename = (const char *)parm[0].value.string;
bcmos_bool stop_on_error = (bcmos_bool)parm[1].value.number;
return _run_cli_script(sess, filename, stop_on_error);
}
static bcmos_errno _cli_quit(bcmcli_session *session, const bcmcli_cmd_parm parm[], uint16_t n_parms)
{
bcmcli_print(session, "NETCONF server terminated by CLI command\n");
bcmcli_stop(session);
return BCM_ERR_OK;
}
int main(int argc, char *argv[])
{
#ifndef BCM_OPEN_SOURCE_SIM
bcmolt_host_init_parms init_parms = {
.transport.type = BCM_HOST_API_CONN_LOCAL
};
dev_log_init_parms *p_log_parms = &init_parms.log;
#else
dev_log_init_parms log_parms = {};
dev_log_init_parms *p_log_parms = &log_parms;
#endif
bcm_dev_log_level log_level = DEV_LOG_LEVEL_INFO;
bcm_dev_log_level sr_log_level = DEV_LOG_LEVEL_INFO;
#ifdef NETCONF_MODULE_BBF_POLT_VOMCI
tr451_polt_init_parms tr451_init_parms = { .log_level = DEV_LOG_LEVEL_INFO };
#endif
#ifdef ENABLE_LOG
char *config_log_names[NUM_LOG_CONFIG_SELECTIONS] = { };
int config_log_cntr = 0;
bcm_dev_log_level dev_log_level[NUM_LOG_CONFIG_SELECTIONS] = { DEV_LOG_LEVEL_NO_LOG };
#endif
bcmos_bool do_not_daemonize = BCMOS_FALSE;
bcmolt_daemon_parms daemon_parms = {
.name = "netconf"
};
bcmos_bool log_syslog = BCMOS_FALSE;
bcmos_task_parm tp = {
.name = "netconf",
.priority = TASK_PRIORITY_OLT_AGENT
};
bcmos_module_parm mp = {
.qparm.name = "netconf"
};
const char *init_script_name = NULL;
bcmos_errno rc;
int i;
int sr_rc;
// Parameter validation
for (i = 1; i < argc; i++)
{
if (!strcmp(argv[i], "-log"))
{
++i;
if (i >= argc)
return print_help(argv[0]);
if (!strcmp(argv[i], "debug"))
log_level = DEV_LOG_LEVEL_DEBUG;
else if (!strcmp(argv[i], "info"))
log_level = DEV_LOG_LEVEL_INFO;
else if (!strcmp(argv[i], "error"))
log_level = DEV_LOG_LEVEL_ERROR;
else
return print_help(argv[0]);
}
#ifndef BCM_OPEN_SOURCE_SIM
else if (!strcmp(argv[i], "-device"))
{
uint32_t remote_ip = 0;
uint16_t remote_port = 0;
++i;
if (i >= argc)
return print_help(argv[0]);
init_parms.transport.type = BCM_HOST_API_CONN_REMOTE;
if (_parse_ip_port(argv[i], &remote_ip, &remote_port) != BCM_ERR_OK)
return -1;
init_parms.transport.addr.ip.u32 = remote_ip;
init_parms.transport.addr.port = remote_port;
}
#endif
else if (!strcmp(argv[i], "-srlog"))
{
++i;
if (i >= argc)
return print_help(argv[0]);
if (!strcmp(argv[i], "debug"))
sr_log_level = DEV_LOG_LEVEL_DEBUG;
else if (!strcmp(argv[i], "info"))
sr_log_level = DEV_LOG_LEVEL_INFO;
else if (!strcmp(argv[i], "error"))
sr_log_level = DEV_LOG_LEVEL_ERROR;
else
return print_help(argv[0]);
}
else if (!strcmp(argv[i], "-d"))
{
do_not_daemonize = BCMOS_TRUE;
}
else if (!strcmp(argv[i], "-syslog"))
{
log_syslog = BCMOS_TRUE;
}
#ifdef BCM_OPEN_SOURCE_SIM
else if (!strcmp(argv[i], "-dummy_tr385"))
{
startup_opts.dummy_tr385_management = BCMOS_TRUE;
}
#endif
#ifdef NETCONF_MODULE_BBF_POLT_VOMCI
#ifndef BCM_OPEN_SOURCE_SIM
else if (!strcmp(argv[i], "-tr451_polt"))
{
startup_opts.tr451_onu_management = BCMOS_TRUE;
}
#endif
else if (!strcmp(argv[i], "-tr451_polt_log"))
{
++i;
if (i >= argc)
return print_help(argv[0]);
if (!strcmp(argv[i], "debug"))
tr451_init_parms.log_level = DEV_LOG_LEVEL_DEBUG;
else if (!strcmp(argv[i], "info"))
tr451_init_parms.log_level = DEV_LOG_LEVEL_INFO;
else if (!strcmp(argv[i], "error"))
tr451_init_parms.log_level = DEV_LOG_LEVEL_ERROR;
else
return print_help(argv[0]);
}
#endif
#ifdef ENABLE_LOG
else if (!strcmp(argv[i], "-config_log"))
{
const char *user_logging_level;
++i;
if (i >= argc)
return print_help(argv[0]);
/* pick up the logging level */
user_logging_level = argv[i];
switch(user_logging_level[0])
{
case 'd': /* debug */
case 'D':
dev_log_level[config_log_cntr] = DEV_LOG_LEVEL_DEBUG;
break;
case 'i': /* info */
case 'I':
dev_log_level[config_log_cntr] = DEV_LOG_LEVEL_INFO;
break;
case 'e': /* error */
case 'E':
dev_log_level[config_log_cntr] = DEV_LOG_LEVEL_ERROR;
break;
case 'w': /* warning */
case 'W':
dev_log_level[config_log_cntr] = DEV_LOG_LEVEL_WARNING;
break;
case 'f': /* fatal */
case 'F':
dev_log_level[config_log_cntr] = DEV_LOG_LEVEL_FATAL;
break;
case 'n': /* none */
case 'N':
dev_log_level[config_log_cntr] = DEV_LOG_LEVEL_NO_LOG;
break;
default:
return print_help(argv[0]);
}
++i;
config_log_names[config_log_cntr] = argv[i];
if(++config_log_cntr == NUM_LOG_CONFIG_SELECTIONS)
{
fprintf(stderr, "Too many config_log choices have been made, only %d allowed\n\n",
NUM_LOG_CONFIG_SELECTIONS);
return print_help(argv[0]);
}
}
#endif
else if (!strcmp(argv[i], "-f"))
{
++i;
if (i >= argc)
return print_help(argv[0]);
init_script_name = argv[i];
}
else
{
return print_help(argv[0]);
}
}
#if defined(NETCONF_MODULE_BBF_POLT_VOMCI) && defined(BCM_OPEN_SOURCE_SIM)
startup_opts.tr451_onu_management = BCMOS_TRUE;
#endif
#if !defined(BCM_OPEN_SOURCE_SIM) && defined(SIMULATION_BUILD)
if (!init_parms.transport.addr.port)
{
fprintf(stderr, "-device parameter is mandatory\n");
return print_help(argv[0]);
}
#endif
/* Daemonize if necessary */
if (!do_not_daemonize)
{
daemon_parms.is_cli_support = BCMOS_TRUE;
daemon_parms.terminate_cb = bcm_netconf_shutdown;
//daemon_parms.restart_cb = bcm_netconf_restart;
rc = bcmolt_daemon_start(&daemon_parms);
BUG_ON(rc);
log_syslog = BCMOS_TRUE;
}
else
{
if (bcmolt_daemon_check_lock(&daemon_parms))
exit(-1);
}
if (!log_syslog)
{
p_log_parms->type = BCM_DEV_LOG_FILE_MEMORY;
p_log_parms->mem_size = BCM_NETCONF_LOG_SIZE;
}
else
{
p_log_parms->type = BCM_DEV_LOG_FILE_SYSLOG;
}
#ifndef BCM_OPEN_SOURCE_SIM
/* Initialize host application */
rc = bcmolt_host_init(&init_parms);
BUG_ON(rc != BCM_ERR_OK);
#else
bcmos_trace_level_set(BCMOS_TRACE_LEVEL_INFO);
#ifdef ENABLE_LOG
/* Initialize logger */
rc = bcm_log_init(p_log_parms);
BCMOS_TRACE_CHECK_RETURN(rc, rc, "bcmolt_log_init()\n");
#endif
#endif /* #ifndef BCM_OPEN_SOURCE_SIM */
#ifdef ENABLE_LOG
log_id_netconf = bcm_dev_log_id_register("NETCONF", log_level, DEV_LOG_ID_TYPE_BOTH);
bcm_dev_log_id_set_level(log_id_netconf, log_level, log_level);
log_id_sysrepo = bcm_dev_log_id_register("SYSREPO", log_level, DEV_LOG_ID_TYPE_BOTH);
bcm_dev_log_id_set_level(log_id_sysrepo, sr_log_level, sr_log_level);
/* Set log levels as per command line */
for (i=0; i<config_log_cntr; i++)
{
char *log_name = strtok(config_log_names[i], ",");
dev_log_id log_id;
while (log_name != NULL)
{
fprintf(stdout, "Enable logging for %s with dev_log set to %d\n", log_name, dev_log_level[i]);
if (!strcmp(log_name, "ALL"))
{
dev_log_id_parm id_parm = {};
fprintf(stdout, "All logs enabled at all levels\n");
log_id = DEV_LOG_INVALID_ID;
while ((log_id = bcm_dev_log_id_get_next(log_id)) != DEV_LOG_INVALID_ID)
{
bcm_dev_log_id_get(log_id, &id_parm);
/* Set the default level of all modules to the selected level. However, if the
* selected level is DEBUG, don't set the serializer module to the debug logging level,
* since it would be too chatty once the host is connected to the device(s)
*/
if((strcmp(id_parm.name, "serializer")) && (DEV_LOG_LEVEL_DEBUG == dev_log_level[i]))
{
bcm_dev_log_id_set_level(log_id, dev_log_level[i], dev_log_level[i]);
}
}
break;
}
else
{
log_id = bcm_dev_log_id_get_by_name(log_name);
if (log_id != DEV_LOG_INVALID_ID)
{
bcm_dev_log_id_set_level(log_id, dev_log_level[i], dev_log_level[i]);
}
else
{
fprintf(stderr, "Log name %s is unknown. Skipped\n", log_name);
}
log_name = strtok(NULL, ",");
}
}
}
#endif
sr_log_set_cb(_sr_log_cb);
/* Initialize CLI */
bcmcli_session_parm mon_session_parm = {};
/* Create CLI session */
memset(&mon_session_parm, 0, sizeof(mon_session_parm));
mon_session_parm.access_right = BCMCLI_ACCESS_ADMIN;
rc = bcmcli_session_open(&mon_session_parm, ¤t_session);
BUG_ON(rc != BCM_ERR_OK);
#ifndef BCM_OPEN_SOURCE
bcmolt_olt_sel_init(NULL);
/* API CLI */
bcm_api_cli_init(NULL, current_session);
/* ONU management */
bcmonu_mgmt_cli_init(NULL, current_session);
/* Transport CLI */
bcmtr_cli_init();
/* CLD directory */
bcmtr_cld_cli_init();
/* os CLI directory */
bcmos_cli_init(NULL);
#endif
#ifdef ENABLE_LOG
/* logger CLI directory */
bcm_dev_log_cli_init(NULL);
#endif
/* Create task and module for handling NETCONF events */
rc = bcmos_task_create(&netconf_task, &tp);
BUG_ON(rc != BCM_ERR_OK);
rc = bcmos_module_create(BCMOS_MODULE_ID_NETCONF_SERVER, &netconf_task, &mp);
BUG_ON(rc != BCM_ERR_OK);
#ifdef NETCONF_MODULE_BBF_POLT_VOMCI
/* Start TR-451 pOLT subsystem */
if (startup_opts.tr451_onu_management)
{
rc = bcm_tr451_polt_init(&tr451_init_parms);
BUG_ON(rc != BCM_ERR_OK);
}
#endif
#ifdef ENABLE_LOG
/* Set log levels as per configuration in the command line */
for (i=0; i<config_log_cntr; i++)
{
char *log_name = strtok(config_log_names[i], ",");
dev_log_id log_id;
while (log_name != NULL)
{
fprintf(stdout, "Enable logging for %s with dev_log set to %d\n", log_name, dev_log_level[i]);
if (!strcmp(log_name, "ALL"))
{
dev_log_id_parm id_parm = {};
fprintf(stdout, "All logs enabled at all levels\n");
log_id = DEV_LOG_INVALID_ID;
while ((log_id = bcm_dev_log_id_get_next(log_id)) != DEV_LOG_INVALID_ID)
{
bcm_dev_log_id_get(log_id, &id_parm);
/* Set the default level of all modules to the selected level. However, if the
* selected level is DEBUG, don't set the serializer module to the debug logging level,
* since it would be too chatty once the host is connected to the device(s)
*/
if((strcmp(id_parm.name, "serializer")) && (DEV_LOG_LEVEL_DEBUG == dev_log_level[i]))
{
bcm_dev_log_id_set_level(log_id, dev_log_level[i], dev_log_level[i]);
}
}
break;
}
else
{
log_id = bcm_dev_log_id_get_by_name(log_name);
if (log_id != DEV_LOG_INVALID_ID)
{
bcm_dev_log_id_set_level(log_id, dev_log_level[i], dev_log_level[i]);
}
else
{
fprintf(stderr, "Log name %s is unknown. Skipped\n", log_name);
}
log_name = strtok(NULL, ",");
}
}
}
#endif
/* Connect with sysrepo */
sr_rc = sr_connect(SR_CONN_DEFAULT, &sr_conn);
if (sr_rc != SR_ERR_OK)
{
bcmos_printf("Can't connect with sysrepo. Error %s\n", sr_strerror(sr_rc));
return -1;
}
sr_rc = sr_session_start(sr_conn, SR_DS_RUNNING, &sr_sess);
if (sr_rc != SR_ERR_OK)
{
bcmos_printf("Unable to create Netopeer session with sysrepod (%s).", sr_strerror(sr_rc));
return -1;
}
/* build libyang context */
ly_ctx = ly_ctx_new(SR_MODELS_SEARCH_DIR, LY_CTX_ALLIMPLEMENTED);
if (!ly_ctx)
{
bcmos_printf("Unable to create libyang context.");
return -1;
}
/* Start plugin */
rc = bcm_netconf_modules_init(sr_sess, ly_ctx, &startup_opts);
if (rc != BCM_ERR_OK)
{
/* Let logs a chance to print */
bcmos_usleep(500000);
bcmos_printf("NETCONF modules init failed. Error %s\n", bcmos_strerror(rc));
return -1;
}
/* Mark daemon as running */
if (!do_not_daemonize)
bcmolt_daemon_init_completed();
/* Add Execute Script command */
BCMCLI_MAKE_CMD(NULL, "run", "Run CLI script", _cmd_run_script,
BCMCLI_MAKE_PARM("name", "Script file name", BCMCLI_PARM_STRING, 0),
BCMCLI_MAKE_PARM_ENUM_DEFVAL("stop_on_error", "Stop on error", bcmcli_enum_bool_table, 0, "no"));
BCMCLI_MAKE_CMD_NOPARM(NULL, "quit", "quit", _cli_quit);
/* Run init script if any */
if (init_script_name)
{
rc = _run_cli_script(current_session, init_script_name, BCMOS_FALSE);
if (rc != BCM_ERR_OK)
return rc;
}
/* Handle CLI input */
while (!bcmcli_is_stopped(current_session))
{
/* Process user input until EOF or quit command */
bcmcli_driver(current_session);
if (feof(stdin) && !do_not_daemonize)
{
bcmos_usleep(100000);
clearerr(stdin);
}
}
/* Cleanup */
bcm_netconf_shutdown();
return 0;
}
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
/* bcmos_rw_lock_coverity.c: Dramatically simplified model of a reader/writer lock so Coverity can understand it.
*
* We could use code-level annotations in bcmos_rw_lock.c to prevent the Coverity errors, but then Coverity would
* lose the fact that these functions do take/release locks, just like a regular mutex.
*/
#include "bcmos_rw_lock.h"
struct bcmos_rw_lock
{
bcmos_mutex lock;
};
bcmos_errno bcmos_rw_lock_create(bcmos_rw_lock **lock)
{
bcmos_errno err;
*lock = (bcmos_rw_lock*)bcmos_calloc(sizeof(bcmos_rw_lock));
BUG_ON(*lock == NULL);
err = bcmos_mutex_create(&(*lock)->lock, 0, "bcmos_rw_lock_create_lock");
BUG_ON(err != BCM_ERR_OK);
return BCM_ERR_OK;
}
void bcmos_rw_write_lock(bcmos_rw_lock* lock)
{
bcmos_mutex_lock(&lock->lock);
}
void bcmos_rw_write_release(bcmos_rw_lock* lock)
{
bcmos_mutex_unlock(&lock->lock);
}
void bcmos_rw_read_lock(bcmos_rw_lock* lock)
{
bcmos_mutex_lock(&lock->lock);
}
void bcmos_rw_read_release(bcmos_rw_lock* lock)
{
bcmos_mutex_unlock(&lock->lock);
}
<file_sep>/*
<:copyright-BRCM:2016-2019:Apache:standard
Copyright (c) 2016-2019 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
* :>
*/
#ifndef __BCM_DEV_LOG_H_
#define __BCM_DEV_LOG_H_
#include <bcmos_system.h>
#ifdef ENABLE_LOG
#include "bcm_dev_log_task.h"
#include <math.h>
/********************************************/
/* */
/* Log macros */
/* */
/********************************************/
#define MACRO_ARG_N(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, N, ...) N
#define MACROS_ARGS_SEQUENCE 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
#define MACRO_NUM_ARGS_HELPER(...) MACRO_ARG_N(__VA_ARGS__)
#define MACRO_NUM_ARGS(...) MACRO_NUM_ARGS_HELPER(__VA_ARGS__, MACROS_ARGS_SEQUENCE)
/* IMPORTANT! DO NOT USE THESE MACROS, USE BCM_LOG ONLY ! */
/* These macros force number of arguments in compile time. A single macro for each number of arguments (including the format) */
#ifdef __BASENAME__
#define _BCM_LOG_ARGS1(level, id, flags, ...) \
bcm_dev_log_log(id, level, flags, STRINGIFY_EXPAND(__BASENAME__) " " STRINGIFY_EXPAND(__LINE__) "| " __VA_ARGS__)
#else
#define _BCM_LOG_ARGS1(level, id, flags, ...) \
bcm_dev_log_log(id, level, flags | BCM_LOG_FLAG_FILENAME_IN_FMT, __FILE__ " " STRINGIFY_EXPAND(__LINE__) "| " __VA_ARGS__)
#endif
#define _BCM_LOG_ARGS2(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS3(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS4(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS5(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS6(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS7(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS8(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS9(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS10(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS11(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS12(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS13(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS14(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS15(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS16(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS17(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS18(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS19(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS20(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS21(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS22(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS23(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS24(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS25(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS26(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS27(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS28(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS29(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS30(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS31(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS32(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS33(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS34(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS35(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS36(...) _BCM_LOG_ARGS1(__VA_ARGS__)
#define _BCM_LOG_ARGS(n) _BCM_LOG_ARGS##n
#define _BCM_LOG_EXPAND(n, ...) _BCM_LOG_ARGS(n) (__VA_ARGS__)
/*
* IMPORTANT! you should use only this macro for logging
*
* 1. Support prints up to DEV_LOG_MAX_ARGS parameters each with maximum size of 32bits
* 2. Support also prints of arguments with size 64bits but each one counted as two arguments of 32bits,
* so you can only print up to (DEV_LOG_MAX_ARGS/2) arguments of 64bits.
* Mix of 64 and 32 are allowed as long you don't exceed DEV_LOG_MAX_ARGS.
* 3. Any possible combination of mix 32 and 64 arguments are allowed.
*/
#define BCM_LOG(level, id, ...) _BCM_LOG_EXPAND(MACRO_NUM_ARGS(__VA_ARGS__), DEV_LOG_LEVEL_##level, id, 0, __VA_ARGS__)
/* Same as BCM_LOG(), but overrides BCM_LOG() default behavior by letting the format be done in the context of the caller task. This allows using stack/heap strings
* for fmt and args. See comment for BCM_LOG_FLAG_CALLER_FMT. */
#define BCM_LOG_CALLER_FMT(level, id, ...) _BCM_LOG_EXPAND(MACRO_NUM_ARGS(__VA_ARGS__), DEV_LOG_LEVEL_##level, id, BCM_LOG_FLAG_CALLER_FMT, __VA_ARGS__)
/* Same as BCM_LOG(), but the level is not given as a token for concatenation, but as a regular enum. */
#define BCM_LOG_LEVEL(level, id, ...) _BCM_LOG_EXPAND(MACRO_NUM_ARGS(__VA_ARGS__), level, id, 0, __VA_ARGS__)
#define BCM_LOG_FLAG_NONE 0
#define BCM_LOG_FLAG_NO_HEADER (1 << 0) /* Avoid inserting header to each message. */
#define BCM_LOG_FLAG_CALLER_FMT (1 << 1) /* The log message will be formatted in the context of the caller task, not the logger task (override default behavior).
* This has a penalty - bcm_dev_log_log() becomes slower. */
#define BCM_LOG_FLAG_FILENAME_IN_FMT (1 << 2) /* Indicates that __FILE__ is inserted at the beginning of the message format. */
#define BCM_LOG_FLAG_DONT_SKIP_PRINT (1 << 3) /* The message should always be printed even if the msg pool is nearly full. */
/********************************************/
/* */
/* Callbacks functions */
/* */
/********************************************/
/********************************************/
/* */
/* Functions prototypes */
/* */
/********************************************/
const char *dev_log_basename(const char *str);
/****************************************************************************************/
/* */
/* Name: bcm_dev_log_log */
/* Abstract: Log function */
/* It is better using the macros and not the function directly. */
/* */
/* Arguments: */
/* - id - The Log ID this message is connected to. */
/* (The ID we got form bcm_dev_log_id_register) */
/* - log_level - The Log level of this message */
/* - flags - Can be one of BCM_LOG_FLAG_XXX above. */
/* - fmt - The print format */
/* Note: The default behavior is to format the string in the logger */
/* task context, not the caller task context, to reduce the */
/* penalty of calling bcm_dev_log_log(). This means 'fmt' can */
/* point only to strings in data segment, but not to head/stack. */
/* You can override this behavior with BCM_LOG_FLAG_CALLER_FMT. */
/* */
/* - param1 - Format parameter No. 1. Like 'fmt', can reside only in data */
/* segment, unless choosing BCM_LOG_FLAG_CALLER_FMT */
/* - ... */
/* - paramN - Format parameter No. N */
/* */
/* IMPORTANT! */
/* 1. bcm_dev_log_log() must have even number of arguments before the '...'. */
/* This comes from the 64bits limitation that must be align to 8bytes in some */
/* platforms who doesn't support unaligned access, */
/* on xponsw (x86) it doesn't matter but on device (arm) you must have that. */
/* */
/****************************************************************************************/
void bcm_dev_log_log(dev_log_id id,
bcm_dev_log_level log_level,
uint32_t flags,
const char *fmt,
...) __attribute__((format(__printf__, 4, 5))); /* compiler attribute to check as printf style for arguments 4 (fmt) and 5 (all other) */
void bcm_dev_log_vlog(dev_log_id id,
bcm_dev_log_level log_level,
uint32_t flags,
const char *fmt,
va_list args);
#if defined(BCM_SUBSYSTEM_HOST)
/* The following functions might be used on the host side to make sure
that multiple log entries are "together",ie are not interleaved
with other log entries. It might be necessary if application needs to log
a very long string that must be split into multiple log entries.
*/
void bcm_dev_log_lock(void);
void bcm_dev_log_unlock(void);
#endif /* #if defined(BCM_SUBSYSTEM_HOST) */
typedef enum
{
DEV_LOG_RATE_LIMIT_ID_NONE,
DEV_LOG_RATE_LIMIT_ID_BWS_DBA_BD_ADD_ALLOC_FAILED,
DEV_LOG_RATE_LIMIT_ID_BWS_DBA_BD_ADD_GUARANTEED_ALLOC_FAILED,
DEV_LOG_RATE_LIMIT_ID_BWS_CBR_RT_ADD_ALLOC_FAILED,
DEV_LOG_RATE_LIMIT_ID_BWS_CBR_RT_ADD_ACCESS_FAILED,
DEV_LOG_RATE_LIMIT_ID_BWS_QW_CBR_RT_ADD_ACCESS_FAILED,
DEV_LOG_RATE_LIMIT_ID_BWS_CBR_NRT_ADD_ALLOC_FAILED,
DEV_LOG_RATE_LIMIT_ID_BWS_CBR_COMPENSATION_ADD_ACCESS_FAILED,
DEV_LOG_RATE_LIMIT_ID_BWS_CBR_NO_COMPENSATION_ADD_ACCESS_FAILED,
DEV_LOG_RATE_LIMIT_ID_BWS_CBR_COPY_COMPENSATION_ADD_ACCESS_FAILED,
DEV_LOG_RATE_LIMIT_ID_BWS_CBR_RT_SAVE_ACCESS_FOR_COMPENSATION_FAILED,
DEV_LOG_RATE_LIMIT_ID_BWS_CBR_NRT_SAVE_ACCESS_FOR_COMPENSATION_FAILED,
DEV_LOG_RATE_LIMIT_ID_BWS_CBR_FLUSH_FAILED,
DEV_LOG_RATE_LIMIT_ID_BWS_DBA_BA_INCORRECT_SHARING,
DEV_LOG_RATE_LIMIT_ID_BWS_DBA_BA_INSUFFICIENT_REMAINING_BW,
DEV_LOG_RATE_LIMIT_ID__NUM_OF,
} dev_log_rate_limit_id;
void bcm_dev_log_log_ratelimit(dev_log_id id,
bcm_dev_log_level log_level,
uint32_t flags,
uint32_t rate_us,
dev_log_rate_limit_id rate_limit_id,
const char *fmt,
...) __attribute__((format(__printf__, 6, 7))); /* compiler attribute to check as printf style for arguments 6 (fmt) and 7 (all other) */
/********************************************************************************************/
/* */
/* Name: bcm_dev_log_os_trace_init */
/* */
/* Abstract: Direct bcmos_trace() output to log */
/* Arguments: NONE */
/* */
/* Return Value: */
/* bcmos_errno - Success code (BCM_ERR_OK) or Error code (see bcmos_errno.h) */
/* */
/********************************************************************************************/
bcmos_errno bcm_dev_log_os_trace_init(void);
#define DEV_LOG_CHRDEV_MAX_KERNEL_IDS 32
/* ID descriptor */
typedef struct dev_log_id_info
{
uint32_t index;
char name[MAX_DEV_LOG_ID_NAME + 1];
bcm_dev_log_level default_level;
bcm_dev_log_id_type default_type;
} dev_log_id_info;
/* ioctl parameters */
typedef union dev_log_io_param
{
struct
{
int num_ids;
dev_log_id_info ids[DEV_LOG_CHRDEV_MAX_KERNEL_IDS];
} db_read;
struct
{
uint32_t index;
bcm_dev_log_level level_print;
bcm_dev_log_level level_save;
} level_set;
struct
{
uint32_t index;
bcm_dev_log_id_type type;
} type_set;
struct
{
uint32_t offset;
char msg[MAX_DEV_LOG_STRING_SIZE + 1];
} msg_read;
} dev_log_io_param;
#define BCM_DEV_LOG_MAX_DOUBLE_STR 32 /* Should be big enough to accommodate the biggest string representation of double (64 bit), including the decimal point. */
typedef struct
{
ulong_t int_val;
const char *leading_zeros;
ulong_t fraction;
} double2two_int_t;
/* Convert a double type to an integer part and a fractional part (given as an output struture).
* Input - double value,
* precision - number of digits after the decimal point
* Output: Result structure */
void dev_log_double2two_int_conv(double double_val, uint8_t precision, double2two_int_t *result);
/* Convert a double type to a string.
* Input - double value,
* precision - number of digits after the decimal point
* Output: Result string */
char *dev_log_double2str_conv(double double_val, uint8_t precision, char *result);
#else /* #ifndef ENABLE_LOG */
typedef unsigned long dev_log_id;
#define DEV_LOG_INVALID_ID (dev_log_id)UINT_MAX
#define BCM_LOG(level, id, ...) \
do \
{ \
} \
while (0)
#define BCM_LOG_CALLER_FMT(level, id, ...) \
do \
{ \
} \
while (0)
#endif /* ENABLE_LOG */
#endif /* __BCM_DEV_LOG_H_ */
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#include <bcm_tr451_polt_internal.h>
#include <fstream>
//#include <grpc/grpc_security_constants.h>
// BcmPoltServer constructor
BcmPoltServer::BcmPoltServer(const tr451_server_endpoint *ep):
GrpcProcessor(GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_SERVER, ep->endpoint.name),
hello_service_(this), message_service_(this), endpoint_(&ep->endpoint, ep->local_name)
{
p_server_ = nullptr;
}
// Destructor
BcmPoltServer::~BcmPoltServer()
{
Stop();
}
// Start gRPC server
// This function is called in context of dedicated task
bcmos_errno BcmPoltServer::Start()
{
std::string server_address =
string(endpoint_.host_name() ? endpoint_.host_name() : "0.0.0.0") + string(":") +
std::to_string(endpoint_.port());
// See if authentication is required
string my_key, my_cert, peer_cert;
bool use_auth = false;
grpc::SslServerCredentialsOptions sslOpts;
if (bcm_tr451_auth_data(my_key, my_cert, peer_cert))
{
sslOpts.pem_root_certs = peer_cert;
sslOpts.pem_key_cert_pairs.push_back(
grpc::SslServerCredentialsOptions::PemKeyCertPair{my_key, my_cert});
sslOpts.client_certificate_request = GRPC_SSL_REQUEST_CLIENT_CERTIFICATE_AND_VERIFY;
use_auth = true;
BCM_POLT_LOG(INFO, "%s: Enabling ssl authentication\n", this->name());
}
ServerBuilder builder;
auto creds = grpc::SslServerCredentials(sslOpts);
builder.AddListeningPort(server_address,
use_auth ? grpc::SslServerCredentials(sslOpts) : grpc::InsecureServerCredentials());
builder.RegisterService(&this->hello_service_);
builder.RegisterService(&this->message_service_);
std::unique_ptr<Server> server(builder.BuildAndStart());
if (server == nullptr)
{
BCM_POLT_LOG(ERROR, "Failed to create %s on %s\n", this->name(), server_address.c_str());
return BCM_ERR_PARM;
}
BCM_POLT_LOG(INFO, "Server %s is listening on %s\n", this->name(), server_address.c_str());
p_server_ = &server;
server->Wait();
return BCM_ERR_OK;
}
// Stop server
void BcmPoltServer::Stop()
{
if (!stopping)
{
stopping = true;
VomciConnection *prev = nullptr, *next;
if (p_server_ != nullptr)
{
(*p_server_)->Shutdown();
p_server_ = nullptr;
}
// Pick up the remaining connections if any
next = vomci_connection_get_next(prev, this);
while (next != nullptr)
{
prev = next;
next = vomci_connection_get_next(prev, this);
if (prev != nullptr)
delete prev;
}
GrpcProcessor::Stop();
BCM_POLT_LOG(INFO, "server %s: Stopped\n", name());
}
}
// OmciFunctionHello service handler
Status BcmPoltServer::OmciServiceHello::HelloVomci(
ServerContext* context,
const HelloVomciRequest* request,
HelloVomciResponse* response)
{
const char *vomci_name = request->has_local_endpoint_hello() ?
request->local_endpoint_hello().endpoint_name().c_str() : nullptr;
const char *local_name = parent_->endpoint()->name_for_hello();
if (context->auth_context()->IsPeerAuthenticated() && vomci_name == nullptr)
{
std::vector<grpc::string_ref> auth_identity =
context->auth_context()->FindPropertyValues(context->auth_context()->GetPeerIdentityPropertyName());
if (auth_identity.size())
vomci_name = auth_identity[0].data();
}
BCM_POLT_LOG(INFO, "Server %s: received HelloRequest from vOMCI %s\n",
parent_->name(),
(vomci_name != nullptr) ? vomci_name : "*undefined*");
if (vomci_name == nullptr || !strlen(vomci_name))
{
return tr451_bcm_errno_grpc_status(BCM_ERR_PARM,
"Can't identify connection. vomci_name is missing in HelloVomci and in Auth identity");
}
Hello *olt = new Hello();
olt->set_endpoint_name(local_name);
response->set_allocated_remote_endpoint_hello(olt);
new VomciConnection(parent_, parent_->endpoint()->name(), local_name, vomci_name, context->peer());
return Status::OK;
}
// OmciFunctionMessage::ListenForOmciRx service handler
Status BcmPoltServer::OmciServiceMessage::ListenForVomciRx(
ServerContext* context,
const Empty* request,
ServerWriter<VomciMessage>* writer)
{
bcmos_errno err;
VomciConnection *conn = parent_->connection_by_peer(context->peer());
if (conn == nullptr)
{
return tr451_bcm_errno_grpc_status(BCM_ERR_PARM,
"%s: vOMCI instance %s is unknown\n", parent_->name(), context->peer().c_str());
}
BCM_POLT_LOG(INFO, "%s: Forwarding OMCI messages from pOLT to vOMCI %s@%s enabled\n",
parent_->name(), conn->name(), conn->peer());
conn->setConnected(true);
while (!context->IsCancelled() && !parent_->stopping)
{
err = conn->WaitForPacketFromOnu();
if (err != BCM_ERR_OK && err != BCM_ERR_TIMEOUT)
break;
OmciPacketEntry *omci_packet = conn->PopPacketFromOnuFromTxQueue();
if (omci_packet == nullptr)
continue;
// Send to vOMCI peer
VomciMessage tx_msg;
tx_msg.set_allocated_omci_packet_msg(omci_packet);
writer->Write(tx_msg);
++conn->stats.packets_onu_to_vomci_sent;
}
conn->setConnected(false);
BCM_POLT_LOG(INFO, "%s: Forwarding OMCI messages from pOLT to vOMCI %s disabled\n",
parent_->name(), conn->name());
delete conn;
return Status::OK;
}
Status BcmPoltServer::OmciServiceMessage::VomciTx(
ServerContext* context,
const VomciMessage* request,
Empty* response)
{
if (!request->has_omci_packet_msg())
{
BCM_POLT_LOG(ERROR, "message is not a packet. Ignored\n");
return grpc::Status(StatusCode::INVALID_ARGUMENT, "message is not a packet");
}
return parent()->OmciTxToOnu(request->omci_packet_msg());
}
//
// External interface
//
bcmos_errno bcm_tr451_polt_grpc_server_init(void)
{
return BCM_ERR_OK;
}
bcmos_errno bcm_tr451_polt_grpc_server_create(const tr451_server_endpoint *endpoint)
{
bcmos_errno err = BCM_ERR_OK;
BCM_POLT_LOG(INFO, "Creating server %s: name_for_hello=%s listen=%s:%u\n",
endpoint->endpoint.name,
endpoint->local_name ? endpoint->local_name : endpoint->endpoint.name,
endpoint->endpoint.host_name ? endpoint->endpoint.host_name : "any",
endpoint->endpoint.port);
BcmPoltServer *server = new BcmPoltServer(endpoint);
if (bcm_grpc_processor_is_enabled(GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_SERVER))
{
err = server->CreateTaskAndStart();
}
return err;
}
// Get server by name
BcmPoltServer *bcm_polt_server_get_by_name(const char *name)
{
GrpcProcessor *entry = bcm_grpc_processor_get_by_name(name,
GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_SERVER);
return dynamic_cast<BcmPoltServer *>(entry);
}
bcmos_errno bcm_tr451_polt_grpc_server_start(const char *name)
{
GrpcProcessor *entry = bcm_grpc_processor_get_by_name(name,
GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_SERVER);
if (entry == nullptr)
return BCM_ERR_NOENT;
return entry->CreateTaskAndStart();
}
bcmos_errno bcm_tr451_polt_grpc_server_enable_disable(bcmos_bool enable)
{
return bcm_grpc_processor_enable_disable((bool)enable,
GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_SERVER);
}
bcmos_errno bcm_tr451_polt_grpc_server_stop(const char *name)
{
GrpcProcessor *entry = bcm_grpc_processor_get_by_name(name,
GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_SERVER);
if (entry == nullptr)
return BCM_ERR_NOENT;
entry->Stop();
return BCM_ERR_OK;
}
bcmos_errno bcm_tr451_polt_grpc_server_delete(const char *name)
{
GrpcProcessor *entry = bcm_grpc_processor_get_by_name(name,
GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_SERVER);
if (entry == nullptr)
return BCM_ERR_NOENT;
BcmPoltServer *server = dynamic_cast<BcmPoltServer *>(entry);
delete server;
return BCM_ERR_OK;
}
const char *bcm_tr451_polt_grpc_server_client_get_next(const char *prev)
{
VomciConnection *conn;
if (prev != nullptr)
{
conn = vomci_connection_get_by_name(prev);
if (conn != nullptr)
conn = vomci_connection_get_next(conn);
}
else
{
conn = vomci_connection_get_next(nullptr);
}
while (conn != nullptr && conn->parent()->type() != GrpcProcessor::processor_type::GRPC_PROCESSOR_TYPE_SERVER)
conn = vomci_connection_get_next(conn);
return (conn != nullptr) ? conn->name() : nullptr;
}
<file_sep>/*
<:copyright-BRCM:2016-2020:Apache:standard
Copyright (c) 2016-2020 Broadcom. All Rights Reserved
The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
:>
*/
#include "bcmos_system.h"
/* Map error code to error string */
const char *bcmos_strerror(bcmos_errno err)
{
static const char *errstr[] = {
[-BCM_ERR_OK] = "OK",
[-BCM_ERR_IN_PROGRESS] = "In progress",
[-BCM_ERR_PARM] = "Error in parameters",
[-BCM_ERR_NOMEM] = "No memory",
[-BCM_ERR_NORES] = "No resources",
[-BCM_ERR_INTERNAL] = "Internal error",
[-BCM_ERR_NOENT] = "Entry doesn't exist",
[-BCM_ERR_NODEV] = "Device doesn't exist",
[-BCM_ERR_ALREADY] = "Entry already exists/already in requested state",
[-BCM_ERR_RANGE] = "Out of range",
[-BCM_ERR_PERM] = "No permission to perform an operation",
[-BCM_ERR_NOT_SUPPORTED] = "Operation is not supported",
[-BCM_ERR_PARSE] = "Parsing error",
[-BCM_ERR_INVALID_OP] = "Invalid operation",
[-BCM_ERR_IO] = "I/O error",
[-BCM_ERR_STATE] = "Object is in bad state",
[-BCM_ERR_DELETED] = "Object is deleted",
[-BCM_ERR_TOO_MANY] = "Too many objects",
[-BCM_ERR_NO_MORE] = "No more entries",
[-BCM_ERR_OVERFLOW] = "Buffer overflow",
[-BCM_ERR_COMM_FAIL] = "Communication failure",
[-BCM_ERR_NOT_CONNECTED] = "No connection with the target system",
[-BCM_ERR_SYSCALL_ERR] = "System call returned error",
[-BCM_ERR_MSG_ERROR] = "Received message is insane",
[-BCM_ERR_TOO_MANY_REQS] = "Too many outstanding requests",
[-BCM_ERR_TIMEOUT] = "Operation timed out",
[-BCM_ERR_TOO_MANY_FRAGS] = "Too many fragments",
[-BCM_ERR_NULL] = "Got NULL pointer",
[-BCM_ERR_READ_ONLY] = "Attempt to set read-only parameter",
[-BCM_ERR_ONU_ERR_RESP] = "ONU returned an error response",
[-BCM_ERR_MANDATORY_PARM_IS_MISSING] = "Mandatory parameter is missing",
[-BCM_ERR_KEY_RANGE] = "Key field out of range",
[-BCM_ERR_QUEUE_EMPTY] = "Rx of PCIe empty",
[-BCM_ERR_QUEUE_FULL] = "Tx of PCIe full",
[-BCM_ERR_TOO_LONG] = "Processing is taking too long, but will finish eventually",
[-BCM_ERR_INSUFFICIENT_LIST_MEM] = "Insufficient list memory provided",
[-BCM_ERR_OUT_OF_SYNC] = "Sequence number or operation step was out of sync",
[-BCM_ERR_CHECKSUM] = "Checksum error",
[-BCM_ERR_IMAGE_TYPE] = "Unsupported file/image type",
[-BCM_ERR_INCOMPLETE_TERMINATION] = "Incomplete premature termination",
[-BCM_ERR_MISMATCH] = "Parameters mismatch",
[-BCM_ERR_DEPRECATED] = "Parameter is deprecated",
};
static const char *unknown = "*unknown*";
if ((unsigned)(-err) >= sizeof(errstr)/sizeof(errstr[0]) || !errstr[-err])
return unknown;
return errstr[-err];
}
#ifdef __KERNEL__
EXPORT_SYMBOL(bcmos_strerror);
#endif
<file_sep>#====
# Create the system library
#====
bcm_module_name(utils)
bcm_module_header_paths(PUBLIC .)
bcm_module_dependencies(PUBLIC os)
file(GLOB_RECURSE _UTILS_FILES LIST_DIRECTORIES false
RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/*.c)
bcm_module_srcs(${_UTILS_FILES})
if(NOT OPEN_SOURCE)
# Create the library target, but don't reset the internal global variables. We are going to use
# them for the next target.
bcm_create_lib_target(NO_RESET)
#====
# Specifically reset the globals for the sources only.
#====
bcm_module_srcs(RESET)
#====
# Create the bootloader libary
#====
bcm_module_name(utils_boot)
bcm_module_definitions(PUBLIC -D_BLOADER_)
bcm_module_srcs(bcmolt_calc_crc32_table.c)
endif()
bcm_create_lib_target()
if("${OS_KERNEL}" STREQUAL "linux")
# Add additional subdirectories for this module
bcm_add_subdirectory(linux)
endif()
# Add files to the GitHub part of the release tree.
bcm_github_install(bcmolt_utils.* bcmolt_string.* bcmolt_math.h
bcmolt_buf.* bcmolt_calc_crc32_table.* bcmolt_mgt_group.*
bcmolt_conv.h bcmolt_presence_mask.h CMakeLists.txt
RELEASE github/utils)
<file_sep># This CMake module covers post processing done after all the sub-directories have been added.
# The post processing takes advantage of the fact that all the targets have been defined. The
# first thing that is done is to take a set of target properties that we want to use as transitive
# and then making them as such. Once we have that, processing related to those parameters can be done.
#======
# Define the target properties that we want to be transitive. These will be 'flattened' so that if
# any one target looks a the properties, they will see all the entries bubbled up. It is guaranteed that
# the property will not have duplicate entries. Each property name will get prepended by INTERFACE_TRANSITIVE_
# to know where they are flattened to. Since the transitive properties have to start with INTERFACE,
# it is expected the entries will not include that.
#======
set(_TARGET_TRANSITIVE_PROPERTIES LINK_LIBRARIES
SYSTEM_LIBRARIES)
#======
# PRIVATE: Function to get the link libraries. For Interface libraries, this is the INTERFACE_LINK_LIBRARIES
# and for all others it is the LINK_LIBRARIES (to get both public and private). Returns a list of the
# library dependencies.
# @param LIBS_LIST [out] List of libraries we want.
# @param MOD [in] Module we want the dependencies from.
#======
function(_bcm_get_library_list_for_mod LIBS_LIST MOD)
bcm_get_target_property(_MY_TYPE ${MOD} TYPE)
if("${_MY_TYPE}" STREQUAL "INTERFACE_LIBRARY")
# Interface libraries can only have INTERFACE_LINK_LIBRARIES
bcm_get_target_property(_MOD_LIBS ${MOD} INTERFACE_LINK_LIBRARIES)
else()
# All other target types can have both public and private libraries
bcm_get_target_property(_MOD_LIBS ${MOD} LINK_LIBRARIES)
endif()
# Make sure that all the Link Libraries are targets and, if not, we want to flag this as a fatal error. Anything
# flagged indicates it is in the module's dependency list, but there is no build target for it.
unset(_MISSING_DEPS)
foreach(_LIB ${_MOD_LIBS})
if(NOT TARGET ${_LIB})
list(APPEND _MISSING_DEPS ${_LIB})
endif()
endforeach(_LIB)
if(_MISSING_DEPS)
bcm_message(STATUS "The following libraries for '${MOD}' were not found: ${_MISSING_DEPS}")
list(REMOVE_ITEM _MOD_LIBS ${_MISSING_DEPS})
endif()
# If we got here we are good so update the output list
set(${LIBS_LIST} ${_MOD_LIBS} PARENT_SCOPE)
endfunction(_bcm_get_library_list_for_mod)
#======
# PRIVATE: Function to bubble up the options we want to the given module target. The output is updated target
# properties for the given module.
#
# @param MOD [in] module that we want the transitive properties added to
# @param ARGN [in] list of targets that we want to bubble up
#======
function(_bcm_bubble_up_properties MOD)
# Next get the transitive properties on the module and add the modules properties in
foreach(_PROP ${_TARGET_TRANSITIVE_PROPERTIES})
bcm_get_target_property(_MOD_INTERFACE_TRANSITIVE_${_PROP} ${MOD} INTERFACE_TRANSITIVE_${_PROP})
endforeach(_PROP)
# Now walk the dependencies and bubble up the values
foreach(_DEP ${ARGN})
foreach(_PROP ${_TARGET_TRANSITIVE_PROPERTIES})
bcm_get_target_property(_DEP_INTERFACE_TRANSITIVE ${_DEP} INTERFACE_TRANSITIVE_${_PROP})
if(DEFINED _DEP_INTERFACE_TRANSITIVE)
list(APPEND _MOD_INTERFACE_TRANSITIVE_${_PROP} ${_DEP_INTERFACE_TRANSITIVE})
endif()
endforeach(_PROP)
endforeach(_DEP)
# Now make sure they are unique and update the module
foreach(_PROP ${_TARGET_TRANSITIVE_PROPERTIES})
if(DEFINED _MOD_INTERFACE_TRANSITIVE_${_PROP})
list(REMOVE_DUPLICATES _MOD_INTERFACE_TRANSITIVE_${_PROP})
set_target_properties(${MOD} PROPERTIES INTERFACE_TRANSITIVE_${_PROP}
"${_MOD_INTERFACE_TRANSITIVE_${_PROP}}")
endif()
endforeach(_PROP)
endfunction(_bcm_bubble_up_properties)
#======
# PRIVATE: This function does the recursion through the depth of transitive link libraries to determine what target
# properties should be bubbled up to create the flattended property lists. We use the target property,
# INTERFACE_PROCESS_STATE with a value of 'undefined', 'continue', 'done'. The 'undefined' means we
# haven't done anything with that module yet, the 'started' keeps us from being stuck in circular dependencies
# and 'done' keeps us from reprocessing a library tree we've already seen.
#
# @param MOD [in] Module name
# @param ARGN [in] List of dependencies to look through for the module
#======
function(_bcm_recurse_transitive_dependencies MOD)
if(TARGET ${MOD})
bcm_get_target_property(_MOD_PROCESSED ${MOD} INTERFACE_PROCESS_STATE)
if(NOT "${_MOD_PROCESSED}" STREQUAL "DONE")
# This module has not been walked yet, so go ahead and do it.
if(${ARGC} GREATER 1)
foreach(_LIB ${ARGN})
# Check if each library is already processed and, if not, recurse to look at its dependencies.
if(TARGET ${_LIB})
bcm_get_target_property(_LIB_PROCESSED ${_LIB} INTERFACE_PROCESS_STATE)
if("${_LIB_PROCESSED}" STREQUAL "DONE")
# The library is already flattened (all transitive dependencies have been addressed).
# We can just add them in.
_bcm_bubble_up_properties(${MOD} ${_LIB})
elseif(NOT DEFINED _LIB_PROCESSED)
# The library is not yet processed, so dig in and see any below it.
set_target_properties(${MOD} PROPERTIES INTERFACE_PROCESS_STATE STARTED)
_bcm_get_library_list_for_mod(_MOD_LIBS ${_LIB})
_bcm_recurse_transitive_dependencies(${_LIB} ${_MOD_LIBS})
_bcm_bubble_up_properties(${MOD} ${_LIB})
endif()
endif()
endforeach(_LIB)
else()
# We are at the bottom of this branch, so just add the properties to the transitive
_bcm_bubble_up_properties(${MOD})
endif()
# Add in the module level settings to the transitive
foreach(_PROP ${_TARGET_TRANSITIVE_PROPERTIES})
bcm_get_target_property(_MOD_INTERFACE_TRANSITIVE ${MOD} INTERFACE_TRANSITIVE_${_PROP})
if("${_PROP}" STREQUAL "LINK_LIBRARIES")
_bcm_get_library_list_for_mod(_MOD_THIS_PROP ${MOD})
else()
bcm_get_target_property(_MOD_THIS_PROP ${MOD} INTERFACE_${_PROP})
endif()
if(DEFINED _MOD_THIS_PROP)
list(APPEND _MOD_INTERFACE_TRANSITIVE ${_MOD_THIS_PROP})
list(REMOVE_DUPLICATES _MOD_INTERFACE_TRANSITIVE)
set_target_properties(${MOD} PROPERTIES INTERFACE_TRANSITIVE_${_PROP}
"${_MOD_INTERFACE_TRANSITIVE}")
endif()
endforeach(_PROP)
# Mark this module as processed
set_target_properties(${MOD} PROPERTIES INTERFACE_PROCESS_STATE DONE)
endif()
endif()
endfunction(_bcm_recurse_transitive_dependencies)
#======
# Walk the applications and shared libraries and get the transitive target properties as a flat list
# for each of the properties defined in _TARGET_TRANSITIVE_PROPERTIES. We can then use these for other
# processing (e.g. determine the "system" libraries that we link to for an application or shared library.
#======
macro(bcm_flatten_transitive_dependencies)
foreach(_MOD ${BCM_ALL_APP_MODULES} ${BCM_ALL_SHARED_LIB_MODULES})
# For applications and shared libraries we need to look at both private and public dependencies
# so we use the LINK_LIBRARIES property.
get_target_property(_MOD_PUBLIC_LIBS ${_MOD} LINK_LIBRARIES)
_bcm_recurse_transitive_dependencies(${_MOD} ${_MOD_PUBLIC_LIBS})
# Cache the transitive dependencies for future reference
foreach(_PROP ${_TARGET_TRANSITIVE_PROPERTIES})
bcm_get_target_property(_MOD_TRANSITIVE_PROP ${_MOD} INTERFACE_TRANSITIVE_${_PROP})
if(DEFINED _MOD_TRANSITIVE_PROP)
set(${_MOD}_${_PROP} ${_MOD_TRANSITIVE_PROP} CACHE STRING
"Flat ${_PROP} for '${_MOD}'" FORCE)
endif()
endforeach(_PROP)
# For the ARMCC case, we also want to collect the libraries and paths in the cache
if(COMMAND armlink_post_process_lib_setup)
armlink_post_process_lib_setup(${_MOD})
endif()
endforeach(_MOD)
endmacro(bcm_flatten_transitive_dependencies)
#======
# For optional dependencies, we need to walk all the modules added and look for definition of an optional
# dependency, then look if it exists. If an optional dependency is found and the dependency is a build target,
# add the depdendency to the module.
#======
macro(bcm_eval_optional_dependencies)
foreach(_MOD ${BCM_ALL_APP_MODULES} ${BCM_ALL_SHARED_LIB_MODULES} ${BCM_ALL_LIB_MODULES})
foreach(_LEVEL PUBLIC PRIVATE INTERFACE)
bcm_get_target_property(_MOD_OPTIONAL ${_MOD} INTERFACE_OPTIONAL_${_LEVEL}_LIBRARIES)
foreach(_OPT ${_MOD_OPTIONAL})
if(TARGET ${_OPT})
# The optional dependency exists as a target in our build so now it becomes
# mandatory. We can't use 'target_link_libraries' here because it can only
# be used in the subdirectory where the target was defined. Instead we directly
# add to the LINK_LIBRARIES.
bcm_get_target_property(_MOD_LINK_LIBS ${_MOD} INTERFACE_LINK_LIBRARIES)
if("${_LEVEL}" STREQUAL "PRIVATE")
# Indicates that we link to this, but do not make it transitive
list(APPEND _MOD_LINK_LIBS $<LINK_ONLY:${_OPT}>)
else()
# Public will link, Interface will not (according to CMake docs)
list(APPEND _MOD_LINK_LIBS ${_OPT})
endif()
set_target_properties(${_MOD} PROPERTIES INTERFACE_LINK_LIBRARIES "${_MOD_LINK_LIBS}")
bcm_message(STATUS "Optional dependency '${_OPT}' added to '${_MOD}'")
endif()
endforeach(_OPT)
endforeach(_LEVEL)
endforeach(_MOD)
endmacro(bcm_eval_optional_dependencies)
<file_sep>#!/usr/bin/env python
#
# Script to find the list of 'make' options from the CMake cache and output to stdout. This is
# used to dump the available options for 'make help'.
#
import os.path
import sys
import re
import subprocess
# Usage for the script
def usage():
print "usage: " + os.path.basename(sys.argv[0]) + " <list type> <build path>"
print " list type - Type of option list (e.g. normal or debug)"
print " build path - Top of the build object tree (e.g. build/embedded-<platform>)"
print
exit(1)
# Get the parameters
list_type = sys.argv[1]
cache_path = os.path.join(sys.argv[2], "CMakeCache.txt")
# There is nothing to output if the build path does not exist
if not os.path.exists(cache_path):
exit(0)
# Look for the variables we want from the cache file. If these exist, they will be CMake lists (';' delimeter)
search_base = "BCM_" + list_type.upper() + "_"
file = open(cache_path, "r")
options = []
descriptions = []
values = []
cache_contents = file.readlines()
for line in cache_contents:
if re.search(search_base + "OPTIONS", line):
options = line.replace(search_base + "OPTIONS:STRING=", "").strip().split(';')
if re.search(search_base + "DESCRIPTIONS", line):
descriptions = line.replace(search_base + "DESCRIPTIONS:STRING=", "").strip().split(';')
# Next go through the cache_contents and find the current value for variables.
for option in options:
r = re.compile(option + ":.*=")
option_line = filter(r.match, cache_contents)[0].strip()
values.append(r.sub("", option_line))
# At this point if the cache had the values we have two lists, one with the option and one with the description
for idx, val in enumerate(options):
print(" %-25s - %s [current='%s']" % (val, descriptions[idx], values[idx]))
exit(0)
|
7e9351ba69c41c5266d4307e91c3f9a52355c290
|
[
"CMake",
"YAML",
"Markdown",
"Makefile",
"Dockerfile",
"Python",
"C",
"C++",
"Shell"
] | 121
|
Makefile
|
akhileshkumar7662/obbaa-polt-simulator
|
459efdbadb0816974e386a5003d61a1b1c7dbc29
|
4d75ed5d1c38f2d43eea95834757c085835e239e
|
refs/heads/master
|
<repo_name>zhaoke2011/JAE<file_sep>/jae/modules/admin/templates/menu_edit.tpl.php
<?php include $this->admin_tpl('head');
?>
<form name="myform" id="myform" action="/admin.php?m=admin&c=menu&a=edit" method="post">
<table width="100%" class="table_form contentWrap">
<tbody><tr>
<th width="200">上级菜单:</th>
<td><select name="info[parentid]">
<option value="0">作为一级菜单</option>
<?php echo $select_categorys;?>
</select></td>
</tr>
<tr>
<th> 对应的中文语言名称:</th>
<td><input type="text" name="info[name]" id="language" class="input-text" value="<?php echo $name;?>"><div id="languageTip" class="onShow">请输入对应的中文语言名称</div></td>
</tr>
<tr>
<th>菜单英文名称:</th>
<td><input type="text" name="info[language]" id="name" class="input-text" value="<?php echo $language;?>"><div id="nameTip" class="onShow">请输入菜单英文名称</div></td>
</tr>
<tr>
<th>模块名:</th>
<td><input type="text" name="info[m]" id="m" class="input-text" value="<?php echo $m;?>"><div id="mTip" class="onShow">请输入模块名</div></td>
</tr>
<tr>
<th>文件名:</th>
<td><input type="text" name="info[c]" id="c" class="input-text" value="<?php echo $c;?>"><div id="cTip" class="onShow">请输入文件名</div></td>
</tr>
<tr>
<th>方法名:</th>
<td><input type="text" name="info[a]" id="a" class="input-text" value="<?php echo $a;?>"> <span id="a_tip" class="onShow">请输入方法名</span>通过AJAX 传递的方法,请使用 ajax_开头,方法为修改或删除操作时,请对应写成,ajax_edit_myaction/ajax_delete_myaction</td>
</tr>
<tr>
<th>附加参数:</th>
<td><input type="text" name="info[data]" class="input-text" value="<?php echo $data;?>"></td>
</tr>
<tr>
<th>是否显示菜单:</th>
<td><input type="radio" name="info[display]" value="1" <?php if($display==1) echo "checked";?>> 是<input type="radio" name="info[display]" value="0" <?php if($display==0) echo "checked";?>> 否</td>
</tr>
<tr>
<th>在此模式中显示:</th>
<td><input type="checkbox" name="info[project1]" value="1"> 经典模式</td>
</tr>
</tbody></table>
<!--table_form_off--><input name="id" type="hidden" value="<?php echo $id?>">
<div class="btns"><input type="submit" id="dosubmit" class="button" name="dosubmit" value="提交"></div>
</form>
<?php include $this->admin_tpl('foot');?><file_sep>/caches/caches_commons/caches_data/category_content_1.cache.php
<?php
return array (
1 =>
array (
'catid' => '1',
0 => '1',
'siteid' => '1',
1 => '1',
2 => 'content',
'type' => '0',
3 => '0',
'modelid' => '1',
4 => '1',
'parentid' => '0',
5 => '0',
'arrparentid' => NULL,
6 => NULL,
'child' => '0',
7 => '0',
'arrchildid' => NULL,
8 => NULL,
'catname' => '商品大全',
9 => '商品大全',
'style' => NULL,
10 => NULL,
'image' => '',
11 => '',
'description' => '',
12 => '',
'parentdir' => NULL,
13 => NULL,
'catdir' => '',
14 => '',
'url' => '/index.php?m=content&c=index&a=lists&catid=1',
15 => '/index.php?m=content&c=index&a=lists&catid=1',
'items' => '0',
16 => '0',
'hits' => '0',
17 => '0',
'setting' => 'array (
\'modelid\' => \'1\',
\'siteid\' => \'1\',
\'name\' => \'商品模型\',
\'description\' => \'\',
\'tablename\' => \'goods\',
\'setting\' => \'\',
\'addtime\' => \'0\',
\'items\' => \'0\',
\'enablesearch\' => \'1\',
\'disabled\' => \'0\',
\'default_style\' => \'default\',
\'category_template\' => \'category_goods\',
\'list_template\' => \'list_goods\',
\'show_template\' => \'show_goods\',
\'js_template\' => \'\',
\'admin_list_template\' => \'\',
\'member_add_template\' => \'\',
\'member_list_template\' => \'\',
\'sort\' => \'0\',
\'type\' => \'0\',
)',
18 => 'array (
\'modelid\' => \'1\',
\'siteid\' => \'1\',
\'name\' => \'商品模型\',
\'description\' => \'\',
\'tablename\' => \'goods\',
\'setting\' => \'\',
\'addtime\' => \'0\',
\'items\' => \'0\',
\'enablesearch\' => \'1\',
\'disabled\' => \'0\',
\'default_style\' => \'default\',
\'category_template\' => \'category_goods\',
\'list_template\' => \'list_goods\',
\'show_template\' => \'show_goods\',
\'js_template\' => \'\',
\'admin_list_template\' => \'\',
\'member_add_template\' => \'\',
\'member_list_template\' => \'\',
\'sort\' => \'0\',
\'type\' => \'0\',
)',
'listorder' => '1',
19 => '1',
'ismenu' => '1',
20 => '1',
'sethtml' => '0',
21 => '0',
'letter' => NULL,
22 => NULL,
'usable_type' => NULL,
23 => NULL,
'create_to_html_root' => NULL,
'ishtml' => NULL,
'content_ishtml' => NULL,
'category_ruleid' => NULL,
'show_ruleid' => NULL,
'workflowid' => NULL,
'isdomain' => '0',
),
2 =>
array (
'catid' => '2',
0 => '2',
'siteid' => '1',
1 => '1',
2 => 'content',
'type' => '0',
3 => '0',
'modelid' => '2',
4 => '2',
'parentid' => '0',
5 => '0',
'arrparentid' => NULL,
6 => NULL,
'child' => '0',
7 => '0',
'arrchildid' => NULL,
8 => NULL,
'catname' => '特色店铺',
9 => '特色店铺',
'style' => NULL,
10 => NULL,
'image' => '',
11 => '',
'description' => '',
12 => '',
'parentdir' => NULL,
13 => NULL,
'catdir' => '',
14 => '',
'url' => '/index.php?m=content&c=index&a=lists&catid=2',
15 => '/index.php?m=content&c=index&a=lists&catid=2',
'items' => '0',
16 => '0',
'hits' => '0',
17 => '0',
'setting' => 'array (
\'modelid\' => \'2\',
\'siteid\' => \'1\',
\'name\' => \'店铺模型\',
\'description\' => \'\',
\'tablename\' => \'download\',
\'setting\' => \'\',
\'addtime\' => \'0\',
\'items\' => \'0\',
\'enablesearch\' => \'1\',
\'disabled\' => \'0\',
\'default_style\' => \'default\',
\'category_template\' => \'category_shop\',
\'list_template\' => \'list_shop\',
\'show_template\' => \'show_shop\',
\'js_template\' => \'\',
\'admin_list_template\' => \'\',
\'member_add_template\' => \'\',
\'member_list_template\' => \'\',
\'sort\' => \'0\',
\'type\' => \'0\',
)',
18 => 'array (
\'modelid\' => \'2\',
\'siteid\' => \'1\',
\'name\' => \'店铺模型\',
\'description\' => \'\',
\'tablename\' => \'download\',
\'setting\' => \'\',
\'addtime\' => \'0\',
\'items\' => \'0\',
\'enablesearch\' => \'1\',
\'disabled\' => \'0\',
\'default_style\' => \'default\',
\'category_template\' => \'category_shop\',
\'list_template\' => \'list_shop\',
\'show_template\' => \'show_shop\',
\'js_template\' => \'\',
\'admin_list_template\' => \'\',
\'member_add_template\' => \'\',
\'member_list_template\' => \'\',
\'sort\' => \'0\',
\'type\' => \'0\',
)',
'listorder' => '2',
19 => '2',
'ismenu' => '1',
20 => '1',
'sethtml' => '0',
21 => '0',
'letter' => NULL,
22 => NULL,
'usable_type' => NULL,
23 => NULL,
'create_to_html_root' => NULL,
'ishtml' => NULL,
'content_ishtml' => NULL,
'category_ruleid' => NULL,
'show_ruleid' => NULL,
'workflowid' => NULL,
'isdomain' => '0',
),
3 =>
array (
'catid' => '3',
0 => '3',
'siteid' => '1',
1 => '1',
2 => 'content',
'type' => '0',
3 => '0',
'modelid' => '4',
4 => '4',
'parentid' => '0',
5 => '0',
'arrparentid' => NULL,
6 => NULL,
'child' => '0',
7 => '0',
'arrchildid' => NULL,
8 => NULL,
'catname' => '美食专辑',
9 => '美食专辑',
'style' => NULL,
10 => NULL,
'image' => '',
11 => '',
'description' => '',
12 => '',
'parentdir' => NULL,
13 => NULL,
'catdir' => '',
14 => '',
'url' => '/index.php?m=content&c=index&a=lists&catid=3',
15 => '/index.php?m=content&c=index&a=lists&catid=3',
'items' => '0',
16 => '0',
'hits' => '0',
17 => '0',
'setting' => 'array (
\'modelid\' => \'4\',
\'siteid\' => \'1\',
\'name\' => \'专题模型\',
\'description\' => \'\',
\'tablename\' => \'video\',
\'setting\' => \'\',
\'addtime\' => \'0\',
\'items\' => \'0\',
\'enablesearch\' => \'1\',
\'disabled\' => \'0\',
\'default_style\' => \'default\',
\'category_template\' => \'category_special\',
\'list_template\' => \'list_special\',
\'show_template\' => \'show_special\',
\'js_template\' => \'\',
\'admin_list_template\' => \'\',
\'member_add_template\' => \'\',
\'member_list_template\' => \'\',
\'sort\' => \'0\',
\'type\' => \'0\',
)',
18 => 'array (
\'modelid\' => \'4\',
\'siteid\' => \'1\',
\'name\' => \'专题模型\',
\'description\' => \'\',
\'tablename\' => \'video\',
\'setting\' => \'\',
\'addtime\' => \'0\',
\'items\' => \'0\',
\'enablesearch\' => \'1\',
\'disabled\' => \'0\',
\'default_style\' => \'default\',
\'category_template\' => \'category_special\',
\'list_template\' => \'list_special\',
\'show_template\' => \'show_special\',
\'js_template\' => \'\',
\'admin_list_template\' => \'\',
\'member_add_template\' => \'\',
\'member_list_template\' => \'\',
\'sort\' => \'0\',
\'type\' => \'0\',
)',
'listorder' => '3',
19 => '3',
'ismenu' => '1',
20 => '1',
'sethtml' => '0',
21 => '0',
'letter' => NULL,
22 => NULL,
'usable_type' => NULL,
23 => NULL,
'create_to_html_root' => NULL,
'ishtml' => NULL,
'content_ishtml' => NULL,
'category_ruleid' => NULL,
'show_ruleid' => NULL,
'workflowid' => NULL,
'isdomain' => '0',
),
7 =>
array (
'catid' => '7',
0 => '7',
'siteid' => '1',
1 => '1',
2 => 'content',
'type' => '2',
3 => '2',
'modelid' => '0',
4 => '0',
'parentid' => '0',
5 => '0',
'arrparentid' => NULL,
6 => NULL,
'child' => '0',
7 => '0',
'arrchildid' => NULL,
8 => NULL,
'catname' => '积分抽奖',
9 => '积分抽奖',
'style' => NULL,
10 => NULL,
'image' => '',
11 => '',
'description' => NULL,
12 => NULL,
'parentdir' => NULL,
13 => NULL,
'catdir' => NULL,
14 => NULL,
'url' => '/index.php?m=prize&c=index&a=init',
15 => '/index.php?m=prize&c=index&a=init',
'items' => '0',
16 => '0',
'hits' => '0',
17 => '0',
'setting' => '',
18 => '',
'listorder' => '4',
19 => '4',
'ismenu' => '1',
20 => '1',
'sethtml' => '0',
21 => '0',
'letter' => NULL,
22 => NULL,
'usable_type' => NULL,
23 => NULL,
'create_to_html_root' => NULL,
'ishtml' => NULL,
'content_ishtml' => NULL,
'category_ruleid' => NULL,
'show_ruleid' => NULL,
'workflowid' => NULL,
'isdomain' => '0',
),
8 =>
array (
'catid' => '8',
0 => '8',
'siteid' => '1',
1 => '1',
2 => 'content',
'type' => '2',
3 => '2',
'modelid' => '0',
4 => '0',
'parentid' => '0',
5 => '0',
'arrparentid' => NULL,
6 => NULL,
'child' => '0',
7 => '0',
'arrchildid' => NULL,
8 => NULL,
'catname' => '积分换购',
9 => '积分换购',
'style' => NULL,
10 => NULL,
'image' => '',
11 => '',
'description' => NULL,
12 => NULL,
'parentdir' => NULL,
13 => NULL,
'catdir' => NULL,
14 => NULL,
'url' => '/index.php?m=exchange&c=index&a=init',
15 => '/index.php?m=exchange&c=index&a=init',
'items' => '0',
16 => '0',
'hits' => '0',
17 => '0',
'setting' => '',
18 => '',
'listorder' => '5',
19 => '5',
'ismenu' => '1',
20 => '1',
'sethtml' => '0',
21 => '0',
'letter' => NULL,
22 => NULL,
'usable_type' => NULL,
23 => NULL,
'create_to_html_root' => NULL,
'ishtml' => NULL,
'content_ishtml' => NULL,
'category_ruleid' => NULL,
'show_ruleid' => NULL,
'workflowid' => NULL,
'isdomain' => '0',
),
9 =>
array (
'catid' => '9',
0 => '9',
'siteid' => '1',
1 => '1',
2 => 'content',
'type' => '2',
3 => '2',
'modelid' => '0',
4 => '0',
'parentid' => '0',
5 => '0',
'arrparentid' => NULL,
6 => NULL,
'child' => '0',
7 => '0',
'arrchildid' => NULL,
8 => NULL,
'catname' => '积分整点聚',
9 => '积分整点聚',
'style' => NULL,
10 => NULL,
'image' => '',
11 => '',
'description' => NULL,
12 => NULL,
'parentdir' => NULL,
13 => NULL,
'catdir' => NULL,
14 => NULL,
'url' => '/index.php?m=seckill&c=index&a=init',
15 => '/index.php?m=seckill&c=index&a=init',
'items' => '0',
16 => '0',
'hits' => '0',
17 => '0',
'setting' => '',
18 => '',
'listorder' => '5',
19 => '5',
'ismenu' => '1',
20 => '1',
'sethtml' => '0',
21 => '0',
'letter' => NULL,
22 => NULL,
'usable_type' => NULL,
23 => NULL,
'create_to_html_root' => NULL,
'ishtml' => NULL,
'content_ishtml' => NULL,
'category_ruleid' => NULL,
'show_ruleid' => NULL,
'workflowid' => NULL,
'isdomain' => '0',
),
4 =>
array (
'catid' => '4',
0 => '4',
'siteid' => '1',
1 => '1',
2 => 'content',
'type' => '2',
3 => '2',
'modelid' => '0',
4 => '0',
'parentid' => '0',
5 => '0',
'arrparentid' => NULL,
6 => NULL,
'child' => '0',
7 => '0',
'arrchildid' => NULL,
8 => NULL,
'catname' => '服务承诺',
9 => '服务承诺',
'style' => NULL,
10 => NULL,
'image' => '',
11 => '',
'description' => NULL,
12 => NULL,
'parentdir' => NULL,
13 => NULL,
'catdir' => NULL,
14 => NULL,
'url' => 'http://bangpai.taobao.com/group/thread/14715437-289148642.htm?spm=a216r.7118237.1.11.KQLGYX',
15 => 'http://bangpai.taobao.com/group/thread/14715437-289148642.htm?spm=a216r.7118237.1.11.KQLGYX',
'items' => '0',
16 => '0',
'hits' => '0',
17 => '0',
'setting' => '',
18 => '',
'listorder' => '7',
19 => '7',
'ismenu' => '1',
20 => '1',
'sethtml' => '0',
21 => '0',
'letter' => NULL,
22 => NULL,
'usable_type' => NULL,
23 => NULL,
'create_to_html_root' => NULL,
'ishtml' => NULL,
'content_ishtml' => NULL,
'category_ruleid' => NULL,
'show_ruleid' => NULL,
'workflowid' => NULL,
'isdomain' => '0',
),
5 =>
array (
'catid' => '5',
0 => '5',
'siteid' => '1',
1 => '1',
2 => 'content',
'type' => '2',
3 => '2',
'modelid' => '0',
4 => '0',
'parentid' => '0',
5 => '0',
'arrparentid' => NULL,
6 => NULL,
'child' => '0',
7 => '0',
'arrchildid' => NULL,
8 => NULL,
'catname' => '商家报名',
9 => '商家报名',
'style' => NULL,
10 => NULL,
'image' => '',
11 => '',
'description' => NULL,
12 => NULL,
'parentdir' => NULL,
13 => NULL,
'catdir' => NULL,
14 => NULL,
'url' => '/index.php?spm=a216r.7118237.1.13.F535ND&m=member&c=index&a=goods_apply',
15 => '/index.php?spm=a216r.7118237.1.13.F535ND&m=member&c=index&a=goods_apply',
'items' => '0',
16 => '0',
'hits' => '0',
17 => '0',
'setting' => '',
18 => '',
'listorder' => '8',
19 => '8',
'ismenu' => '1',
20 => '1',
'sethtml' => '0',
21 => '0',
'letter' => NULL,
22 => NULL,
'usable_type' => NULL,
23 => NULL,
'create_to_html_root' => NULL,
'ishtml' => NULL,
'content_ishtml' => NULL,
'category_ruleid' => NULL,
'show_ruleid' => NULL,
'workflowid' => NULL,
'isdomain' => '0',
),
6 =>
array (
'catid' => '6',
0 => '6',
'siteid' => '1',
1 => '1',
2 => 'content',
'type' => '2',
3 => '2',
'modelid' => '0',
4 => '0',
'parentid' => '0',
5 => '0',
'arrparentid' => NULL,
6 => NULL,
'child' => '0',
7 => '0',
'arrchildid' => NULL,
8 => NULL,
'catname' => '招商说明',
9 => '招商说明',
'style' => NULL,
10 => NULL,
'image' => '',
11 => '',
'description' => NULL,
12 => NULL,
'parentdir' => NULL,
13 => NULL,
'catdir' => NULL,
14 => NULL,
'url' => 'http://bangpai.taobao.com/group/thread/14715437-286960706.htm',
15 => 'http://bangpai.taobao.com/group/thread/14715437-286960706.htm',
'items' => '0',
16 => '0',
'hits' => '0',
17 => '0',
'setting' => '',
18 => '',
'listorder' => '9',
19 => '9',
'ismenu' => '1',
20 => '1',
'sethtml' => '0',
21 => '0',
'letter' => NULL,
22 => NULL,
'usable_type' => NULL,
23 => NULL,
'create_to_html_root' => NULL,
'ishtml' => NULL,
'content_ishtml' => NULL,
'category_ruleid' => NULL,
'show_ruleid' => NULL,
'workflowid' => NULL,
'isdomain' => '0',
),
);
?><file_sep>/jae/modules/point/templates/point_setinfo.tpl.php
<?php include $this->admin_tpl('head','admin');
?>
<form name="myform" id="myform" action="/admin.php?m=point&c=point_set&a=point_setinfo" method="post">
<table width="100%" class="table_form contentWrap">
<tbody>
<tr>
<th width="150">启用:</th>
<td><input type="radio" name="setting[enable]" value="1" <?php if($enable==1) echo "checked"?>> 是
<input type="radio" name="setting[enable]" value="0" <?php if($enable==0) echo "checked"?>> 否</td>
</tr>
<tr>
<th width="100"> 任务标题:</th>
<td><input style="width:300px;" type="text" name="setting[title]" value="<?php echo $title?>" class="input-text"><div id="languageTip" class="onShow"></div></td>
</tr>
<tr>
<th> 任务描述:</th>
<td><input style="width:300px;" type="text" name="setting[description]" value="<?php echo $description?>" class="input-text"><div id="languageTip" class="onShow"></div></td>
</tr>
<tr>
<th>任务图片:</th>
<td> <input style="width:300px;" type="text" name="setting[thumb]" value="<?php echo $thumb?>" class="input-text"><div id="nameTip" class="onShow"></div></td>
</tr>
<tr>
<th>任务积分:</th>
<td><input style="width:300px;" type="text" name="setting[point]" value="<?php echo $point?>" class="input-text"><div id="nameTip" class="onShow"></div></td>
</tr>
</tbody></table>
<!--table_form_off-->
<div class="btns">
<input type="hidden" name="id" value="<?php echo $id?>"><input type="submit" id="dosubmit" class="button" name="dosubmit" value="提交"></div>
</form>
<?php include $this->admin_tpl('foot','admin');?><file_sep>/jae/modules/visualization/content.php
<?php
defined('IN_JAE') or exit('No permission resources.');defined('IN_ADMIN') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
class content extends admin {
function __construct() {
parent::__construct();
$this->block_db = jae_base::load_model('block_model');
$this->weblink_db = jae_base::load_model('weblink_model');
$this->position_data_db = jae_base::load_model('position_data_model');
$this->menuid=14;
}
function init () {
$a=$_GET['op'];
}
function position () {
$sql = '';
$array = array();
$posid = intval($_GET['posid']);
$order = $_GET['order'];
$data['limit'] = $_GET['num'];
$thumb = (empty($_GET['thumb']) || intval($_GET['thumb']) == 0) ? 0 : 1;
$siteid = $GLOBALS['siteid'] ? $GLOBALS['siteid'] : SITEID;
$catid = (empty($_GET['catid']) || $_GET['catid'] == 0) ? '' : intval($_GET['catid']);
if($catid) {
$siteids = getcache('category_content','commons');
if(!$siteids[$catid]) return false;
$siteid = $siteids[$catid];
$this->category = getcache('category_content_'.$siteid,'commons');
}
if($catid && $this->category[$catid]['child']) {
$catids_str = $this->category[$catid]['arrchildid'];
$pos = strpos($catids_str,',')+1;
$catids_str = substr($catids_str, $pos);
$sql = "`catid` IN ($catids_str) AND ";
} elseif($catid && !$this->category[$catid]['child']) {
$sql = "`catid` = '$catid' AND ";
}
if($thumb) $sql .= "`thumb` = '1' AND ";
if(isset($_GET['where'])) $sql .= $_GET['where'].' AND ';
if(isset($_GET['expiration']) && $_GET['expiration']==1) $sql .= '(`expiration` >= \''.SYS_TIME.'\' OR `expiration` = \'0\' ) AND ';
$sql .= "`posid` = '$posid' ";
$pos_arr = $this->position_data_db->select($sql, '*', $data['limit'],$order);
if(!empty($pos_arr)) {
foreach ($pos_arr as $info) {
$key = $info['catid'].'-'.$info['id'];
$array[$key] = string2array($info['data']);
//$array[$key]['url'] = go($info['catid'],$info['id']);
$array[$key]['posid']=$info['posid'];
$array[$key]['modelid']=$info['modelid'];
$array[$key]['url']=$info['url'];
$array[$key]['thumb']=$info['thumb'];
$array[$key]['id'] = $info['id'];
$array[$key]['catid'] = $info['catid'];
$array[$key]['listorder'] = $info['listorder'];
$array[$key]['begin_time'] = $info['begin_time'];
$array[$key]['end_time'] = $info['end_time'];
}
}
$infos=$array;
include $this->admin_tpl('position_items','position');
}
function listorder() {
if(isset($_POST['dosubmit'])) {
foreach($_POST['listorders'] as $id => $listorder) {
$listorder = !empty($listorder) ? $listorder : '0';
$this->db->update(array('listorder'=>$listorder),$this->table,'id='.$id);
$status = isset($_POST["status"][$id]) ? $_POST["status"][$id] : '0';
$this->db->update(array('status'=>$status),$this->table,'id='.$id);
}
showmessage(L('operation_success'));
} else {
showmessage(L('operation_failure'));
}
}
}
?><file_sep>/jae/modules/admin/templates/head.tpl.php
<link href="/statics/css/system.css" rel="stylesheet" type="text/css" />
<link href="/statics/css/table_form.css" rel="stylesheet" type="text/css" />
<?php $menuid=$_GET['menuid']; if ($menuid) { $menu=get_menu($menuid); } else {$menu=get_menu(10) ;} $current_version = jae_base::load_config('version'); $siteinfo=siteinfo(get_siteid());
?>
<div class="header" style="width: auto; ">
<div class="logo lf"><a href="/index.php" target="_blank"><span class="invisible">JAE特色中国管理系统</span></a></div>
<div class="rt-col">
<div class="tab_style white cut_line text-r"><a href="http://hubei.china.taobao.com" target="_blank">技术支持:湖北馆</a><span>|</span><a href="http://www.ehoneycomb.com" target="_blank">已授权</a><span>|</span><br>当前程序版本:<?php echo $current_version['jae_version']?> 更新日期:<?php echo $current_version['jae_release']?><br>
当前数据库版本:<?php echo $siteinfo['version']?> 更新日期:<?php echo $siteinfo['date']?>
<ul id="Skin">
<li class="s1 styleswitch" rel="styles1"></li>
<li class="s2 styleswitch" rel="styles2"></li>
<li class="s3 styleswitch" rel="styles3"></li>
<li class="s4 styleswitch" rel="styles4"></li>
</ul>
</div>
</div>
<div class="col-auto" style="float:left;">
<div class="log white cut_line">您好!<?php echo $siteinfo['name'];?> [超级管理员]<span>|</span>
<a href="/index.php?nocache=true" target="_blank" id="site_homepage">预览首页</a><span>|</span>
<a href="/admin.php" target="_blank">后台首页</a><span>|</span>
<a href="/member.php" target="_blank">会员中心</a><span>|</span>
</div>
<ul class="nav white" >
<?php
$mysql =jae_base::load_sys_class('mysql');//一级菜单
$result=$mysql->select('*','jae_menu','parentid=0 AND display=1 ORDER BY listorder,id ASC');
foreach($result as $r){
?>
<li id="_M7" class="top_menu <?php if ($menu[0]['id']==$r['id']) echo "on";?> "><a href="/admin.php?m=admin&c=index&a=init&menuid=<?php echo $r['id']?>" hidefocus="true" style="outline:none;"><?php echo $r['name']?></a></li>
<?php }?>
</ul>
</div>
</div>
<div class="contents" style="width: auto; ">
<div class="col-left left_menu">
<div id="Scroll" style="height: 520px; "><div id="leftMain">
<?php
$result=$mysql->select('*','jae_menu','parentid='.$menu[0]['id'].' AND display=1');//二级菜单
foreach($result as $r){
?>
<h3 class="f14"><span class="switchs cu on" title="展开与收缩"></span><?php echo $r['name']?></h3>
<ul>
<?php
$result=$mysql->select('*','jae_menu','parentid='.$r['id'].' AND display=1');//三级菜单
foreach($result as $r){
?>
<li id="_MP64" class="sub_menu <?php if ($menu[2]['id']==$r['id']) echo "on";?>"><a href="/admin.php?m=<?php echo $r['m']?>&c=<?php echo $r['c']?>&a=<?php echo $r['a']?>&<?php echo $r['data']?>&menuid=<?php echo $r['id']?>" hidefocus="true" style="outline:none;"><?php echo $r['name']?></a></li>
<?php }?>
</ul>
<?php }?>
<h3 class="f14"><span class="switchs cu on" title="展开与收缩"></span>图片空间</h3>
<ul> <li id="_MP64" class="sub_menu "><a href="http://tu.taobao.com/redaction/manager.htm" target="_blank">标准版</a>
<li id="_MP64" class="sub_menu "><a href="http://disk.taobao.com" target="_blank">商务版</a></ul>
</div></div>
<a href="javascript:;" id="openClose" style="outline: invert none medium; height: 431px; " hidefocus="hidefocus" class="open" title="展开与关闭"><span class="hidden">展开</span></a>
</div>
<div class="col-1 lf cat-menu" id="display_center_id" style="display: none; " height="100%">
<div class="content">
<iframe name="center_frame" id="center_frame" src="?m=content&c=content&a=public_categorys&type=add&menuid=822&pc_hash=NcwdoP" frameborder="false" scrolling="auto" style="border: none; height: 410px; " width="100%" height="auto" allowtransparency="true"></iframe>
</div>
</div>
<div class="col-auto mr8">
<div class="crumbs">
<div class="shortcut cu-span"><a href="/admin.php?m=content&c=create_html&a=public_index" ><span>生成首页</span></a><a href="/admin.php?m=admin&c=cache_all&a=init&dosubmit=1" ><span>更新缓存</span></a><a href="/admin.php?m=admin&c=menu&a=init&menuid=3"><span>后台地图</span></a><a href="http://sitemanager.jae.taobao.com/sitemanager/manage/magix.htm?bizType=15#!/manage/report/reports" target="_blank"><span>数据统计</span></a></div>
当前位置:<span id="current_pos">设置 > </span></div>
<div class="col-1">
<div class="content" style="position:relative; ">
<div name="right" class="right" id="rightMain" src="?m=content&c=content&a=init&menuid=822&pc_hash=NcwdoP" frameborder="false" scrolling="auto" style="border: none; margin-bottom: 30px; " width="100%" height="auto" allowtransparency="true">
<?php if ($menu[2]['id']){?>
<div class="subnav">
<div class="content-menu ib-a blue line-x">
<a href="/admin.php?menuid=<?php echo $menu[2]['id']?>&m=<?php echo $menu[2]['m']?>&c=<?php echo $menu[2]['c']?>&a=<?php echo $menu[2]['a']?>&data=<?php echo $menu[2]['data']?>" class=" <?php if ($menu[2]['id']==$_GET['menuid']) echo "on";?>"><em><?php echo $menu[2]['name']?></em></a><span>|</span>
<?php
$result=$mysql->select('*','jae_menu','parentid='.$menu[2]['id'].' AND display=1');
foreach($result as $r){
?>
<a href="/admin.php?menuid=<?php echo $r['id']?>&m=<?php echo $r['m']?>&c=<?php echo $r['c']?>&a=<?php echo $r['a']?>&<?php echo $r['data']?>" class=" <?php if ($menu[3]['id']==$r['id']) echo "on";?>"><em><?php echo $r['name']?></em></a><span>|</span>
<?php }?>
</div>
</div>
<?php }?>
<div style="padding:10px;"><file_sep>/caches/caches_template/default/member/goods_apply.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head'); ?>
<link href="/statics/css/apply.css" rel="stylesheet" type="text/css" />
<div class="blank"></div>
<div class="wrap">
<dl class="ui-tab clearfix" >
<dt>商品管理</dt>
<dd data-type="all" class="j_nativeHistory all <?php if(ROUTE_A=='goods_apply') echo "select"?> " data-template=""><a href="/index.php?m=member&c=index&a=goods_apply&manage=all">活动报名</a></dd>
<dd data-type="all" class="j_nativeHistory all <?php if($manage=='pass') echo "select"?> " data-template=""><a href="/index.php?m=member&c=index&a=goods_manage&manage=pass">已通过</a></dd>
<dd data-type="income" class="j_nativeHistory income <?php if($manage=='check') echo "select"?>" data-template="/point/detail/income"><a href="/index.php?m=member&c=index&a=goods_manage&manage=check ">审核中</a></dd>
<dd data-type="used" class="j_nativeHistory used <?php if($manage=='refuse') echo "select"?>" data-template="/point/detail/used"><a href="/index.php?m=member&c=index&a=goods_manage&manage=refuse">被拒绝</a></dd>
<!-- <dd data-type="expired" class="j_nativeHistory expired <?php if(ROUTE_A=='apply_task') echo "select"?>" ><a href="/index.php?m=member&c=index&a=apply_task">报名条件</a></dd> -->
<!-- <dd data-type="freezed" class="j_nativeHistory freezed" data-template="/point/detail/freezed">冻结积分</dd>-->
</dl>
<div class="clear"></div>
</div>
<div class="xf-layout xf-mb">
<!-- 两栏布局 -->
<div class="xf-m622s288">
<div class="xf-main">
<div class="xf-wrap">
<!-- 报名表单 -->
<div class="xf-form">
<div style="color: orange; text-align: center; padding-bottom: 10px;font-size: 20px;">
<?php echo $createMessage; ?>
</div>
<form name="form1" method="post">
<div class="f-itm">
<label class="f-label" for="">商品ID :</label>
<input class="f-text" name="num_iid" type="text" style="width:140px;" />
<input name="dopost" type="hidden" value="caiji"/>
<button class="f-btn" type="submit">获取商品信息</button>
</div>
</form>
<form name="form2" method="post">
<!-- 获取后出现下面的f-show -->
<div class="f-show">
<div style=" float:left">
<img src="<?php echo $pic_url; ?>" width="200" height="200" />
</div>
<table cellspacing="0" cellpadding="0" border="0" width="430">
<tr>
<th width="90">商品链接:</th>
<td><?php echo $detail_url; ?></td>
</tr>
<tr>
<th>是否包邮:</th>
<td><em><?php if($freight_payer=='seller') echo '是';elseif($freight_payer=='buyer') echo '否'; ?></em></td>
</tr>
<tr>
<th>店家昵称:</th>
<td><?php echo $nick;?></td>
</tr>
<tr>
<th>商品原价:</th>
<td>¥<?php echo $price;?></td>
</tr>
<tr>
<th>库存数量:</th>
<td><?php echo $num; ?>件</td>
</tr>
</table>
</div>
<div class="f-itm">
<label class="f-label" for="">商品分类 :</label>
<select name="category_id">
<option value="0">无分类</option>
<?php foreach($categoryArr as $catId=>$catName){; ?>
<option value="<?php echo $catId; ?>"><?php echo $catName; ?></option>
<?php }; ?>
</select>
<em>可改</em>
</div>
<div class="f-itm">
<label class="f-label" for="">商品主图 :</label>
<input class="f-text" name="pic_url" type="text" style="width:350px;" value=" <?php echo $pic_url; ?>" />
<em>必改*</em>
<div style="color:#999999">(要求图片高清、无文字和水印、大于230*230的正方形,最好是白底图)</div>
</div>
<div class="f-itm">
<label class="f-label" for="">*商品标题 :</label>
<input class="f-text" name="title" type="text" style="width:350px;" value="<?php echo $title; ?>" />
<em>必改*</em>
</div>
<div class="f-itm">
<label class="f-label" for="">*商品特价 :</label>
<input class="f-text" name="coupon_price" type="text" style="width:350px;" value="<?php echo $coupon_price; ?>" />
<em>必改*</em>
<div style="color:#999999">(审核时发现宝贝页的折扣价与商品特价不符时不予通过,请报名后立刻调整折扣价)</div>
</div>
<div class="f-itm">
<label class="f-label" for="">卖点描述 :</label>
<textarea name="description" class="f-text" style="width:366px;height:80px;"></textarea><em>必填*</em>
</div>
<div class="f-itm">
<input name="num_iid" type="hidden" value="<?php echo $num_iid; ?>"/>
<input name="detail_url" type="hidden" value="<?php echo $detail_url; ?>"/>
<input name="freight_payer" type="hidden" value="<?php echo $freight_payer; ?>"/>
<input name="nick" type="hidden" value="<?php echo $nick; ?>"/>
<input name="price" type="hidden" value="<?php echo $price; ?>"/>
<input name="num" type="hidden" value="<?php echo $num; ?>"/>
<input name="pic_url" type="hidden" value="<?php echo $pic_url; ?>"/>
<input name="dopost" type="hidden" value="create"/>
<button class="f-submit" name="dosubmit" type="submit">提交审核</button> <div style="color: orange; margin-top:20px;font-size: 20px;">
<?php echo $createMessage; ?>
</div>
</div>
</form>
</div>
<!-- /报名表单 -->
</div>
</div>
<div class="xf-sub">
<!-- 公告 -->
<div class="xf-box">
<div class="notice">
<h2>报名公告</h2>
<div class="cnt">
<?php echo block(35);?>
</div>
</div>
</div>
<!-- 特价推荐 -->
</div>
</div>
<!-- /两栏布局 -->
</div>
<file_sep>/jae/modules/trade/templates/trade_list.tpl.php
<?php include $this->admin_tpl('head','admin');?>
<form name="myform" action="/admin.php?m=prize&c=prize_set&a=listorder" method="post">
<div class="pad-lr-10">
<div class="table-list">
<table width="100%" cellspacing="0" class="table_form">
<tbody>
<tr class="thead">
<th width="20"><?php echo L('id')?></th>
<th width="100"><?php echo L('user_id')?></th>
<th width="60"><?php echo L('buyer_nick')?></th>
<th width="120"><?php echo L('auction_id')?></th>
<th width="60"><?php echo L('paid_fee')?></th>
<th width="100"><?php echo L('auction_count')?></th>
<th width="80"><?php echo L('auction_title')?></th>
<th width="100"><?php echo L('pub_time')?></th>
<th width="100"><?php echo L('pub_app_key')?></th>
<th width="100"><?php echo L('topic')?> </th>
</tr>
<?php foreach ($data as $v){?>
<tr>
<td align="center"><?php echo $v['id'];?></td>
<td align="center"><?php echo $v['user_id']?></td>
<td ><?php echo $v['buyer_nick']?></td>
<td ><?php echo $v['auction_id']?></td>
<td ><?php echo $v['paid_fee']?></td>
<td ><?php echo $v['auction_count']?></td>
<td ><a target="_blank" href="http://item.taobao.com/item.htm?id=<?php echo $v['auction_id']?>"><?php echo $v['auction_title']?></a></td>
<td ><?php echo date('Y-m-d H:i:s',$v['pub_time'])?></td>
<td ><?php echo $v['pub_app_key']?></td>
<td ><?php echo $v['topic']?></td>
</tr>
<?php }?>
</tbody>
</table>
<div class="btns">
<input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>" />
</div>
</div>
</div>
</div>
</form>
<div class="pages"><?php echo $pages;?></div>
<?php include $this->admin_tpl('foot','admin');?>
<file_sep>/caches/caches_template/default/order/order_list.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head');?>
<link rel="stylesheet" href="/statics/css/order.css" />
<div class="blank"></div>
<div class="wrap">
<dl class="ui-tab clearfix" id="">
<dt>我的订单</dt>
<!-- <dd data-type="all" class="j_nativeHistory all <?php if($receive==0) echo "select"?> " data-template=""><a href="/index.php?m=point&c=index&a=receive_point&receive=0">未领取的宝贝</a></dd>
<dd data-type="income" class="j_nativeHistory income <?php if($receive==1) echo "select"?>" data-template="/point/detail/income"><a href="/index.php?m=point&c=index&a=receive_point&receive=1 ">已经领取的宝贝</a></dd> -->
<!-- <dd data-type="used" class="j_nativeHistory used <?php if($trad=='used') echo "select"?>" data-template="/point/detail/used"><a href="/index.php?m=point&c=index&a=sign&trad=used">积分支出</a></dd> -->
<!-- <dd data-type="expired" class="j_nativeHistory expired" data-template="/point/detail/expired"><a href="/index.php?m=point&c=index&a=point_task" target="_blank">积分任务说明</a></dd> -->
<!-- <dd data-type="freezed" class="j_nativeHistory freezed" data-template="/point/detail/freezed">冻结积分</dd>-->
</dl>
<div class="border">
<div class="pd20">
<div class="content">
<!-- point .summary END -->
<div class="detail">
<div class="masthead clearfix"><span class="why">消费项目</span><span class="what">消费积分</span><span class="when" style="width:150px;">日期</span><span class="what">物流</span><span style="width:130px;" class="notes">状态</span><span class="notes" style="width:120px;">订单类型</span></div>
<div id="J_pointDetail">
<ul class="item-list" id="J_item-list">
<?php foreach ($data as $v){?>
<li class="item clearfix">
<div class="why"><a class="img" href="<?php echo $v['url']?>" target="_blank"><img src="<?php echo $v['picture']?>" width="60" height="60" alt="<?php echo $v['title']?>"></a><a class="title" href="<?php echo $v['url']?>" target="_blank"><?php echo $v['title']?></a><span class="order-number">编号:<?php echo $v['id']?></span></div>
<div class="what"><span class=" plus"><?php echo $v['point'] ?></span></div>
<div class="when" style="width:150px;"><?php echo date('Y-m-d H:i:s',$v['date'])?></div>
<div class="notes" style="width:200px;">快递名称: <?php echo $v['express_name']?> <br>快递单号:<?php echo $v['express_num']?> </div>
<div class="notes" style="width:150px;"><span class="<?php if($v['status']==6) echo "btn_receive"; else echo "btn_received" ; ?>"><a href="<?php if($v['status']==6) echo "/index.php?m=order&c=index&a=receive&id=".$v['id']; else echo "" ; ?>"><?php echo $order_follow[$v['status']+2]; ?></a></span></div>
<div class="notes" style="width:120px; text-align:center"><?php echo $modules[$v['module']]?></div>
</li>
<?php }?>
</ul>
</div>
<div id="J_pointError" class="hidden error"></div>
<div id="J_pointPager" class="pages">
<?php echo $pages;?>
</div>
</div>
<!-- point .detail END --></div>
<div class="blank"></div>
<div class="m_main"> </div>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<div class="blank"></div>
<link rel="stylesheet" href="/statics/css/order.css" />
<div class="blank"></div>
<div class="wrap">
<?php foreach ($data as $k => $v) {
?>
<div >
<table class="order_list">
<tr class="thead">
<td> 产品</td>
<td>标题</td>
<td>单价</td>
<td>数量</td>
<td>消耗积分</td>
<td width="100">快递名称 </td>
<td width="100">快递单号 </td>
<th width="100">时间 </th>
</tr>
<tr>
<td><img width="80" height="80" src="<?php echo $v['picture']?>"></td>
<td><?php echo $v['title']?></td>
<td><?php echo $v['price']?></td>
<td><?php echo $v['num']?></td>
<td><?php echo $v['point']?></td>
<td align="center" ><?php echo $v['express_name']?></td>
<td align="center" ><?php echo $v['express_num']?></td>
<th width="100">时间 </th>
</tr>
</table>
</div>
<?php }?>
<div class="clear"></div>
</div><file_sep>/caches/caches_template/default/point/invite.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php
include template('content','head');
?>
<link href="/statics/css/invite.css" rel="stylesheet" type="text/css" />
<div class="page_content">
<div class="invite_content">
<div class="invite_copy">
<h2>将以下内容复制分享给您的好友,快来邀请您的好友成为会员,每成功邀请一位会员您将得到<?php echo $data['point']?>积分!</h2>
<textarea><?php echo $data['content_url']."\r\n".$siteinfo['domain']."index.php?fromuserid=".$memberinfo['userid'] ; ?></textarea>
</div></div>
</div>
<!--
<div class="page_main">
<div class="add_point"><h1>赚积分</h1><div class="add_sort"><ul><li>签到</li><li>签到</li><li>签到</li><li>签到</li><li>签到</li><li>签到</li></ul></div></div>
<div class="minus_point"><h1>花积分</h1><div class="minus_sort"><ul><li>签到</li><li>签到</li><li>签到</li></ul></div></div>
<div class="sort1">
<div class="txt fl"></div><div class="img style="display:block"fr" ></div>
</div>
</div>
-->
<div style=" position:relative; width:1190px; height:4500px; margin:0 auto; " >
<div style="width:1920px; height:2000px; position:absolute; left:-365px;"><img style="display:block" src="http://img02.taobaocdn.com/imgextra/i2/1089118323/TB257fxXVXXXXbNXXXXXXXXXXXX-1089118323.jpg" alt=" 小伙伴大召集2_02"/>
<a href="/index.php?m=point&c=index&a=sign" target="_blank"><img style="display:block"src="http://img04.taobaocdn.com/imgextra/i4/1089118323/TB2YAfxXVXXXXaYXXXXXXXXXXXX-1089118323.jpg" border="0"/></a>
<a href="/index.php?m=member&c=index&a=setinfo"><img style="display:block"src="http://img02.taobaocdn.com/imgextra/i2/1089118323/TB2EkfxXVXXXXakXpXXXXXXXXXX-1089118323.jpg" border="0"/></a>
<a href="/index.php?m=prize&c=index&a=init"><img style="display:block"src="http://img02.taobaocdn.com/imgextra/i2/1089118323/TB2f7jxXVXXXXXCXXXXXXXXXXXX-1089118323.jpg" border="0"/></a>
<a href="/index.php?m=content&c=index&a=lists&catid=1"><img style="display:block"src="http://img02.taobaocdn.com/imgextra/i2/1089118323/TB2rQnxXVXXXXcvXXXXXXXXXXXX-1089118323.jpg" border="0"/></a>
<a href="/index.php?m=point&c=index&a=point_invite"><img style="display:block"src="http://img04.taobaocdn.com/imgextra/i4/1089118323/TB21QfxXVXXXXcQXXXXXXXXXXXX-1089118323.jpg" border="0"/></a>
<a href="/"><img style="display:block"src="http://img03.taobaocdn.com/imgextra/i3/1089118323/TB2AkfxXVXXXXb7XXXXXXXXXXXX-1089118323.jpg" border="0"/></a>
<a href="/index.php?m=prize&c=index&a=init"><img style="display:block"src="http://img04.taobaocdn.com/imgextra/i4/1089118323/TB2akjxXVXXXXX1XXXXXXXXXXXX-1089118323.jpg" border="0"/></a>
<a href="/index.php?m=exchange&c=index&a=init"><img style="display:block"src="http://img04.taobaocdn.com/imgextra/i4/1089118323/TB2NQfxXVXXXXbWXXXXXXXXXXXX-1089118323.jpg" border="0"/></a>
<a href="/index.php?m=seckill&c=index&a=init"><img style="display:block"src="http://img02.taobaocdn.com/imgextra/i2/1089118323/TB2W7fxXVXXXXbqXXXXXXXXXXXX-1089118323.jpg" border="0"/></a></div></div><file_sep>/jae/modules/visualization/block.php
<?php
defined('IN_JAE') or exit('No permission resources.');defined('IN_ADMIN') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
class block extends admin {
function __construct() {
parent::__construct();
$this->block_db = jae_base::load_model('block_model');
$this->weblink_db = jae_base::load_model('weblink_model');
$this->position = jae_base::load_model('position_data_model');
$this->menuid=14;
}
function init() {
$siteid=get_siteid();
if(isset($_POST['dosubmit'])) {
$id = intval($_POST['id']);
$data=$_POST['info'];
$_POST['info']['data']=htmlspecialchars($_POST['info']['data']);
$this->db->update($data,$this->table,'id='.$id);
showmessage(L('operation_success'));
include $this->admin_tpl('block_edit');
} else {
$id = intval($_GET['id']);
$pos =$_GET['pos'];
$r=$this->block_db->get_one(" `id`= '$id' or `pos`='$pos' and `siteid`='$siteid' ");
if($r) extract($r);
include $this->admin_tpl('block_edit','block');
}
}
function listorder() {
if(isset($_POST['dosubmit'])) {
foreach($_POST['listorders'] as $id => $listorder) {
$listorder = !empty($listorder) ? $listorder : '0';
$this->db->update(array('listorder'=>$listorder),$this->table,'id='.$id);
$status = isset($_POST["status"][$id]) ? $_POST["status"][$id] : '0';
$this->db->update(array('status'=>$status),$this->table,'id='.$id);
}
showmessage(L('operation_success'));
} else {
showmessage(L('operation_failure'));
}
}
}
?><file_sep>/jae/modules/template/templates/file_edit_file.tpl.php
<?php
defined('IN_ADMIN') or exit('No permission resources.');
include $this->admin_tpl('head', 'admin');
?>
<tr>
<td align="left" colspan="3"><?php echo L("local_dir")?>£º<?php echo $local?></td>
</tr>
<?php if ($dir !='' && $dir != '.'):?>
<tr>
<td align="left" colspan="3"><a href="<?php echo '/admin.php?m=template&c=file&a=init&style='.$this->style.'&dir='.$dir ?>"><img src="/statics/images/folder-closed.gif" /><?php echo L("parent_directory")?></a></td>
</tr>
<?php endif;?>
<div class="pad-10" style="padding-bottom:0px">
<!--<div class="col-right">
<h3 class="f14"><?php echo L('common_variables')?></h3>
<input type="button" class="button pt" onClick="javascript:insertText('{CSS_PATH}')" value="{CSS_PATH}" title="<?php echo L('click_into')?>"/><br />
<input type="button" class="button pt" onClick="javascript:insertText('{JS_PATH}')" value="{JS_PATH}" title="<?php echo L('click_into')?>"/><br />
<input type="button" class="button pt" onClick="javascript:insertText('{IMG_PATH}')" value="{IMG_PATH}" title="<?php echo L('click_into')?>"/><br />
<input type="button" class="button pt" onClick="javascript:insertText('{APP_PATH}')" value="{APP_PATH}" title="<?php echo L('click_into')?>"/><br />
<input type="button" class="button pt" onClick="javascript:insertText('{get_siteid()}')" value="{get_siteid()}" title="»ñȡվµãID"/><br />
<input type="button" class="button pt" onClick="javascript:insertText('{loop $data $n $r}')" value="{loop $data $n $r}" title="<?php echo L('click_into')?>"/><br />
<input type="button" class="button pt" onClick="javascript:insertText('{$r[\'url\']}')" value="{$r['url']}" title="<?php echo L('click_into')?>"/><br />
<input type="button" class="button pt" onClick="javascript:insertText('{$r[\'title\']}')" value="{$r['title']}" title="<?php echo L('click_into')?>"/><br />
<input type="button" class="button pt" onClick="javascript:insertText('{$r[\'thumb\']}')" value="{$r['thumb']}" title="<?php echo L('click_into')?>"/><br />
<input type="button" class="button pt" onClick="javascript:insertText('{strip_tags($r[description])}')" value="{strip_tags($r[description])}" title="<?php echo L('click_into')?>"/><br />
<?php if (is_array($file_t_v[$file_t])) { foreach($file_t_v[$file_t] as $k => $v) {?>
<input type="button" class="button pt" onClick="javascript:insertText('<?php echo $k?>')" value="<?php echo $k?>" title="<?php echo $v ? $v :L('click_into')?>"/><br />
<?php } }?>
</div>-->
<div class="col-auto">
<form action="/admin.php?m=template&c=file&a=edit_file&style=<?php echo $this->style?>&dir=<?php echo $dir?>&file=<?php echo $file?>" method="post" name="myform" id="myform">
<textarea name="code" id="code" style="height: 280px;width:96%; visibility:inherit"><?php echo $data?></textarea>
<div class="bk10"></div>
<input type="submit" id="dosubmit" class="button pt" name="dosubmit" value="<?php echo L('submit')?>" />
</form>
</div>
</div>
<?php
include $this->admin_tpl('foot', 'admin');
?><file_sep>/jae/modules/apply/templates/goods_list.tpl.php
<?php include $this->admin_tpl('head','admin');?>
<div class="pad-lr-10">
<form name="searchform" action="" method="get" accept-charset="UTF-8">
<input type="hidden" name="m" value="apply">
<input type="hidden" name="c" value="goods">
<input type="hidden" name="a" value="search">
<input type="hidden" name="dopost" value="search">
<input type="hidden" value="<?php echo $this->menuid;?>" name="menuid">
<table width="100%" cellspacing="0" class="search-form">
<tbody>
<tr>
<td><div class="explain-col">
分类: <select name="searchCategoryId">
<option<?php if(intval($searchCategoryId)==-1){?> selected="selected"<?php }?> value="-1">全部</option>
<?php
foreach ($categoryArr as $catid => $name)
{
?>
<option <?php if ($searchCategoryId == $catid)
{
?>selected="selected" <?php }; ?>value="<?php echo $catid; ?>"><?php echo $name; ?></option>
<?php }; ?>
<option <?php if(intval($searchCategoryId)==0){?> selected="selected"<?php }?> value="0">无分类</option>
</select>
推荐位: <select name="searchPromoteId[<?php echo $row['id']?>]">
<option<?php if(intval($searchPromoteId)==-1){?> selected="selected"<?php }?> value="-1">全部</option>
<?php foreach($promotePositionArr as $promoteId=>$promoteName){; ?>
<option<?php if( $promoteId==$searchPromoteId){; ?> selected="selected"<?php }; ?> value="<?php echo $promoteId?>"> <?php echo $promoteName; ?></option>
<?php }; ?>
<option <?php if(intval($searchPromoteId)==0){?> selected="selected"<?php }?> value="0">无推荐位</option>
</select>
频道: <select name="searchPindaoId[<?php echo $row['id']?>]">
<option<?php if(intval($searchPindaoId)==-1){?> selected="selected"<?php }?> value="-1">全部</option>
<?php foreach($pindaoArr as $pindaoId=>$pindaoName){; ?>
<option <?php if( $pindaoId==$searchPindaoId){; ?> selected="selected"<?php }; ?> value="<?php echo $pindaoId?>"> <?php echo $pindaoName; ?></option>
<?php }; ?>
<option <?php if(intval($searchPindaoId)==0){?> selected="selected"<?php }?> value="0">无频道</option>
</select>
关键字查询:
<input class="input-text" type="text" name="searchWord" value="<?php echo $searchWord ?>">
<input type="submit" name="search" class="button" value="查询"> (商品名称、NUMID、用户昵称)
</div></td>
</tr>
</tbody>
</table>
<input name="pc_hash" type="hidden" value="4ua2L3">
</form>
</div>
<form name="myform" action="/admin.php?m=apply&c=goods&a=delete" method="post">
<div class="pad-lr-10">
<div class="table-list">
<table width="100%" cellspacing="0" class="table_form">
<tbody>
<tr class="thead">
<th width="40" ><input type="checkbox" value="" id="check_box" onclick="selectall('ids[]');"></th>
<th width="40" >id</th>
<th width="100" >商品图片</th>
<th >商品名称</th>
<th >昵称</th>
<th width="10%" >商品价格</th>
<th width="10%" >状态</th>
<th width="200" align="center"><?php echo L('operations_manage');?></th>
</tr>
<?php foreach ($data as $r){?>
<tr>
<td align="center"><input type="checkbox" name="ids[]" value="<?php echo $r['id']; ?>" ></td>
<td align="center"><?php echo $r['id'];?></td>
<td align="center"><a target="_blank" href="<?php echo $r['detail_url']?>"><img src="<?php echo $r['pic_url'];?>" height="40"></a></td>
<td><a target="_blank" href="<?php echo $r['detail_url']?>"><?php echo $r['title'];?></a></td>
<td><a target="_blank" href="<?php echo $r['detail_url']?>"><?php echo $r['nick'];?></a></td>
<td align="center">原价:<?php echo $r['price']; ?><br>
现价:<?php echo $r['coupon_price']; ?></td>
<td align="center"><?php if( $r['status']==0) echo "未审核" ; if( $r['status']==-1) echo "被拒绝" ; if( $r['status']==1) echo "审核通过" ;?></td>
<td align="center"><?php echo '<a href="/admin.php?m=apply&c=goods&a=pass&id='.$r['id'].'&menuid='.$menuid.'">通过</a> |<a href="/admin.php?m=apply&c=goods&a=edit&id='.$r['id'].'&menuid='.$menuid.'">拒绝</a> | <a href="/admin.php?m=apply&c=goods&a=delete&id='.$r['id'].'&menuid='.$menuid.'">'.L('delete').'</a> ';?></td>
</tr>
<?php }?>
</tbody>
</table>
<div class="btns"><input type="submit" class="button" name="dosubmit" value="<?php echo L('delete')?>" /></div> </div>
</div>
</div>
</form>
<div class="pages"><?php echo $pages;?></div>
<?php include $this->admin_tpl('foot','admin');?><file_sep>/caches/caches_template/neimeng/content/mall.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head2');?>
<link rel="stylesheet" href="/statics/css/lows.css" />
<div class="lows-banner J_TWidget" style="display:none" id="J_LowsBanner" data-widget-type="Carousel" data-widget-config="{'navCls':'ks-switchable-nav','contentCls':'ks-switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'active','autoplay':'true','interval':3,'prevBtnCls': 'prev', 'nextBtnCls': 'next', 'disableBtnCls': 'disable' }">
<div class="trigger-wrap">
<span class="close J_LowsClose"></span>
<span class="prev"></span>
<span class="next"></span>
<ol class="lows-trigger ks-switchable-nav">
<li class="ks-switchable-trigger-internal297 active"></li>
<li class="ks-switchable-trigger-internal297 "></li>
<li class="ks-switchable-trigger-internal297"></li>
</ol>
</div>
<ul class="ks-switchable-content clear-fix">
<li class="pic1 ks-switchable-panel-internal298" style="display: block; opacity: 0; position: absolute; z-index: 1; "><div class="banner-pic" style="background: url(http://img03.taobaocdn.com/imgextra/i3/1863579612/TB2_FMOXVXXXXX7XpXXXXXXXXXX-1863579612.png) no-repeat 0 0;"></div></li>
<li class="pic2 ks-switchable-panel-internal298" style="display: block; opacity: 1; position: absolute; z-index: 9; "><div class="banner-pic" style="background: url(http://img04.taobaocdn.com/imgextra/i4/1863579612/TB2VhgOXVXXXXbaXXXXXXXXXXXX-1863579612.png) no-repeat 0 0;"></div></li>
<li class="pic3 ks-switchable-panel-internal298" style="display: block; opacity: 0; position: absolute; z-index: 1; "><div class="banner-pic" style="background: url(http://img02.taobaocdn.com/imgextra/i2/1863579612/TB2G4ZOXVXXXXXGXXXXXXXXXXXX-1863579612.png) no-repeat 0 0;"></div></li>
</ul>
</div>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=c48e16dbd8278d8301abbc5c84a59774&action=lists&id=185&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=c48e16dbd8278d8301abbc5c84a59774&action=lists&id=185&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'185','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<div class="body_w" style="background-image:url(<?php echo $r['picture'];?>);background-repeat: repeat;">
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<!--首焦-->
<div class="wrap" style="height:420px; position:relative;">
<div class="root61" style="z-index:22">
<div class=" smCategorys">
<div class="sm-c-wrap">
<div class="menu switchable-nav">
<div class="item fore1">
<i class="i1"></i>
<span class="blank"></span>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=fbfd1bf4a40dbeac9ac0541dc24484f6&action=lists&typeid=10&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=fbfd1bf4a40dbeac9ac0541dc24484f6&action=lists&typeid=10&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'10','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<h3><a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a></h3>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<div class="ext">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=659bfc50112d9edffb3f5716f62311d9&action=lists&typeid=10&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=659bfc50112d9edffb3f5716f62311d9&action=lists&typeid=10&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'10','order'=>'listorder ASC','limit'=>'20',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?><?php if($n>1) { ?>
<a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a>
<?php } ?>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
<div class="item fore2">
<i class="i2"></i>
<span class="blank"></span>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=ea0a9866571de93d8ad19c9250246eec&action=lists&typeid=16&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=ea0a9866571de93d8ad19c9250246eec&action=lists&typeid=16&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'16','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<h3><a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a></h3>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<div class="ext">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=10afa1e3dd018f0207be14f349ae285c&action=lists&typeid=16&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=10afa1e3dd018f0207be14f349ae285c&action=lists&typeid=16&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'16','order'=>'listorder ASC','limit'=>'20',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?><?php if($n>1) { ?>
<a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a>
<?php } ?>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
<div class="item fore3">
<i class="i3"></i>
<span class="blank"></span>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=0d04e7787a9a3af53f5c85854f01db9b&action=lists&typeid=17&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=0d04e7787a9a3af53f5c85854f01db9b&action=lists&typeid=17&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'17','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<h3><a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a></h3>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<div class="ext">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=dc6f3f04b7c0bf5f710b33211db949a2&action=lists&typeid=17&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=dc6f3f04b7c0bf5f710b33211db949a2&action=lists&typeid=17&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'17','order'=>'listorder ASC','limit'=>'20',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?><?php if($n>1) { ?>
<a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a>
<?php } ?>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
<div class="item fore4">
<i class="i4"></i>
<span class="blank"></span>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=1ef57e5654162d5aead24c6937597b6c&action=lists&typeid=18&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=1ef57e5654162d5aead24c6937597b6c&action=lists&typeid=18&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'18','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<h3><a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a></h3>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<div class="ext">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=86b75660d3e42ee4e29123012301db19&action=lists&typeid=18&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=86b75660d3e42ee4e29123012301db19&action=lists&typeid=18&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'18','order'=>'listorder ASC','limit'=>'20',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?><?php if($n>1) { ?>
<a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a>
<?php } ?>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
<div class="item fore5">
<i class="i5"></i>
<span class="blank"></span>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=dd282ce42fde959e6a44cda1e470685e&action=lists&typeid=19&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=dd282ce42fde959e6a44cda1e470685e&action=lists&typeid=19&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'19','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<h3><a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a></h3>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<div class="ext">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=158246be5f5778db2fd5132944aca82a&action=lists&typeid=19&order=listorder+ASC+&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=158246be5f5778db2fd5132944aca82a&action=lists&typeid=19&order=listorder+ASC+&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'19','order'=>'listorder ASC ','limit'=>'20',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?><?php if($n>1) { ?>
<a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a>
<?php } ?>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--shoujiao-->
<div class="sjjz">
<div class="qpsj ">
<div class="focus J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'tab-nav','contentCls':'tab-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [1920], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<div class="prev"></div><div class="next"></div>
<div class="tab-content">
<?php $sql="SELECT * FROM jae_focus WHERE status=1 ORDER BY listorder ASC ";
$r_focus=query($sql); foreach ($r_focus as $r) {?>
<div><a href="<?php echo $r["link"]?>" target="_blank"> <img src="http://img02.taobaocdn.com/imgextra/i2/1863579612/TB22rNyapXXXXbpXXXXXXXXXXXX_!!1863579612.jpg" height="400"/></a></div>
<?php }?>
</div>
<div class="tab-nav">
<?php $r_focuss=query($sql); foreach ($r_focuss as $k=>$rs) {?>
<div class="v<?php echo $k?>"></div>
<?php }?>
</div>
</div>
</div>
</div>
<!--shoujia end-->
<div class="wrap">
<div class="fl" style="margin-right:5px;">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=c6fd7403822181b7450aa0463594257b&action=lists&id=170&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=c6fd7403822181b7450aa0463594257b&action=lists&id=170&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'170','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a href="<?php echo $r['link'];?>" target="_blank"><img src="<?php echo $r['picture'];?>" /></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="fl">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=a5257e2deba1329b6d9f53dabda02949&action=lists&id=171&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=a5257e2deba1329b6d9f53dabda02949&action=lists&id=171&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'171','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a href="<?php echo $r['link'];?>" target="_blank"><img src="<?php echo $r['picture'];?>" /></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="fr">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=b6b19278882c73e9be2ab6d026b3a3b8&action=lists&id=172&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=b6b19278882c73e9be2ab6d026b3a3b8&action=lists&id=172&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'172','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a href="<?php echo $r['link'];?>" target="_blank"><img src="<?php echo $r['picture'];?>" /></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div>
<div class="blank"></div>
<!--秒杀-->
<div class="wrap">
<div class="sec">
<a href="http://neimenggu.china.taobao.com/index.php?spm=a216r.7173997.1.15.cSK9Dn&m=seckill&c=index&a=init" target="_blank">
<?php $hour=Date('Hs',SYS_TIME); ?>
<div class="time <?php if (800<$hour && $hour<=1000 ){ echo "current";}?> ">
<span><?php if (800<$hour && $hour<=1000 ){ echo "秒杀开始";}else { echo "秒杀结束"} ?></span>
<i>10:00</i>
</div>
<div class="time <?php if (1000<$hour && $hour<=1200 ){ echo "current";}?> ">
<span><?php if (1000<$hour && $hour<=1200 ){ echo "秒杀开始";}else { echo "秒杀结束"} ?></span>
<i>12:00</i>
</div>
<div class="time <?php if (1200<$hour && $hour<=1500 ){ echo "current";}?> ">
<span><?php if (1200<$hour && $hour<=1500 ){ echo "秒杀开始";}else { echo "秒杀结束"} ?></span>
<i>15:00</i>
</div>
<div class="time <?php if ( 1500 <$hour && $hour <= 1700 ) echo 'current';?>">
<span><?php if (1500<$hour && $hour<=1700 ){ echo "秒杀开始";}else { echo "秒杀结束"} ?></span>
<i>17:00</i>
</div>
<div class="time <?php if (1700<$hour && $hour<=2000 ){ echo "current";}?> ">
<span><?php if (1700<$hour && $hour<=2000 ){ echo "秒杀开始";}else { echo "秒杀结束"} ?></span>
<i>20:00</i>
</div>
<div class="time <?php if (2000<$hour && $hour<=2200 ){ echo "current";}?> ">
<span><?php if (2000<$hour && $hour<=2200 ){ echo "秒杀开始";}else { echo "秒杀结束"} ?></span>
<i>22:00</i>
</div>
</a>
</div>
</div>
<!--秒杀-->
<!--优质推荐-->
<div style="height:10px;"></div>
<div class="wrap">
<div class="youzhi J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'tab-nav','contentCls':'tab-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [620], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<div class="title">
<div class="swap tab-nav"><span>鲜米杂粮</span><span>佐餐调味</span></div>
</div>
<div class="con tab-content">
<div class="list ">
<ul>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=2b02159bb28edd0104d260bb3efca791&action=position&posid=7&order=listorder+asc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=2b02159bb28edd0104d260bb3efca791&action=position&posid=7&order=listorder+asc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'7','order'=>'listorder asc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li> <a href="<?php echo $r['url'];?>" target="_blank"><img height="280" src="<?php echo $r['thumb'];?>" width="280" /><br />
<div class="txt"><?php echo $r['title'];?></div>
<div class="sj"><span class="jg">¥<?php echo round($r['coupon_price']);?></span><span class="yj">原价:¥<?php echo $r['price'];?></span></div><span class="gm"></span></a></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div><div class="list ">
<ul>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=e5e2af994e7cae08630ea50d678a4f10&action=position&posid=8&order=listorder+asc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=e5e2af994e7cae08630ea50d678a4f10&action=position&posid=8&order=listorder+asc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'8','order'=>'listorder asc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li> <a href="<?php echo $r['url'];?>" target="_blank"><img height="280" src="<?php echo $r['thumb'];?>" width="280" /><br />
<div class="txt"><?php echo $r['title'];?></div>
<div class="sj"><span class="jg">¥<?php echo round($r['coupon_price']);?></span><span class="yj">原价:¥<?php echo $r['price'];?></span></div><span class="gm"></span></a></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
</div>
<div class="bt"></div>
</div>
</div>
<div class="blank"></div>
<!--banner-->
<div class="wrap">
<div class="banad">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=93d7d188e57673d4e25f6c7510b0cc1e&action=lists&id=77&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=93d7d188e57673d4e25f6c7510b0cc1e&action=lists&id=77&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'77','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img width="1210" data-ks-lazyload="<?php echo $r['picture'];?>"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
<div style="height:15px; clear:both;"></div>
<!--banner end-->
<!--九九-->
<div class="wrap">
<div class="jiujiu">
<div class="title">
</div>
<div class="con">
<div class="list">
<ul>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=91f7849d9e8646e70cf35d663f338492&action=position&posid=9&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=91f7849d9e8646e70cf35d663f338492&action=position&posid=9&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'9','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li> <a href="<?php echo $r['url'];?>" target="_blank"><img height="280" src="<?php echo $r['thumb'];?>" width="280" /><br />
<div class="txt"><?php echo $r['title'];?></div>
<div class="sj"><span class="jg">¥<?php echo round($r['coupon_price'],1);?></span><span class="yj">原价:¥<?php echo $r['price'];?></span></div><span class="gm"></span></a></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<div class="clear"></div>
</div>
</div>
</div>
</div>
<div class="blank"></div>
<!--探寻内蒙古-->
<div class="wrap">
<div class="tanxun J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'tab-nav','contentCls':'tab-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [620], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<div class=" tab-content">
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=6431b1a4a2166b549c439013781b6af6&action=position&posid=36&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=6431b1a4a2166b549c439013781b6af6&action=position&posid=36&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'36','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=094e03babad955c1ef915ca0e9f485d0&action=position&posid=39&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=094e03babad955c1ef915ca0e9f485d0&action=position&posid=39&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'39','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=d483e9ea7232e29bae8cc203d5bff399&action=position&posid=34&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=d483e9ea7232e29bae8cc203d5bff399&action=position&posid=34&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'34','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=073531f232d4422c9c98ac3d40ad74b1&action=position&posid=33&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=073531f232d4422c9c98ac3d40ad74b1&action=position&posid=33&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'33','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=2ae1328f25d47e6b1750f107e99166c7&action=position&posid=40&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=2ae1328f25d47e6b1750f107e99166c7&action=position&posid=40&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'40','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=949410eafa76184755a73bfab8dfafaa&action=position&posid=38&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=949410eafa76184755a73bfab8dfafaa&action=position&posid=38&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'38','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=d02a77157cfc744e5375bf71a04b9e26&action=position&posid=31&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=d02a77157cfc744e5375bf71a04b9e26&action=position&posid=31&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'31','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=5b66ab823663ecf901e4a14dce2093b0&action=position&posid=30&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=5b66ab823663ecf901e4a14dce2093b0&action=position&posid=30&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'30','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=873041e2efd3092ec97e9cc627217d99&action=position&posid=37&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=873041e2efd3092ec97e9cc627217d99&action=position&posid=37&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'37','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=cad2ac420fb795128582ffabfcf035d2&action=position&posid=35&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=cad2ac420fb795128582ffabfcf035d2&action=position&posid=35&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'35','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=e615377c9e7687c449134b7fe8a3d22b&action=position&posid=32&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=e615377c9e7687c449134b7fe8a3d22b&action=position&posid=32&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'32','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=a4c1d4dde0d937de6da3f85d7ef643ab&action=position&posid=41&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=a4c1d4dde0d937de6da3f85d7ef643ab&action=position&posid=41&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'41','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
<div class="ditu tab-nav">
<div class="qu1">
<span></span>
呼伦贝尔市
</div>
<div class="qu2">
<span></span>
兴安盟
</div>
<div class="qu3"><span></span>
通辽市
</div>
<div class="qu4"><span></span>
赤峰市
</div>
<div class="qu5"><span></span>
锡林郭勒盟
</div>
<div class="qu6"><span></span>
乌兰察布市
</div>
<div class="qu7"><span></span>
包头市
</div>
<div class="qu8"><span></span>
呼和浩特市
</div>
<div class="qu9"><span></span>
巴颜淖尔市
</div>
<div class="qu10"><span></span>
鄂尔多斯市
</div>
<div class="qu11"><span></span>
乌海市
</div>
<div class="qu12"><span></span>
阿拉善盟
</div>
</div>
</div>
</div>
<!--9.9包邮 -->
<div class="blank"></div>
<!-- 特色品类 -->
<div class="wrap">
<div class="pinlei">
<div class="li3">
<div class="li3_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=02d755253663379ad470bf8c8f731227&action=lists&id=106&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=02d755253663379ad470bf8c8f731227&action=lists&id=106&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'106','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $r['picture'];?>"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="li3_t">
<div class="tit"><span class="t">天山百果</span><span class="des">新鲜上市 产地直供</span></div>
<div><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=f74965672ad7f6e613f42e1e62ccc2e2&pos=shuiguo-1\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=f74965672ad7f6e613f42e1e62ccc2e2&pos=shuiguo-1\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'shuiguo-1',));?><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=4fff7339c868e3d264aaf57bcfc407c4&action=lists&id=107&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=4fff7339c868e3d264aaf57bcfc407c4&action=lists&id=107&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'107','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $r['picture'];?>"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="li3_t"><div class="tit"><span class="t">丝路养生</span><span class="des">滋补养生 颐养生命</span></div>
<div><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=a09d1893058b68f1b2bc46d6e023f139&pos=shuiguo-2\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=a09d1893058b68f1b2bc46d6e023f139&pos=shuiguo-2\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'shuiguo-2',));?><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=dd0430593b77d68bdcd48675f650c485&action=lists&id=108&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=dd0430593b77d68bdcd48675f650c485&action=lists&id=108&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'108','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $r['picture'];?>"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="li3_t"><div class="tit"><span class="t">特色小吃</span><span class="des">前年的发展 亮丽的风景线</span></div>
<div><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=0a17d08d4d5bdbac77bdbdf6dea66dff&pos=shuiguo-3\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=0a17d08d4d5bdbac77bdbdf6dea66dff&pos=shuiguo-3\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'shuiguo-3',));?><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=8f758e9d453fd239fc3e1f9c6b6f8570&action=lists&id=109&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=8f758e9d453fd239fc3e1f9c6b6f8570&action=lists&id=109&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'109','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $r['picture'];?>"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="li3_t"><div class="tit"><span class="t">特色工艺</span><span class="des">人们世代智慧的传承</span></div>
<div><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=6126a69ec49be8ff20ecd3943e0494dd&pos=shuiguo-4\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=6126a69ec49be8ff20ecd3943e0494dd&pos=shuiguo-4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'shuiguo-4',));?><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?> </div>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<div class="blank"></div>
<!--1楼-->
<div class="wrap">
<div class="louceng J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'tab-nav2','contentCls':'tab-content2','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [620], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<div class="title" style="background:url(http://img02.taobaocdn.com/imgextra/i2/1863579612/TB2_Dg9aXXXXXamXXXXXXXXXXXX_!!1863579612.png) no-repeat"> <div class="swap tab-nav2"><span class="on">美味零食</span><span>传统奶茶</span><span>牧场鲜奶</span></div> </div>
<div class="tab-content2">
<div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=0dfa6ba0b36e35c180b125ff568b4be7&action=lists&id=173&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=0dfa6ba0b36e35c180b125ff568b4be7&action=lists&id=173&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'173','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=8e3b64c070c9dd850bdcd286a79eb8ca&action=position&posid=10&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=8e3b64c070c9dd850bdcd286a79eb8ca&action=position&posid=10&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'10','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">促销价¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div>
<div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=b7248d155311004362a0b3262c6fa108&action=lists&id=174&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=b7248d155311004362a0b3262c6fa108&action=lists&id=174&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'174','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=37ce7cd0a40b0e3d392bda8c876e6587&action=position&posid=14&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=37ce7cd0a40b0e3d392bda8c876e6587&action=position&posid=14&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'14','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">促销价¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div>
<div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=a5232a251d157ee55fc9b4aff3603316&action=lists&id=175&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=a5232a251d157ee55fc9b4aff3603316&action=lists&id=175&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'175','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=0f176ee658b82a579fea4bac2ffc5f07&action=position&posid=15&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=0f176ee658b82a579fea4bac2ffc5f07&action=position&posid=15&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'15','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">促销价¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</div>
<div class="blank"></div>
<!--2楼-->
<div class="wrap">
<div class="louceng J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'tab-nav2','contentCls':'tab-content2','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [620], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<div class="title" style="background:url(http://img04.taobaocdn.com/imgextra/i4/1863579612/TB2I_s5aXXXXXX4XpXXXXXXXXXX_!!1863579612.png) no-repeat"> <div class="swap tab-nav2"><span class="on">风干牛肉</span><span>草原全羊</span><span>经典小食</span></div> </div>
<div class="tab-content2">
<div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=a2d78784c7a4e2df9a6f26bb41ef870c&action=lists&id=176&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=a2d78784c7a4e2df9a6f26bb41ef870c&action=lists&id=176&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'176','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=068d2c82aecdf8fe1c946c7455357593&action=position&posid=16&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=068d2c82aecdf8fe1c946c7455357593&action=position&posid=16&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'16','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">促销价¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div><div class="cons ">
<div class="l_img"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=80ecb6c19e3ea8cbd912056a91a02c08&action=lists&id=177&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=80ecb6c19e3ea8cbd912056a91a02c08&action=lists&id=177&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'177','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=547b5561f7a200b33b6bce83b6603842&action=position&posid=17&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=547b5561f7a200b33b6bce83b6603842&action=position&posid=17&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'17','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">促销价¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div><div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=674bffd22e123c3a7d966da23bd127df&action=lists&id=178&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=674bffd22e123c3a7d966da23bd127df&action=lists&id=178&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'178','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=dd29aabfc85582cc71ad80af9956b07b&action=position&posid=18&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=dd29aabfc85582cc71ad80af9956b07b&action=position&posid=18&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'18','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">促销价¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</div>
<div class="blank"></div>
<!--3楼-->
<div class="wrap">
<div class="louceng J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'tab-nav2','contentCls':'tab-content2','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [620], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<div class="title" style="background:url(http://img01.taobaocdn.com/imgextra/i1/1863579612/TB2QH78aXXXXXbJXXXXXXXXXXXX_!!1863579612.png) no-repeat"> <div class="swap tab-nav2"><span class="on">草原鲜米</span><span>精选杂粮</span><span>佐餐调味</span></div> </div>
<div class="tab-content2">
<div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=d4bbc702264b80783ddface97f287db0&action=lists&id=179&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=d4bbc702264b80783ddface97f287db0&action=lists&id=179&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'179','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=366626f77e5750ad5bc359123d14f417&action=position&posid=20&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=366626f77e5750ad5bc359123d14f417&action=position&posid=20&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'20','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">促销价¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div><div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=86cbb36c63bcd4454d7d764c13a51c80&action=lists&id=180&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=86cbb36c63bcd4454d7d764c13a51c80&action=lists&id=180&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'180','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=7b82308ea73efd075db8a04fe7adc31d&action=position&posid=21&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=7b82308ea73efd075db8a04fe7adc31d&action=position&posid=21&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'21','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">促销价¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div><div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=4677c98674c86e3fab25ebe379ad5062&action=lists&id=181&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=4677c98674c86e3fab25ebe379ad5062&action=lists&id=181&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'181','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=2c5b96184d361dd0ecf8d74f7e304d40&action=position&posid=22&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=2c5b96184d361dd0ecf8d74f7e304d40&action=position&posid=22&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'22','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">促销价¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</div>
<div class="blank"></div>
<!--4楼-->
<div class="wrap">
<div class="louceng J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'tab-nav2','contentCls':'tab-content2','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [620], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<div class="title" style="background:url(http://img04.taobaocdn.com/imgextra/i4/1863579612/TB2tr.9aXXXXXaEXXXXXXXXXXXX_!!1863579612.png) no-repeat"> <div class="swap tab-nav2"><span class="on">蒙古特色</span><span>手工制品</span><span>精品羊绒</span></div> </div>
<div class="tab-content2">
<div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=7c9c0a6f07792ee4bad2f9e81fe22ab7&action=lists&id=182&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=7c9c0a6f07792ee4bad2f9e81fe22ab7&action=lists&id=182&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'182','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=276e731df5ace4902c10ece4d57fda6e&action=position&posid=23&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=276e731df5ace4902c10ece4d57fda6e&action=position&posid=23&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'23','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">促销价¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div><div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=7f0aa5922e4d3e4dc48d4380776d6954&action=lists&id=183&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=7f0aa5922e4d3e4dc48d4380776d6954&action=lists&id=183&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'183','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=ffdf7c2f9735697086b1395e993e2af1&action=position&posid=24&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=ffdf7c2f9735697086b1395e993e2af1&action=position&posid=24&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'24','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">促销价¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div><div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=f99436bc9fb5ca07075c2911bd0cf4c7&action=lists&id=184&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=f99436bc9fb5ca07075c2911bd0cf4c7&action=lists&id=184&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'184','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=0503b8c54e3f8ad87d527f8e749cbfeb&action=position&posid=25&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=0503b8c54e3f8ad87d527f8e749cbfeb&action=position&posid=25&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'25','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">促销价¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</div>
<div class="blank"></div>
<!-- 友链 -->
<div class="wrap">
<div class="jh">
<?php $result=query('SELECT * FROM jae_link WHERE typeid=0 AND listorder!=0 AND passed=1 ORDER BY listorder ASC LIMIT 0,50 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img data-ks-lazyload="<?php echo $v['logo'];?>"></a>
<?php }
?>
</div>
</div>
<!-- 友链 end-->
<div class="blank"></div>
<?php include template('content','foot');?>
</div>
<file_sep>/caches/caches_commons/caches_data/model.cache.php
<?php
return array (
1 =>
array (
'modelid' => '1',
'siteid' => '1',
'name' => '商品模型',
'description' => '',
'tablename' => 'goods',
'setting' => '',
'addtime' => '0',
'items' => '0',
'enablesearch' => '1',
'disabled' => '0',
'default_style' => 'default',
'category_template' => 'category_goods',
'list_template' => 'list_goods',
'show_template' => 'show_goods',
'js_template' => '',
'admin_list_template' => '',
'member_add_template' => '',
'member_list_template' => '',
'sort' => '0',
'type' => '0',
),
2 =>
array (
'modelid' => '2',
'siteid' => '1',
'name' => '店铺模型',
'description' => '',
'tablename' => 'download',
'setting' => '',
'addtime' => '0',
'items' => '0',
'enablesearch' => '1',
'disabled' => '0',
'default_style' => 'default',
'category_template' => 'category_shop',
'list_template' => 'list_shop',
'show_template' => 'show_shop',
'js_template' => '',
'admin_list_template' => '',
'member_add_template' => '',
'member_list_template' => '',
'sort' => '0',
'type' => '0',
),
3 =>
array (
'modelid' => '3',
'siteid' => '1',
'name' => '文章模型',
'description' => '',
'tablename' => 'picture',
'setting' => '',
'addtime' => '0',
'items' => '0',
'enablesearch' => '1',
'disabled' => '0',
'default_style' => 'default',
'category_template' => 'category_article',
'list_template' => 'list_article',
'show_template' => 'show_article',
'js_template' => '',
'admin_list_template' => '',
'member_add_template' => '',
'member_list_template' => '',
'sort' => '0',
'type' => '0',
),
4 =>
array (
'modelid' => '4',
'siteid' => '1',
'name' => '专题模型',
'description' => '',
'tablename' => 'video',
'setting' => '',
'addtime' => '0',
'items' => '0',
'enablesearch' => '1',
'disabled' => '0',
'default_style' => 'default',
'category_template' => 'category_special',
'list_template' => 'list_special',
'show_template' => 'show_special',
'js_template' => '',
'admin_list_template' => '',
'member_add_template' => '',
'member_list_template' => '',
'sort' => '0',
'type' => '0',
),
);
?><file_sep>/caches/caches_commons/caches_data/seckill.cache.php
<?php
return array (
'title' => '积分秒杀',
'bg_color' => '#E8E8E8',
'description' => '积分秒杀',
'enable' => '1',
'img' => '/statics/images/seckill.png',
'rules' => '<p>一、积分兑换商品于12月5日10:00:00开始,活动商品统一为积分兑换商品,具体兑换时间以活动商品页显示为准;</p>
<p>二、活动期间,同一用户对于同一款活动商品仅只有一次兑换机会,同一用户(是指虽然不同账户名称,但账户注册信息中包含但不限于相同的手机号、姓名、收货地址等多个内容一致的信息的,活动期间均应视为“同一用户”)。积分兑换购商品数量有限,兑完即止; </p>
<p>三、活动期间的所有积分兑换商品均包邮,由商家在用户成功拍下商品并积分支付完成后的72小时内完成发货。</p>
<p>四、若因用户填写的联系方式、收货地址等信息有误,导致按用户填写的信息最终无法发放或发放不到的,视同用户自动放弃领取资格,不再补发商品。</p>
<p>五、积分抵扣实物交易款项时,商家有权对积分所对应的金额不开具发票。</p>
<p>六、在获取和使用积分过程中,如果出现任何违法违规行为(包括但不限于商家及/或用户作弊领取、恶意套现、刷取信誉、虚假交易等),天猫及/或聚划算将取消您的获取资格,并有权撤销违规交易,收回积分(含已使用的及未使用的),给天猫及/或聚划算造成损失的应负责赔偿,必要时追究法律责任。</p>
<p>七、如活动受政府机关指令需要停止举办的,或活动遭受严重网络攻击需暂停举办的,或者遭遇不可抗力的,或者系统故障导致的其它意外问题的,天猫及/或聚划算无需为此对外承担任何损害赔偿或者补偿。</p>',
'bg_img' => '/statics/images/seckill_bg.jpg',
);
?><file_sep>/caches/configs/prize_type.php
<?php
return array (
'0' => '没有中奖',
'1' => '积分',
'2' => '实物奖品',
);
?><file_sep>/api/click.php
<?php
// header("KissyIoDataType:jsonp");
// exit($_GET['callback'].'('.json_encode(array('data'=>'222')).')');
// exit($_GET['callback']."({\"status\":200,\"data\":\"kissy.io 中文. URL中文".urldecode_utf8($_GET["encodeCpt"])." ,".urldecode_utf8($_GET["encode"])."\"})");
?>
<?php
header("KissyIoDataType:jsonp");
$member=jae_base::load_app_class('foreground','member');
$point_db=jae_base::load_model('point_model');
$memberinfo = $member->memberinfo;
if($memberinfo["userid"]){
$login="签到赢积分";
if(!empty($memberinfo["wangwang"])) { $tips= $memberinfo["wangwang"] ; } else { $tips="请填写正确的资料";}
}else {$login='请登录'; $tips='请登录';
}
$prizes=$prize_db->count("userid=$memberinfo[userid]");
$orders=$order_db->count("userid=$memberinfo[userid]");
exit($_GET['callback'].'('.json_encode(array('tips'=>$tips,'point'=>$memberinfo['point'],'login'=>$login,'prizes'=>$prizes,'orders'=>$orders)).')');
?><file_sep>/upgrade/20140609.sql
ALTER TABLE jae_member DROP COLUMN fromuserid;
ALTER TABLE jae_member ADD fromuserid MEDIUMINT(8) UNSIGNED DEFAULT null AFTER userid;
UPDATE jae_site SET date='20140609' ;
UPDATE jae_site SET version='135';<file_sep>/jae/templates/liaoning2/config.php
<?php return array (
'name' => '辽宁2',
'author' => 'JAE TEAM QQ:182050367 ',
'dirname' => 'liaoning2',
'homepage' => '',
'version' => '1.0',
'disable' => 0,
'file_explan' =>
array (
'templates|liaoning|content' =>
array (
'foot.html' => '底部',
'head.html' => '顶部',
'index.html' => '网站首页',
),
'templates|liaoning|' =>
array (
'content' => '内容模型',
'css' => 'CSS样式',
),
'templates|liaoning|css' =>
array (
'mall.css' => '首页样式表',
),
'templates|liaoning|apply' =>
array (
'index.html' => '活动报名',
),
),
);?><file_sep>/upgrade/20140724.sql
ALTER TABLE `jae_block_type` ADD `siteid` SMALLINT(5) UNSIGNED NULL DEFAULT '0' AFTER `typeid`;
UPDATE jae_site SET date='20140724' ;
UPDATE jae_site SET version='145';<file_sep>/upgrade/20140615.sql
ALTER TABLE `jae_focus` CHANGE COLUMN `link` `link` TEXT NULL DEFAULT NULL AFTER `picture`;
UPDATE jae_site SET date='20140619' ;
UPDATE jae_site SET version='137';<file_sep>/caches/caches_commons/caches_data/point.cache.php
<?php
return array (
'point' => '50',
'title' => '完善基本资料获取积分',
'description' => '完善基本资料获取积分',
'thumb' => '/statics/images/',
);
?><file_sep>/caches/caches_template/default/content/list_goods.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head');?>
<!-- 商品列表开始 -->
<div class="wrap">
<div class="good_sort">
<ul><li <?php if($_GET["catId"]==''){?> class="on" <?php }?>>
<a style="width:150px; font-weight:bold;" href="/index.php?m=content&c=index&a=list_goods" >全部 </a></li>
<?php foreach ($r_category as $r) {?>
<li <?php if($_GET["catId"]==$r["id"]){?> class="on" <?php }?>> <a href="/index.php?m=content&c=index&a=list_goods&catId=<?php echo $r["id"];?>"><?php echo $r["name"];?> </a></li>
<?php }?>
</ul>
</div>
<div class="good_list">
<ul>
<?php
$db= jae_base::load_model('goods_model');
$data=$db->listinfo($where,$order = 'id DESC',$page, $pages = '30');
$pages=$db->pages;
foreach($data as $goods){; ?>
<li>
<div class="goods-block"> <a class="pic" target="_blank" href="<?php echo $goods['detail_url']; ?>"> <img class="height-aware" width="220" height="220" src="<?php echo $goods['pic_url']; ?>">
<div class="cover" style="bottom: -35px; "><?php echo $goods['title']; ?></div>
</a>
<div class="bottom"> <span class="price"><?php echo $goods['coupon_price']; ?></span> <span style="color:#D0D0D0;font-size:15px;">|</span> <span class="strike-price">¥<?php echo $goods['price']; ?></span> <br>
<span class="cp"> <b></b> </span>
<div class="buttons buybtn"> <a href="<?php echo $goods['detail_url']; ?>">去看看</a> </div>
</div>
</div>
</li>
<?php }?>
</ul>
</div>
</div>
<!-- 列表分页 -->
<div style="clear:both;"></div>
<div class="wrap pages">
<?php echo $pages; ?>
</div>
<?php include template('content','foot');?><file_sep>/caches/caches_template/liaoning/content/list_goods.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head');?>
<!-- 商品列表开始 -->
<?php $this->goods_type_db= jae_base::load_model('goods_type_model');
$v=$this->goods_type_db->get_one("typeid = $category_id"); ?>
<div style="background:#e7eded">
<div style="width:1190px; height:620px; margin:0 auto; position:relative">
<div style="width:1920px; position:absolute; left:-365px; top:0px;height:620px; overflow:hidden;"> <img src="<?php echo $v['description']; ?>"></div></div>
<div class="wrap">
<div class="good_list">
<ul>
<?php
$db= jae_base::load_model('goods_model');
$data=$db->listinfo($where,$order = 'id DESC',$page, $pages = '30');
$pages=$db->pages;
foreach($data as $goods){; ?>
<li>
<div class="goods-block"> <a class="pic" target="_blank" href="<?php echo $goods['detail_url']; ?>"> <img class="height-aware" width="280" height="280" src="<?php echo $goods['pic_url']; ?>">
<div class="cover" style="bottom: -35px; "><?php echo $goods['title']; ?></div>
</a>
<div class="bottom">
<a style="display:block" target="_blank" href="<?php echo $goods['detail_url']; ?>">
<span class="price">辽宁馆</span>
</a>
</div>
</div>
</li>
<?php }?>
</ul>
</div>
</div>
<!-- 列表分页 -->
<div style="clear:both;"></div>
<div class="wrap pages">
<?php echo $pages; ?>
</div>
</div>
<?php include template('content','foot');?><file_sep>/jae/modules/admin/templates/category_link.tpl.php
<?php include $this->admin_tpl('head');
?>
<form name="myform" id="myform" action="/admin.php?m=admin&c=category&a=add" method="post">
<table width="100%" class="table_form ">
<tr>
<th width="200"><?php echo L('parent_category')?>£؛</th>
<td>
<?php echo form::select_category('category_content_'.$this->siteid,$parentid,'name="info[parentid]"',L('please_select_parent_category'),0,-1);?>
</td>
</tr>
<tr>
<th><?php echo L('catname')?>£؛</th>
<td><input type="text" name="info[catname]" id="catname" class="input-text" value="<?php echo $catname;?>"></td>
</tr>
<tr>
<th><?php echo L('catgory_img')?>£؛</th>
<td><input type="text" name="info[image]" id="catname" class="input-text" value="<?php echo $catname;?>"></td>
</tr>
<tr>
<th><?php echo L('link_url')?>£؛</th>
<td><input type="text" name="info[url]" id="url" size="50" class="input-text" value="<?php echo $url;?>"></td>
</tr>
</table>
<!--table_form_off--><input type='hidden' name='info[type]' value='2'>
<div class="btns"><input type="submit" id="dosubmit" class="button" name="dosubmit" value="جل½»"></div>
</form>
<?php include $this->admin_tpl('foot');?><file_sep>/jae/templates/hubei3/config.php
<?php return array (
'name' => '湖北3',
'author' => 'JAE TEAM QQ:182050367 ',
'dirname' => 'hubei3',
'homepage' => 'http://182050367.qzone.qq.com/',
'version' => '1.0',
'disable' => 0,
'file_explan' =>
array (
'templates|hubei3|content' =>
array (
'foot.html' => '底部',
'head.html' => '顶部',
'index.html' => '网站首页',
),
'templates|hubei3|' =>
array (
'content' => '内容模型',
),
'templates|hubei3|apply' =>
array (
'index.html' => '活动报名',
),
'templates|hubei3|special' =>
array (
'api_picture.html' => '组图',
'comment.html' => '专题首页评论页',
'header.html' => '专题头部',
'index.html' => '专题首页',
'list.html' => '分类页',
'show.html' => '内容页',
'special_list.html' => '专题列表',
),
),
);?><file_sep>/.taecajoled/statics/js/common.js
{
___.loadModule({
'instantiate': function (___, IMPORTS___) {
var dis___ = IMPORTS___;
var moduleResult___, x0___, x1___, x2___, x3___, x4___, x5___, x6___,
x7___, x8___, x9___, x10___, x11___, x12___, x13___, x14___, x15___,
x16___, x17___, x18___, x19___;
moduleResult___ = ___.NO_RESULT;
new (x0___ = IMPORTS___.KISSY_v___? IMPORTS___.KISSY:
___.ri(IMPORTS___, 'KISSY'), x0___.DataLazyload_v___?
x0___.DataLazyload: x0___.v___('DataLazyload')).new___(___.iM([
'diff', 500 ]));
IMPORTS___.w___('$', IMPORTS___.jQuery_v___? IMPORTS___.jQuery:
___.ri(IMPORTS___, 'jQuery'));
IMPORTS___.w___('url_forward', (x1___ = (IMPORTS___.$_v___?
IMPORTS___.$: ___.ri(IMPORTS___, '$')).i___('.showMsg'),
x1___.attr_m___? x1___.attr('data-url'): x1___.m___('attr', [
'data-url' ])));
IMPORTS___.w___('ms', (x2___ = (IMPORTS___.$_v___? IMPORTS___.$:
___.ri(IMPORTS___, '$')).i___('.showMsg'), x2___.attr_m___?
x2___.attr('data-url'): x2___.m___('attr', [ 'data-url' ])));
x3___ = IMPORTS___.console_v___? IMPORTS___.console: ___.ri(IMPORTS___,
'console'), x4___ = IMPORTS___.url_forward_v___?
IMPORTS___.url_forward: ___.ri(IMPORTS___, 'url_forward'),
x3___.log_m___? x3___.log(x4___): x3___.m___('log', [ x4___ ]);
x5___ = IMPORTS___.console_v___? IMPORTS___.console: ___.ri(IMPORTS___,
'console'), x6___ = IMPORTS___.ms_v___? IMPORTS___.ms:
___.ri(IMPORTS___, 'ms'), x5___.log_m___? x5___.log(x6___):
x5___.m___('log', [ x6___ ]);
x7___ = (IMPORTS___.$_v___? IMPORTS___.$: ___.ri(IMPORTS___, '$'))
.i___('.member_btn'), x8___ = ___.f(function () {
var x0___;
x0___ = (IMPORTS___.$_v___? IMPORTS___.$: ___.ri(IMPORTS___, '$'))
.i___('.member_mini_nav'), x0___.show_m___? x0___.show():
x0___.m___('show', [ ]);
}), x9___ = ___.f(function () {
var x0___;
x0___ = (IMPORTS___.$_v___? IMPORTS___.$: ___.ri(IMPORTS___, '$'))
.i___('.member_mini_nav'), x0___.hide_m___? x0___.hide():
x0___.m___('hide', [ ]);
}), x7___.hover_m___? x7___.hover(x8___, x9___): x7___.m___('hover',
[ x8___, x9___ ]);
IMPORTS___.w___('fromuserid', (x10___ = (IMPORTS___.$_v___?
IMPORTS___.$: ___.ri(IMPORTS___, '$')).i___('.fromuserid'),
x10___.attr_m___? x10___.attr('data-fromuser-tips'):
x10___.m___('attr', [ 'data-fromuser-tips' ])));
if ((IMPORTS___.fromuserid_v___? IMPORTS___.fromuserid:
___.ri(IMPORTS___, 'fromuserid')) != 0) {
x11___ = (IMPORTS___.$_v___? IMPORTS___.$: ___.ri(IMPORTS___, '$'))
.i___('.banner-pic'), x12___ = '<a href=\'/member.php?fromuserid='
+ (IMPORTS___.fromuserid_v___? IMPORTS___.fromuserid:
___.ri(IMPORTS___, 'fromuserid')) +
'\' target=\'_blank\'><span class=\'btn-close J_LowsClose\'></span></a>',
x11___.html_m___? x11___.html(x12___): x11___.m___('html', [ x12___ ]
);
x13___ = (IMPORTS___.$_v___? IMPORTS___.$: ___.ri(IMPORTS___, '$'))
.i___('.trigger-wrap .prev'), x14___ =
'<a href=\'/member.php?fromuserid=' + (IMPORTS___.fromuserid_v___?
IMPORTS___.fromuserid: ___.ri(IMPORTS___, 'fromuserid')) +
'\' target=\'_blank\'></a>', x13___.html_m___? x13___.html(x14___):
x13___.m___('html', [ x14___ ]);
x15___ = (IMPORTS___.$_v___? IMPORTS___.$: ___.ri(IMPORTS___, '$'))
.i___('.trigger-wrap .next'), x16___ =
'<a href=\'/member.php?fromuserid=' + (IMPORTS___.fromuserid_v___?
IMPORTS___.fromuserid: ___.ri(IMPORTS___, 'fromuserid')) +
'\' target=\'_blank\'></a>', x15___.html_m___? x15___.html(x16___):
x15___.m___('html', [ x16___ ]);
x17___ = (IMPORTS___.$_v___? IMPORTS___.$: ___.ri(IMPORTS___, '$'))
.i___('.lows-banner'), x17___.slideDown_m___? x17___.slideDown(300)
: x17___.m___('slideDown', [ 300 ]);
x18___ = (IMPORTS___.$_v___? IMPORTS___.$: ___.ri(IMPORTS___, '$'))
.i___('.J_LowsClose'), x19___ = ___.f(function () {
var x0___;
x0___ = (IMPORTS___.$_v___? IMPORTS___.$: ___.ri(IMPORTS___, '$')
).i___('.lows-banner'), x0___.slideUp_m___? x0___.slideUp(300):
x0___.m___('slideUp', [ 300 ]);
}), x18___.click_m___? x18___.click(x19___): x18___.m___('click', [
x19___ ]);
}
moduleResult___ = (IMPORTS___.$ajax_v___? IMPORTS___.$ajax:
___.ri(IMPORTS___, '$ajax')).i___(___.iM([ 'jsonpCallback', 'jsonp',
'jsonp', 'callback', 'url', '/api.php?op=login', 'data', ___.iM([
'p', 1, 'encodeCpt', (IMPORTS___.encodeURIComponent_v___?
IMPORTS___.encodeURIComponent: ___.ri(IMPORTS___,
'encodeURIComponent'))
.i___('\u4e2d\u65871\u6d4b\u8bd5\u6210\u529f'), 'encode',
(IMPORTS___.encodeURI_v___? IMPORTS___.encodeURI:
___.ri(IMPORTS___, 'encodeURI'))
.i___('\u4e2d\u65872\u6d4b\u8bd5\u6210\u529f') ]), 'success',
(function () {
function success$_lit(data, textStatus, xhr) {
var x0___, x1___, x2___, x3___, x4___, x5___, x6___, x7___,
x8___, x9___, x10___, x11___, x12___, x13___;
x0___ = (IMPORTS___.$_v___? IMPORTS___.$: ___.ri(IMPORTS___,
'$')).i___('.member_sign a'), x1___ = data.login_v___?
data.login: data.v___('login'), x0___.html_m___?
x0___.html(x1___): x0___.m___('html', [ x1___ ]);
x2___ = (IMPORTS___.$_v___? IMPORTS___.$: ___.ri(IMPORTS___,
'$')).i___('.member_point a'), x3___ = data.point_v___?
data.point: data.v___('point'), x2___.html_m___?
x2___.html(x3___): x2___.m___('html', [ x3___ ]);
x4___ = (IMPORTS___.$_v___? IMPORTS___.$: ___.ri(IMPORTS___,
'$')).i___('.tips a'), x5___ = data.tips_v___?
data.tips: data.v___('tips'), x4___.html_m___?
x4___.html(x5___): x4___.m___('html', [ x5___ ]);
x6___ = (IMPORTS___.$_v___? IMPORTS___.$: ___.ri(IMPORTS___,
'$')).i___('.pots a'), x7___ = data.point_v___?
data.point: data.v___('point'), x6___.html_m___?
x6___.html(x7___): x6___.m___('html', [ x7___ ]);
x8___ = (IMPORTS___.$_v___? IMPORTS___.$: ___.ri(IMPORTS___,
'$')).i___('.prizes_num'), x9___ = data.prizes_v___?
data.prizes: data.v___('prizes'), x8___.html_m___?
x8___.html(x9___): x8___.m___('html', [ x9___ ]);
x10___ = (IMPORTS___.$_v___? IMPORTS___.$:
___.ri(IMPORTS___, '$')).i___('.orders_num'), x11___ =
data.orders_v___? data.orders: data.v___('orders'),
x10___.html_m___? x10___.html(x11___): x10___.m___('html', [
x11___ ]);
x12___ = (IMPORTS___.$_v___? IMPORTS___.$:
___.ri(IMPORTS___, '$')).i___('.login_tip'), x13___ =
data.tips_v___? data.tips: data.v___('tips'),
x12___.html_m___? x12___.html(x13___): x12___.m___('html', [
x13___ ]);
}
return ___.f(success$_lit, 'success$_lit');
})(), 'complete', (function () {
function complete$_lit(data) {}
return ___.f(complete$_lit, 'complete$_lit');
})(), 'error', (function () {
function error$_lit() {
var x0___;
x0___ = IMPORTS___.console_v___? IMPORTS___.console:
___.ri(IMPORTS___, 'console'), x0___.log_m___?
x0___.log('KissyIO Error'): x0___.m___('log', [
'KissyIO Error' ]);
}
return ___.f(error$_lit, 'error$_lit');
})(), 'dataType', 'jsonp' ]));
return moduleResult___;
},
'cajolerName': 'com.google.caja',
'cajolerVersion': '<unknown>',
'cajoledDate': 1420509444363
});
}<file_sep>/jae/modules/member/templates/edit_point.tpl.php
<?php include $this->admin_tpl('head','admin');
?>
<form name="myform" id="myform" action="/admin.php?m=member&c=buyer&a=edit_point" method="post">
<table width="100%" class="table_form contentWrap">
<tbody>
<tr>
<th> 标题</th>
<td><input style="width:300px;" type="text" name="info[title]" value="<?php echo $title?>" id="language" class="input-text"><div id="languageTip" class="onShow"></div></td>
</tr>
<tr>
<th width="100">图片</th>
<td><input style="width:300px;" type="text" name="info[picture]" value="<?php echo $picture?>" id="language" class="input-text"><div id="languageTip" class="onShow"></div></td>
</tr>
<tr>
<th> 积分</th>
<td><input style="width:300px;" type="text" name="info[point]" value="<?php echo $point?>" id="language" class="input-text"><div id="languageTip" class="onShow"></div></td>
</tr>
<tr>
<th>时间</th>
<td><input style="width:300px;" type="text" name="info[date]" value="<?php echo $date?>" id="language" class="input-text"><div id="nameTip" class="onShow"></div></td>
</tr>
<tr>
<th>类型</th>
<td><input style="width:300px;" type="text" name="info[module]" value="<?php echo $module?>" id="language" class="input-text"><div id="nameTip" class="onShow"></div></td>
</tr>
</tbody></table>
<!--table_form_off-->
<div class="btns"><input type="hidden" name="id" value="<?php echo $id?>">
<input type="hidden" name="userid" value="<?php echo $userid?>"><input type="submit" id="dosubmit" class="button" name="dosubmit" value="提交"></div>
</form>
<?php include $this->admin_tpl('foot','admin');?><file_sep>/jae/modules/position/templates/position_items.tpl.php
<?php
defined('IN_ADMIN') or exit('No permission resources.');
include $this->admin_tpl('head','admin');
?>
<form name="myform" action="/admin.php?m=position&c=position&a=public_item_listorder" method="post">
<input type="hidden" value="<?php echo $posid?>" name="posid">
<div class="pad_10">
<div class="table-list">
<table width="100%" cellspacing="0">
<thead>
<tr class="thead">
<th width="40" align="left"><input type="checkbox" value="" id="check_box" onclick="selectall('items[]');"></th>
<th width="40" align="left"><?php echo L('listorder');?></th>
<th width="40" align="left">ID</th>
<th width="" align="left"><?php echo L('title');?></th>
<th width="15%"><?php echo L('catname');?></th>
<th width="15%"><?php echo L('inputtime')?></th>
<td width="15%" align="center"><?php echo L('posid_operation');?></td>
</tr>
</thead>
<tbody>
<?php
if(is_array($infos)){
foreach($infos as $info){
?>
<tr>
<td >
<input type="checkbox" name="items[]" value="<?php echo $info['id'],'-',$info['modelid']?>" id="items" boxid="items">
</td>
<td >
<input name='listorders[<?php echo $info['catid'],'-',$info['id']?>]' type='text' size='3' value='<?php echo $info['listorder']?>' class="input-text">
</td>
<td align="left"><?php echo $info['id']?></td>
<td align="left"><?php echo $info['title']?> <?php if($info['thumb']!='') {echo '<img src="'.IMG_PATH.'icon/small_img.gif">'; }?></td>
<td align="left"><?php echo $info['catname']?></td>
<td align="left"><?php echo date('Y-m-d H:i:s',$info['inputtime'])?></td>
<td align="center"><a onclick="javascript:openwinx('?m=content&c=content&a=edit&catid=<?php echo $info['catid']?>&id=<?php echo $info['id']?>','')" target="_blank" href="/admin.php?m=admin&c=goods&a=edit&id=<?php echo $info['id']?>"><?php echo L('posid_item_edit');?></a> | <a target="_blank" href="/admin.php?m=position&c=position&a=public_item_manage&id=<?php echo $info['id']?>&posid=<?php echo $info['posid']?>" ><?php echo L('posid_item_manage')?></a> | <a onclick="javascript:openwinx('?m=content&c=content&a=edit&catid=<?php echo $info['catid']?>&id=<?php echo $info['id']?>','')" target="_blank" href="/admin.php?m=position&c=position&a=delete_item&id=<?php echo $info['id']?>&posid=<?php echo $info['posid']?>&modelid=<?php echo $info['modelid']?>"><?php echo L('posid_item_remove');?></a>
</td>
</tr>
<?php
}
}
?>
</tbody>
</table>
<div class="btns"> <input type="submit" class="button" value="<?php echo L('listorder')?>" onclick="myform.action='?m=admin&c=position&a=public_item_listorder';myform.submit();"/> </div></div>
<div id="pages"> <?php echo $pages?></div>
</div>
</div>
</form>
<script type="text/javascript">
function item_manage(id,posid, modelid, name) {
window.top.art.dialog({title:'<?php echo L('edit')?>--'+name, id:'edit', iframe:'?m=admin&c=position&a=public_item_manage&id='+id+'&posid='+posid+'&modelid='+modelid ,width:'550px',height:'430px'}, function(){var d = window.top.art.dialog({id:'edit'}).data.iframe;
var form = d.document.getElementById('dosubmit');form.click();return false;}, function(){window.top.art.dialog({id:'edit'}).close()});
}
</script>
<?php include $this->admin_tpl('foot','admin');?><file_sep>/jae/modules/point/index.php
<?php
defined('IN_JAE') or exit('No permission resources.');
jae_base::load_app_class('foreground','member');
jae_base::load_app_func('global');
class index extends foreground {
public function __construct() {
$this->prize_set_db = jae_base::load_model('prize_set_model');
$this->point_db = jae_base::load_model('point_model');
$this->point_set_db = jae_base::load_model('point_set_model');
$this->prize_db = jae_base::load_model('prize_model');
$this->member_db = jae_base::load_model('member_model');
$this->trade_db = jae_base::load_model('trade_model');
$this->point =jae_base::load_app_class('point','point');
parent::__construct();
}
//活动报名首页
public function init() {
$memberinfo = $this->memberinfo;
$where=" status=1 ";
$prize_arr=$this->prize_set_db->listinfo($where,$order = 'listorder,id DESC',$page, $pages = '12');
$data=$this->prize_db->listinfo($where2,$order = 'id DESC',$page, $pages = '8');
include template('prize','index');
}
public function receive_point() {
$memberinfo = $this->memberinfo;
$where =' 1 ';
$page=$_GET['page'];
$where.=" AND `buyer_nick` = '".$memberinfo['username']."'" ;
$receive=$_GET['receive']?$_GET['receive']:0 ;
$where.=" AND receive =$receive ";
$data=$this->trade_db->listinfo($where,$order = 'pub_time DESC',$page, $pages = '10');
$pages=$this->trade_db->pages;
include template('point','receive_point');
}
public function receive() {
$memberinfo = $this->memberinfo;
$where =' 1 ';
$where.=" AND `buyer_nick` = '".$memberinfo['username']."'" ;
$id=$_GET['id'];
$where.=" AND id=$id ";
$data=$this->trade_db->get_one($where);
$info['userid']=$memberinfo['userid'];
$info['point']=floor($data['paid_fee']/100);
$info['title']=$data['auction_title'];
$info['date']=SYS_TIME;
$info['picture']=$data[''];
$info['description']="消费兑换积分";
$info['status']=1;
$info['module']=$data['trade'];
if ($data['receive']==0) {
$data=$this->trade_db->update(array('receive' =>1 ),"id=$id");
$this->point->change_point($info);
showmessage(L('operation_success'));
} else {
showmessage(L('这个宝贝已经领取了积分'));
}
//include template('point','receive_point');
}
public function sign (){
$memberinfo = $this->memberinfo;//会员详细信息
if ($memberinfo) {
$pointinfo=$this->point_db->get_one('userid="'.$memberinfo['userid'].'" AND typeid=1','*','id DESC');
$signtime=strtotime(date('Y-m-d',SYS_TIME));
if ($signtime-$pointinfo['date']>0 || empty($pointinfo['date'])) {
//签到积分插入
if ($signtime-$pointinfo['date']>86400 || empty($pointinfo['date'])){ $continue=1;$day=1;}
else {$continue=$pointinfo['continue']+1 ; $day=$pointinfo['continue']+1;}//超过一天才可以签到
$lastday=$this->point_set_db->get_one("","*","day DESC");//取最后一天的积分
if ($continue>$lastday['day']) $continue=$lastday['day'];
//连续签到天数大于设置签到最大天数取最后一天
$point_set=$this->point_set_db->get_one("day=".$continue,'*');
$data= array('userid'=>$memberinfo['userid'],'date'=>SYS_TIME ,'title'=>$point_set['title'] ,'picture'=>$point_set['picture'],'point'=>$point_set['point'],'description'=>$point_set['description'],'status'=>'1','continue'=>$continue,'typeid'=>'1','module'=>'sign' );
//'typeid'=>'1'类型为签到
$this->point_db->insert($data);
$msg="签到成功"."这是连续第".$day."天签到";
//更新member表积分
$sum=$this->point_db->query("select sum(point) as point from jae_point where userid=".$memberinfo['userid']);
$row = $sum->fetch();
$this->member_db->update(array('point'=>$row['point']),'userid="'.$memberinfo['userid'].'"');
} else {
$msg="今天已经签到过了,请明天再来";
}
//统计已经消耗的积分
$sum=$this->member_db->query("select sum(point) as point from jae_point where point<0 and userid=".$memberinfo['userid'] );
$pointeds = $sum->fetch();
//*积分明细
$invite_sum=$this->member_db->count("fromuserid= ".$memberinfo['userid']." AND islock=0 " );
$page=$_GET['page'];
$trad=$_GET['trad'];
if ($_GET['trad']=='income')
{$data=$this->point_db->listinfo("userid='$memberinfo[userid]' AND point >0 ","id DESC",$page,50);}
elseif ($_GET['trad']=='used')
{$data=$this->point_db->listinfo("userid='$memberinfo[userid]' AND point <0 ","id DESC ",$page,50);}
else
{$data=$this->point_db->listinfo("userid=".$memberinfo['userid'],"id DESC",$page,50);
}
$pages=$this->point_db->pages;
//积分明细模板
include template('point','point');
}
else {
include template('member','login');
}
}
public function point_task() {
$data=getcache_sql('point','commons');
include template('point','task');
}
public function point_invite() {
$memberinfo = $this->memberinfo;//会员详细信息
$data=getcache_sql('point_invite','commons');
if ($data['enable']==0){showmessage(L('对不起,该功能暂时没有开放!'),"/index.php");}
$siteinfo=siteinfo(get_siteid());
include template('point','invite');
}
}
?><file_sep>/caches/caches_template/default/content/list_special.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head');?>
<!-- ÉÌÆ·ÁÐ±í¿ªÊ¼ -->
<div class="wrap">
<div class="special_list">
<div class="special_left">
<ul>
<?php
$db= jae_base::load_model('special_model');
$where="status=1";
$data=$db->listinfo($where,$order = 'listorder,id DESC',$page, $pages = '30');
$pages=$goods_db->pages;
foreach ($data as $k=>$v) {?>
<li class="zt<?php echo $k%5+1?>">
<a href="<?php echo "/index.php?m=content&c=special&a=show_special&id=".$v["id"]; ?>" target="_blank">
<h1><?php echo str_cut($v['title'],16,'');?></h1><div class="grace"><?php echo $v['description'];?></div><img height="240" width="240" src="<?php echo $v['thumb'];?>"></a>
</li>
<?php }?>
</ul>
</div>
<div style="clear:both"></div>
</div>
</div>
<!-- Áбí·ÖÒ³ -->
<?php include template('content','foot');?><file_sep>/jae/modules/admin/setting.php
<?php
defined('IN_JAE') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
class setting extends admin {
function __construct() {
parent::__construct();
$this->db =jae_base::load_sys_class('mysql');
$this->table='site_config';
$this->menuid=9;
}
function init () {
$info = isset($_POST["info"])?$_POST["info"]:'';
extract($info);
$updateMessage='';
if (isset($_POST['dosubmit']))
{
$sql1 = 'UPDATE site_config SET `value`="' . $siteUrl . '" WHERE `alias`="siteUrl"';
$sql2 = 'UPDATE site_config SET `value`="' . $wangwang . '" WHERE `alias`="wangwang"';
$sql3 = 'UPDATE site_config SET `value`="' . $bangpai . '" WHERE `alias`="bangpai"';
$sql4 = 'UPDATE site_config SET `value`="' . $appkey . '" WHERE `alias`="appkey"';
$sql5 = 'UPDATE site_config SET `value`="' . $secretKey . '" WHERE `alias`="secretKey"';
$sql6 = 'UPDATE site_config SET `value`="' . $pid . '" WHERE `alias`="pid"';
$sql7 = 'UPDATE site_config SET `value`="' . $logo . '" WHERE `alias`="logo"';
$sql8 = 'UPDATE site_config SET `value`="' . $sessionkey . '" WHERE `alias`="sessionkey"';
$pdo=new PDO();
$result1 = $pdo->exec($sql1);
$result2 = $pdo->exec($sql2);
$result3 = $pdo->exec($sql3);
$result4 = $pdo->exec($sql4);
$result5 = $pdo->exec($sql5);
$result6 = $pdo->exec($sql6);
$result7 = $pdo->exec($sql7);
$result8 = $pdo->exec($sql8);
if ($result1 > 0 && $result2 > 0 && $result3 > 0 && $result4 > 0 && $result5 > 0 && $result6 > 0 && $result7>0 && $result8>0)
{ showmessage(L('operation_success'));
}
else
{
showmessage(L('operation_failure'));
}
}
//赋值表单默认值
$res = rGetSiteConfig();
extract($res);
include $this->admin_tpl('setting');
}
}
?><file_sep>/jae/modules/admin/templates/site_add.tpl.php
<?php
defined('IN_ADMIN') or exit('No permission resources.');
include $this->admin_tpl('head');
?>
<div class="pad-10">
<form action="?m=admin&c=site&a=add" method="post" id="myform">
<div>
<fieldset>
<legend><?php echo L('basic_configuration')?></legend>
<table width="100%" class="table_form">
<tr>
<th width="80"><?php echo L('site_name')?>£º</th>
<td class="y-bg"><input type="text" class="input-text" name="name" id="name" size="40" /></td>
</tr>
<tr>
<th><?php echo L('site_domain')?>£º</th>
<td class="y-bg"><input type="text" class="input-text" name="domain" id="domain" size="40"/></td>
</tr> <tr>
<th><?php echo L('APPKEY')?>£º</th>
<td class="y-bg"><input type="text" class="input-text" name="appkey" id="appkey" size="40" /></td>
</tr>
<tr>
<th><?php echo L('SECRETKEY')?>£º</th>
<td class="y-bg"><input type="text" class="input-text" name="secretkey" id="secretkey" size="40" /></td>
</tr>
</table>
</fieldset>
<div class="bk15"></div>
<fieldset>
<legend><?php echo L('seo_configuration')?></legend>
<table width="100%" class="table_form">
<tr>
<th width="80"><?php echo L('site_title')?>£º</th>
<td class="y-bg"><input type="text" class="input-text" name="site_title" id="site_title" size="40" /></td>
</tr>
<tr>
<th><?php echo L('keyword_name')?>£º</th>
<td class="y-bg"><input type="text" class="input-text" name="keywords" id="keywords" size="40" /></td>
</tr>
<tr>
<th><?php echo L('description')?>£º</th>
<td class="y-bg"><input type="text" class="input-text" name="description" id="description" size="40" /></td>
</tr>
</table>
</fieldset>
<div class="bk15"></div>
<fieldset>
<legend><?php echo L('template_style_configuration')?></legend>
<table width="100%" class="table_form">
<tr>
<th width="80" valign="top"><?php echo L('style_name')?>£º</th>
<td class="y-bg"> <select name="template[]" size="3" style="width:200px;" id="template" multiple title="<?php echo L('ctrl_more_selected')?>" onchange="default_list()">
<?php if(is_array($template_list)):
foreach ($template_list as $key=>$val):
?>
<option value="<?php echo $val['dirname']?>"><?php echo $val['name']?></option>
<?php endforeach;endif;?>
</select></td>
</tr>
</tr>
</table>
</fieldset>
<div class="bk15"></div>
<fieldset>
<legend>
<?php echo L('site_att_config')?></legend>
<table width="100%" class="table_form">
<tr>
<th width="130" valign="top">
<?php echo L('Í·²¿LOGO')?></th>
<td class="y-bg">
<input type="text" class="input-text" name="setting[head_logo]" id="head_logo" size="50" value=""/> </td>
</tr>
<tr>
<th width="130" valign="top">
<?php echo L('µ×²¿LOGO')?></th>
<td class="y-bg">
<input type="text" class="input-text" name="setting[foot_logo]" id="foot_logo" size="50" value=""/> </td>
</tr>
</table>
</fieldset>
</div>
<div class="bk15"></div>
<input type="submit" class="button" id="dosubmit" name="dosubmit" value="<?php echo L('submit')?>" />
</form>
<?php
include $this->admin_tpl('foot');
?>
<file_sep>/jae/modules/mysql/templates/mysql_list.tpl.php
<?php include $this->admin_tpl('head','admin');?>
<form name="searchform" action="" method="get" accept-charset="UTF-8">
<input type="hidden" value="mysql" name="m">
<input type="hidden" value="mysql" name="c">
<input type="hidden" value="init" name="a">
<input type="hidden" value="<?php echo $this->menuid;?>" name="menuid">
<table width="100%" cellspacing="0" class="search-form">
<tbody>
<tr>
<td><div class="explain-col">Êý¾Ý¿â±íÃû
<select name="table">
<?php foreach ($tables as $key => $val) {?>
<option <?php if ($table==$key) echo "selected"?> value="<?php echo $key?>"><?php echo $val.' ==='.$key?> </option>
<?php }?>
</select>
<input type="submit" name="search" class="button" value="<?php echo L('submit')?>">
</div></td>
</tr>
</tbody>
</table>
</form>
<form name="myform" action="/admin.php?m=goods&c=goods_type&a=listorder" method="post" charset="GBK">
<div class="pad-lr-10">
<div class="table-list">
<textarea style="width:100%;height: 300px;" name="info[description]"><?php echo $dump?></textarea>
<div class="btns"><input type="submit" class="button" name="dosubmit" value="<?php echo L('listorder')?>" /></div> </div>
</div>
</div>
</form>
<div class="pages"><?php echo $pages;?></div>
<?php include $this->admin_tpl('foot','admin');?><file_sep>/top/user.php
<?php
/**
* 当前在线用户的信息获取
*
* @author Balsampear
* 2013-03-22
*/
class User {
const TYPE_ADMIN = 9;//最高权限管理员
const TYPE_ITEM_CHECK = 6;//商品审核
const TYPE_GENERAL = 0;//普通用户
private static $nick = null;
private static $data = null;
//取得当前用户的nick
public static function getCurrentNick() {
global $context;
if (is_null(self::$nick)) {
if ($context->getBrowser()){
self::$nick = $context->getBrowser()->getNick();
}else{
self::$nick = '';
}
}
if (is_null(self::$data)) {
if (self::$nick) {
$db = Database::instance();
self::$data = $db->getOne("select su_id,wangwang,user_type from seller_user where nick='".self::$nick."'");
}else{
self::$data = array();
}
}
return self::$nick;
}
public static function reInit() {
self::$nick = null;
self::$data = null;
}
//取得当前用户的旺旺
public static function getCurrentWangwang() {
self::getCurrentNick();
return self::$data['wangwang'];
}
//取得当前用户在vgogo的user id
public static function getCurrentId() {
self::getCurrentNick();
return self::$data['su_id'];
}
//取得当前用户的类型(相当于权限)
public static function getCurrentType() {
self::getCurrentNick();
return self::$data['user_type'];
}
//检测是否有指定的权限
public static function checkRight($needUserType) {
return self::getCurrentType() >= $needUserType;
}
}
<file_sep>/upgrade/jae_menu.sql
DELETE FROM jae_menu;
INSERT INTO `jae_menu` (`id`, `name`, `language`, `parentid`, `m`, `c`, `a`, `data`, `listorder`, `display`, `project1`, `project2`, `project3`, `project4`, `project5`) VALUES
(1, '扩展', 'extend', 0, 'admin', 'extend', 'init', '', 10, '1', 1, 1, 1, 1, 1),
(3, '菜单管理', 'menu', 2, 'admin', 'menu', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(4, '添加菜单', 'menu_add', 3, 'admin', 'menu', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(2, '扩展管理', 'extend', 1, 'admin', 'extend', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(6, '会员', 'member', 0, 'member', 'member', 'init', '', 6, '1', 1, 1, 1, 1, 1),
(7, '买家会员', 'buyer', 6, 'member', 'buyer', 'init', '', 7, '1', 1, 1, 1, 1, 1),
(8, '会员管理', 'buyer', 7, 'member', 'buyer', 'init', '', 8, '1', 1, 1, 1, 1, 1),
(9, '受邀会员审核', 'point_invite', 7, 'member', 'buyer', 'check_invite', '', 9, '1', 1, 1, 1, 1, 1),
(10, '界面', 'template', 0, 'template', 'style', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(11, '界面', 'template', 10, 'template', 'style', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(12, '首焦管理', 'focus', 11, 'admin', 'focus', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(13, '页面链接管理', 'weblink', 65, 'weblink', 'weblink', 'init', '', 13, '1', 1, 1, 1, 1, 1),
(14, '碎片管理', 'block', 64, 'block', 'block', 'init', '', 14, '1', 1, 1, 1, 1, 1),
(15, '营销', '', 0, '', '', '', '', 4, '1', 1, 1, 1, 1, 1),
(16, '内容', '1', 0, '1231', '1233', '123', '123', 0, '1', 1, 1, 1, 1, 1),
(17, '商品管理', '', 16, '', '', '', '', 17, '1', 1, 1, 1, 1, 1),
(18, '采集商品', 'goods_add', 17, 'admin', 'goods', 'add', '', 18, '1', 1, 1, 1, 1, 1),
(19, '报名管理', 'apply', 17, 'apply', 'goods', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(20, '商品管理', 'goods', 17, 'admin', 'goods', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(21, '特色店铺', 'shop', 16, 'admin', 'shop', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(22, '完善资料积分', 'point_setinfo', 7, 'point', 'point_set', 'point_setinfo', '', 0, '1', 1, 1, 1, 1, 1),
(23, '店铺管理', 'shop', 21, 'admin', 'shop', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(24, '文章', 'article', 16, 'admin', 'article', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(25, '文章管理', 'article', 24, 'admin', 'article', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(26, '专题频道', '', 16, '', '', '', '', 0, '1', 1, 1, 1, 1, 1),
(27, '专题管理', 'special', 26, 'admin', 'special', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(28, '自定义频道', '', 16, '', '', '', '', 0, '0', 1, 1, 1, 1, 1),
(29, '频道管理', 'channel', 28, 'admin', 'channel', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(30, '积分秒杀', 'seckill', 15, '', '', '', '', 0, '1', 1, 1, 1, 1, 1),
(31, '商品管理', 'seckill', 30, 'seckill', 'seckill', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(32, '积分抽奖', '', 15, '', '', '', '', 0, '1', 1, 1, 1, 1, 1),
(33, '中奖管理', 'prize', 32, 'prize', 'prize', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(34, '奖品设置', 'prize_set', 32, 'prize', 'prize_set', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(35, '积分签到', '', 15, '', '', '', '', 0, '1', 1, 1, 1, 1, 1),
(36, '签到积分设置', 'point', 35, 'point', 'point_set', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(37, '积分任务说明', 'point_set', 35, 'point', 'point_set', 'point_task', '', 0, '1', 1, 1, 1, 1, 1),
(38, '清除无效订单', 'clear_order', 89, 'order', 'order', 'clear', '', 0, '1', 1, 1, 1, 1, 1),
(39, '换购需知', 'exchange_setting', 79, 'exchange', 'exchange', 'setting', '', 0, '1', 1, 1, 1, 1, 1),
(40, '卖家会员', '', 6, '', '', '', '', 0, '1', 1, 1, 1, 1, 1),
(41, '卖家审核', 'seller_check', 40, 'member', 'seller', 'seller_check', '', 0, '1', 1, 1, 1, 1, 1),
(42, '会员管理', '', 40, 'member', 'seller', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(43, '申请条件设置', '', 40, '', '', '', '', 0, '0', 1, 1, 1, 1, 1),
(44, '合作', '', 0, '', '', '', '', 0, '1', 1, 1, 1, 1, 1),
(45, '友情链接', '', 44, '', '', '', '', 0, '1', 1, 1, 1, 1, 1),
(46, '友情链接管理', 'link', 45, 'admin', 'link', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(47, '品牌合作', '', 44, '', '', '', '', 0, '1', 1, 1, 1, 1, 1),
(48, '品牌管理', 'brand', 47, 'brand', 'brand', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(49, '品牌分类', 'brand_type', 47, 'brand', 'brand_type', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(50, '推荐位', '', 10, '', '', '', '', 0, '1', 1, 1, 1, 1, 1),
(51, '推荐位管理', 'position', 50, 'position', 'position', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(52, '添加首焦', 'focus_add', 12, 'admin', 'focus', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(53, '添加专题', 'special', 27, 'admin', 'special', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(54, '添加友情链接', 'link', 46, 'admin', 'link', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(55, '添加店铺', 'shop', 23, 'admin', 'shop', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(56, '添加文章', 'article', 25, 'admin', 'article', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(57, '添加频道', 'channel_add', 29, 'admin', 'channel', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(58, '添加碎片', 'block', 14, 'block', 'block', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(59, '添加面页链接', 'weblink', 13, 'weblink', 'weblink', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(60, '页面链接分类管理', 'weblink_type', 65, 'weblink', 'weblink_type', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(61, '添加页面链接分类', 'weblink_type_add', 60, 'weblink', 'weblink_type', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(62, '碎片分类管理', 'block_type', 64, 'block', 'block_type', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(63, '添加碎片分类', 'block_type_add', 62, 'block', 'block_type', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(64, '碎片', '', 10, '', '', '', '', 0, '1', 1, 1, 1, 1, 1),
(65, '页面链接', '', 10, '', '', '', '', 0, '1', 1, 1, 1, 1, 1),
(66, '添加推荐位', 'position_add', 51, 'position', 'position', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(67, '添加品牌', 'brand_add', 48, 'brand', 'brand', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(68, '添加品牌分类', 'brand_type_add', 49, 'brand', 'brand_type', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(69, '商品分类', 'goods_type', 17, 'goods', 'goods_type', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(70, '添加商品分类', 'goods_type_add', 69, 'goods', 'goods_type', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(71, '邀请好友赚积分', 'point_invite', 7, 'point', 'point_set', 'point_invite', '', 0, '1', 1, 1, 1, 1, 1),
(72, '首页可视管理', 'index_mamage', 11, 'block', 'block_admin', 'public_visualization', 'type=index', 0, '1', 1, 1, 1, 1, 1),
(73, '生成CSS', 'special_css', 27, 'admin', 'special', 'special_css', '', 0, '1', 1, 1, 1, 1, 1),
(74, '添加商品', 'seckill_add', 31, 'seckill', 'seckill', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(75, '添加奖品', 'prize_set_add', 34, 'prize', 'prize_set', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(76, '抽奖配置', 'prize_rules', 32, 'prize', 'prize', 'setting', '', 0, '1', 1, 1, 1, 1, 1),
(77, '站点管理', 'site', 2, 'admin', 'site', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(78, '数据库工具', 'mysql', 2, 'mysql', 'mysql', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(79, '积分换购', '', 15, '', '', '', '', 0, '1', 1, 1, 1, 1, 1),
(80, '换购商品管理', 'exchange', 79, 'exchange', 'exchange', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(81, '订单', 'order', 0, '', '', '', '', 0, '1', 1, 1, 1, 1, 1),
(88, '订单管理', '', 81, '', '', '', '', 0, '1', 1, 1, 1, 1, 1),
(82, '实物奖品', 'prize_real', 33, 'prize', 'prize', 'prize_real', '', 0, '1', 1, 1, 1, 1, 1),
(83, '栏目导航管理', 'category', 86, 'admin', 'category', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(84, '添加栏目', 'category_add', 83, 'admin', 'category', 'add', 'type=0', 0, '1', 1, 1, 1, 1, 1),
(85, '添加外部链接', 'category_link', 83, 'admin', 'category', 'add', 'type=2', 0, '1', 1, 1, 1, 1, 1),
(86, '内容相关设置', '', 16, '', '', '', '', 0, '1', 1, 1, 1, 1, 1),
(87, '更新栏目缓存', 'category_cache', 83, 'admin', 'category', 'public_cache', '', 0, '1', 1, 1, 1, 1, 1),
(89, '订单管理', 'order', 88, 'order', 'order', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(90, 'JAE导购成交记录', 'trade', 88, 'trade', 'trade', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(91, '获取成交记录', 'consume_request', 90, 'trade', 'trade', 'request', '', 0, '1', 1, 1, 1, 1, 1),
(92, '前台菜单管理', 'member_menu', 2, 'member', 'member_menu', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(93, '添加菜单', 'member_menu_add', 92, 'member', 'member_menu', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(97, '积分秒杀配置', 'seckil_lset', 30, 'seckill', 'seckill', 'setting', '', 0, '1', 1, 1, 1, 1, 1),
(98, '添加商品', 'exchange_add', 80, 'exchange', 'exchange', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(99, '模板管理', '', 10, '', '', '', '', 0, '1', 1, 1, 1, 1, 1),
(100, '模板风格', 'style', 99, 'template', 'style', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(101, '添加站点', 'site_add', 77, 'admin', 'site', 'add', '', 0, '1', 1, 1, 1, 1, 1),
(102, '导出会员数据', 'member_export', 8, 'member', 'buyer', 'export', '', 0, '1', 1, 1, 1, 1, 1),
(103, '系统升级', 'upgrade', 2, 'upgrade', 'index', 'init', '', 0, '1', 1, 1, 1, 1, 1),
(104, '初次登录送积分', 'point_first', 7, 'point', 'point_set', 'point_first', '', 0, '', 1, 1, 1, 1, 1);<file_sep>/index.php
<?php
define('JAE_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR);define('IN_JAE',true);
if($_GET['m']=='admin') exit('No permission resources.');
include JAE_PATH.'/jae/base.php';
jae_base::creat_app();
?><file_sep>/caches/caches_template/default/order/convert_seckill.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head');?>
<link rel="stylesheet" href="/statics/css/order.css" />
<div class="blank"></div>
<div class="wrap">
<div class="flowstep" id="J_Flowstep">
<ol class="flowstep-4">
<li class="step-first">
<div class="step-done">
<div class="step-name">兑换商品</div>
<div class="step-no"></div>
</div>
</li>
<li>
<div class="step-name">提交订单</div>
<div class="step-no">2</div>
</li>
<li>
<div class="step-name">确认收货</div>
<div class="step-no">3</div>
</li>
<li class="step-last">
<div class="step-name">晒单</div>
<div class="step-no">4</div>
</li>
</ol>
</div>
<div class="order">
<h2>确认订单</h2>
<div class="detail">
<div class="masthead clearfix"><span class="why">消费项目</span><span class="what">消费积分</span><span class="when" style="width:200px;">原价</span><span class="what">数量</span><span class="notes">产品描述</span></div>
<div id="J_pointDetail">
<ul class="item-list" id="J_item-list">
<li class="item clearfix">
<div class="why"><a class="img" href="<?php echo $goods['detail_url']?>" target="_blank"><img src="<?php echo $goods['pic_url']?>" width="60" height="60" ></a><a class="title" href="<?php echo $goods['detail_url']?>" target="_blank"><?php echo $goods['title']?></a><span class="order-number">编号:<?php echo $goods['id']?></span></div>
<div class="what"><span class=" plus"><?php echo $goods['point'] ?></span></div>
<div class="when" style="width:200px;"><?php echo $goods['price']?></div>
<div class="when" style="width:200px;">1</div>
<div class="notes"><?php echo $goods['description'];?> </div>
</li>
</ul>
</div>
<div id="J_pointError" class="hidden error"></div>
<div id="J_pointPager" class="pages">
</div>
</div>
</div>
<form name="myform" action="/index.php?m=order&c=index&a=seckill_submit" method="post" >
<div class="checkbar " style="display: block; ">
<div class="due">
<p class="pay-info">
<span class="question"><b>请回答问题:</b> <?php echo $goods['question']?></span>
<span class="answer"> <b>请填写答案:</b> <input type="text" name="answer" value="" ></span>
<span class="bd">
<button id="J_Go" data-mm="tmalljy.2.6?action=submit" class="go-btn" type="submit" data-evt="buy-order/biz/go:submit" title="提交订单">提交订单</button>
</span>
</p>
</div>
<div class="action">
<span>
<input type="hidden" name="id" value="<?php echo $goods['id']?>">
</span>
</div>
</div>
</form>
<div class="clear"></div>
</div><file_sep>/jae/modules/member/classes/foreground.class.php
<?php
class foreground {
public $db, $memberinfo;
private $_member_modelinfo;
public function __construct() {
//self::check_ip()
$this->member_db=jae_base::load_model('member_model');
$this->point_db=jae_base::load_model('point_model');
$this->point_set_db=jae_base::load_model('point_set_model');
$this->point =jae_base::load_app_class('point','point');
if(substr(ROUTE_A, 0, 7) != 'public_') {
self::check_member();
}
self::check_member();
}
/**
* 判断用户是否已经登陆
*/
final public function check_member() {
jae_base::load_sys_class('user');
$browser=$context->getbrowser();
$nick=$browser->nick;
// && in_array(ROUTE_A, array('init', 'sign', 'setinfo','point_task','seller_apply','goods_apply','goods_manage','apply_task','edit','delete'))
if(ROUTE_M =='member' || ROUTE_M =='point' ) {
if (!empty($nick)) {
$result = $this->member_db->get_one ("username='$nick'");
$this->memberinfo=$result;
if(empty($result)){
$fromuserid=intval($_GET['fromuserid']);
if ($fromuserid==0) {$islock=1;}else {$islock=0;}
$data = array('username'=>$nick,'regdate' =>SYS_TIME ,'lastdate'=>SYS_TIME ,'loginnum'=>1,'groupid'=>1,'islock'=>$islock,'fromuserid'=>$fromuserid );//'groupid'=>1 为买家会员
$this->member_db->insert($data);
$result = $this->member_db->get_one ("username='$nick'");
$this->memberinfo=$result;
self::first_login();
//$point_invite_cache=getcache('point_invite','commons');
//if($point_invite_cache['enable']==1) self::invite($fromuserid);
}
else
{
$loginnum = $result['loginnum'] + 1;
$this->member_db->update(array('lastdate'=>SYS_TIME ,'loginnum'=>$loginnum),'userid='.$result['userid']);
}
//showmessage(L('login_success', '', 'member'), 'index.php?m=member&c=index');
} else {
$forward= isset($_GET['forward']) ? urlencode($_GET['forward']) : urlencode(get_url());
header('location:/member.php?forward='.$forward);
//showmessage(L('please_login', '', 'member'), '/index.php?m=member&c=index&a=login&forward='.$forward);
//showmessage(L('please_login', '', 'member'), '/member.php?forward='.$forward);
}
} else {
//判断是否存在auth cookie
if (!empty($nick)) {
$result = $this->member_db->get_one ("username='$nick'");
$this->memberinfo=$result;
} else {
$forward= isset($_GET['forward']) ? urlencode($_GET['forward']) : urlencode(get_url());
header('location:/member.php?forward='.$forward);
//showmessage(L('please_login', '', 'member'), '/member.php?forward='.$forward);
}
}
}
/*第一次登录送积分*/
final public function first_login(){
$memberinfo = $this->memberinfo;//会员详细信息
$continue=0;
$point_set=$this->point_set_db->get_one("day=".$continue);//首次登录所送积分
$data= array('userid'=>$memberinfo['userid'],'date'=>SYS_TIME ,'title'=>$point_set['title'] ,'picture'=>$point_set['picture'],'point'=>$point_set['point'],'description'=>$point_set['description'],'status'=>'1','continue'=>$continue,'typeid'=>2);
$this->point_db->insert($data);
//更新member表积分
$sum=$this->member_db->query("select sum(point) as point from jae_point where userid=".$memberinfo['userid']);
$row = $sum->fetch();
$this->member_db->update(array('point'=>$row['point']),'userid="'.$memberinfo['userid'].'"');
}
/*邀请好友赚积分*/
final public function invite($fromuserid){
$setting=getcache_sql('point_invite', 'commons');
if($setting['enable']==1) {
$array_point=array('userid'=>$fromuserid,'point'=>$setting['point'],'title'=>$setting['title'],'date'=>SYS_TIME,'picture'=>$setting['thumb'],'description'=>$setting['description'],'status'=>'2','module'=>'invite');
$this->point->change_point($array_point);//更新积分明细
}
}
/**
*
* IP禁止判断 ...
*/
final private function check_ip(){
$this->ipbanned = pc_base::load_model('ipbanned_model');
$this->ipbanned->check_ip();
}
}<file_sep>/demo/index.php
<?php
$result = $fileStoreService->saveTextFile("<?php array('a'=>'1'); ?>", "index.php");
if( $fileStoreService->isFileExist("index.html") && $_GET['nocache']==false ){
echo "调用缓存";
echo $getFileTextResult = $fileStoreService->getFileText("index.php") ;
}else {echo "不调用缓存";}
?><file_sep>/jae/modules/block/block.php
<?php
defined('IN_JAE') or exit('No permission resources.');defined('IN_ADMIN') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
class block extends admin {
function __construct() {
parent::__construct();
$this->db =jae_base::load_sys_class('mysql');
$this->table='jae_block';
$this->type='jae_block_type';
$this->menuid=14;
}
function init () {
$sitelist=getcache('sitelist','commons');
$type=$this->db->select('*',$this->type);
$typeid=$_POST['info']['typeid'];
$kw=$_POST['kw'];
$where =1;
if(!empty($typeid)) $where.= " AND typeid='$typeid'";
if(!empty($kw)) $where.= " AND name like '%$kw%'";
$page=$_GET['page'];
$data=$this->db->listinfo("*",$this->table,$where,"id DESC",$page,10);
$pages=$this->db->pages;
include $this->admin_tpl('block_list','block');
}
function add() {
$sitelist=getcache('sitelist','commons');
if(isset($_POST['dosubmit'])) {
$data=$_POST['info'];
$_POST['info']['data']=htmlspecialchars($_POST['info']['data']);
$data['siteid']=get_siteid();
$this->db->insert($data,$this->table);
include $this->admin_tpl('block_add');
showmessage(L('add_success'));
} else {
$typeid=$_GET['typeid'];
$type=$this->db->select('*',$this->type);
include $this->admin_tpl('block_add','block');
}
}
function delete() {
$_GET['id'] = intval($_GET['id']);
$this->db->delete($this->table,'id='.$_GET['id']);
showmessage(L('operation_success'));
}
function edit() {
$sitelist=getcache('sitelist','commons');
if(isset($_POST['dosubmit'])) {
$id = intval($_POST['id']);
$data=$_POST['info'];
$_POST['info']['data']=htmlspecialchars($_POST['info']['data']);
$this->db->update($data,$this->table,'id='.$id);
showmessage(L('operation_success'));
include $this->admin_tpl('block_edit');
} else {
$typeid=$_GET['typeid'];
$type=$this->db->select('*',$this->type);
$id = intval($_GET['id']);
$pos =$_GET['pos'];
$r=$this->db->get_one('*',$this->table," `id`= '$id' or `pos`='$pos'");
if($r) extract($r);
include $this->admin_tpl('block_edit');
}
}
function listorder() {
if(isset($_POST['dosubmit'])) {
foreach($_POST['listorders'] as $id => $listorder) {
$listorder = !empty($listorder) ? $listorder : '0';
$this->db->update(array('listorder'=>$listorder),$this->table,'id='.$id);
$status = isset($_POST["status"][$id]) ? $_POST["status"][$id] : '0';
$this->db->update(array('status'=>$status),$this->table,'id='.$id);
}
showmessage(L('operation_success'));
} else {
showmessage(L('operation_failure'));
}
}
}
?><file_sep>/jae/libs/functions/global.func.php
<?php
function shop_collect($nick){
//获取站点配置信息
$siteinfo=siteinfo(SITEID);
$appkey =$siteinfo['appkey'];
$secret =$siteinfo['secretkey'];
jae_base::load_top('topclient');
jae_base::load_top('ShopGetRequest');
$c = new TopClient;
$c->appkey = $appkey; //top appkey
$c->secretKey = $secret; //top secretkey
//实例化具体API对应的Request类
$req = new ShopGetRequest(); //top 封装的php文件
$req->setFields("sid,cid,title,nick,desc,pic_path,created,modified");
$req->setNick($nick);
$resp = $c->execute($req);
if ($resp->shop)
{
$array['sid'] = $resp->shop->sid;
$array['shop_title'] = $resp->shop->title;
$array['detail_url'] = 'http://shop'.$resp->shop->sid.'.taobao.com';
$array['description'] = $resp->shop->desc;
$array['pic_url'] = $resp->shop->pic_path;
return $array;
}else
return $array = '不存在这个店铺';
}
/**
* 商品采集
* @param $numiid 商品ID
*/
function goods_collect ($numiid){
//获取站点配置信息
$siteinfo=siteinfo(SITEID);
$appkey =$siteinfo['appkey'];
$secret =$siteinfo['secretkey'];
jae_base::load_top('topclient');
jae_base::load_top('ItemGetRequest');
$c= new TopClient;
$c->appkey = $appkey;
$c->secretKey = $secret;
$req = new ItemGetRequest;
$req->setFields("detail_url,num_iid,title,nick,type,cid,seller_cids,props,input_pids,input_str,desc,pic_url,num,valid_thru,list_time,delist_time,stuff_status,location,price,post_fee,express_fee,ems_fee,has_discount,freight_payer,has_invoice,has_warranty,has_showcase,modified,increment,approve_status,postage_id,product_id,auction_point,property_alias,item_img,prop_img,sku,video,outer_id,is_virtual");
$req->setNumIid($numiid);
$resp = $c->execute($req, $sessionKey);
// print_r($resp);
if ($resp->item) {
$array['detail_url'] = $resp->item->detail_url; //商品链接
$array['num_iid'] = $resp->item->num_iid; //商品ID
$array['title'] = $resp->item->title; //商品标题
$array['nick'] = $resp->item->nick; //卖家昵称
$array['pic_url'] = $resp->item->pic_url; //商品主图
$array['num'] = $resp->item->num; //商品数量
$array['price'] = $resp->item->price; //商品原价格
$array['freight_payer'] = $resp->item->freight_payer; //商品原价格
$shop_array=shop_collect($array['nick']);
$array['shop_url']=$shop_array['detail_url'];
; return $array;
} else{
return $array = '不存在这个商品';
}
}
/**
* 判断模块是否安装
* @param $m 模块名称
*/
function module_exists($m = '') {
if ($m=='admin') return true;
$modules = getcache('modules', 'commons');
$modules = array_keys($modules);
//return in_array($m, $modules);
return 1;
}
function jae_tag($op, $data, $html){
$tag=jae_base::load_sys_class('template_cache');
return $tag->jae_tag($op, $data, $html);
}
/**
* 获取当前的站点ID
*/
function get_siteid() {
static $siteid;
if (!empty($siteid)) return $siteid;
if (0) {
//if (defined('IN_ADMIN')) {
if ($d = param::get_cookie('siteid')) {
$siteid = $d;
} else {
return '';
}
} else {
//$data = getcache('sitelist', 'commons');
$db = jae_base::load_model('site_model');
$data=$db->select();
$data =$data->fetchAll();
if(!is_array($data)) return '1';
$site_url = SITE_PROTOCOL.SITE_URL;
foreach ($data as $v) {
if( $v['uuid']==1) $siteid = $v['siteid'];
}
}
if (empty($siteid)) $siteid = 1;
return $siteid;
}
/*碎片调用*/
function block($id){
$mysql=jae_base::load_sys_class('mysql');
$result=$mysql->get_one('*','jae_block','id='.$id);
return htmlspecialchars_decode($result['data']);
}
/*sql语句执行*/
function query($sql){
$db = jae_base::load_model('module_model');;
$result=$db->query($sql);
return $result;
}
/*
奖品数量调用
*/
function get_prize_num($userid){
$prize_db = jae_base::load_model('prize_model');
$sum=$prize_db->count("userid=$userid");
if (intval($sum)) return $sum ; else return 0 ;
}
/**
* 转义 javascript 代码标记
*
* @param $str
* @return mixed
*/
function trim_script($str) {
if(is_array($str)){
foreach ($str as $key => $val){
$str[$key] = trim_script($val);
}
}else{
$str = preg_replace ( '/\<([\/]?)script([^\>]*?)\>/si', '<\\1script\\2>', $str );
$str = preg_replace ( '/\<([\/]?)iframe([^\>]*?)\>/si', '<\\1iframe\\2>', $str );
$str = preg_replace ( '/\<([\/]?)frame([^\>]*?)\>/si', '<\\1frame\\2>', $str );
$str = preg_replace ( '/]]\>/si', ']] >', $str );
}
return $str;
}
/**
* 获取用户信息
* 不传入$field返回用户所有信息,
* 传入field,取用户$field字段信息
*/
function get_memberinfo($userid, $field='') {
if(!is_numeric($userid)) {
return false;
} else {
static $memberinfo;
if (!isset($memberinfo[$userid])) {
$member_db = jae_base::load_model('member_model');
$memberinfo[$userid] = $member_db->get_one(array('userid'=>$userid));
}
if(!empty($field) && !empty($memberinfo[$userid][$field])) {
return $memberinfo[$userid][$field];
} else {
return $memberinfo[$userid];
}
}
}
/**
* 将数组转换为字符串
*
* @param array $data 数组
* @param bool $isformdata 如果为0,则不使用new_stripslashes处理,可选参数,默认为1
* @return string 返回字符串,如果,data为空,则返回空
*/
function array2string($data, $isformdata = 1) {
if($data == '') return '';
$data_arr =array();
foreach ( $data as $k=>$v) {$data_arr[$k]=$v;}
if($isformdata) $data_arr = new_stripslashes($data_arr);
return addslashes(var_export($data_arr, TRUE));
}
/**
* 返回经addslashes处理过的字符串或数组
* @param $string 需要处理的字符串或数组
* @return mixed
*/
function new_addslashes($string){
if(!is_array($string)) return addslashes($string);
foreach($string as $key => $val) $string[$key] = new_addslashes($val);
return $string;
}
/**
* 返回经stripslashes处理过的字符串或数组
* @param $string 需要处理的字符串或数组
* @return mixed
*/
function new_stripslashes($string) {
if(!is_array($string)) return stripslashes($string);
foreach($string as $key => $val) $string[$key] = new_stripslashes($val);
return $string;
}
/**
* 返回经htmlspecialchars处理过的字符串或数组
* @param $obj 需要处理的字符串或数组
* @return mixed
*/
function new_html_special_chars($string) {
if(!is_array($string)) return htmlspecialchars($string);
foreach($string as $key => $val) $string[$key] = new_html_special_chars($val);
return $string;
}
/**
* 将字符串转换为数组
*
* @param string $data 字符串
* @return array 返回数组格式,如果,data为空,则返回空数组
*/
function string2array($data) {
preg_match_all ("/[\((][\s\S]*[\))]/",$data,$out, PREG_PATTERN_ORDER);
if($data == '') return array();
$str= str_replace("(","",$out[0][0]);
$crr=str_replace(")","", $str);
$crr=str_replace("'","", $crr);
$crr=substr($crr,0,-2);
$crr=explode(',',$crr);
foreach ($crr as $v){
$row=explode('=>',$v);
$res[trim($row[0])] = trim($row[1]);
}
return $res;
}
function string2array2($data) {
preg_match_all("/[\'](.*?)[\']/",$data,$matches);
$array = array();
$sum=count($matches[1]);
for ($k=0;$k<=$sum;$k=$k+2){
$array[$matches[1][$k]]=chop($matches[1][$k+1]);
}
return $array;
}
/*sql语句执行*/
function position($where){
$mysql=jae_base::load_sys_class('mysql');
$result=$mysql->get_one('*','jae_position',"posid='$where'");
return $result['title'];
}
/**
* 通过id获取显示菜单
* @param $menuid 当前菜单ID
* @param $keyid 菜单keyid
* @param $space 菜单间隔符
* @param $tyoe 1 返回间隔符链接,完整路径名称 3 返回完整路径数组,2返回当前联动菜单名称,4 直接返回ID
* @param $result 递归使用字段1
* @param $infos 递归使用字段2
*/
function get_menu($menuid,$infos,$result=array()){
if (!$infos){
$db =jae_base::load_sys_class('mysql');
$menulist=$db->select('*','jae_menu');
foreach ($menulist as $k => $v){ $infos[$v['id']]=$v; }
}
if($menuid>0) {
$result[]= $infos[$menuid];
//print_r($result);
$infos[$menuid]['parentid'];
return get_menu($infos[$menuid]['parentid'],$infos,$result);
} else {
krsort($result);
foreach ($result as $k=>$c){$menu[]=$c;}
return $menu;
}
}
/**
* 生成sql语句,如果传入$in_cloumn 生成格式为 IN('a', 'b', 'c')
* @param $data 条件数组或者字符串
* @param $front 连接符
* @param $in_column 字段名称
* @return string
*/
function to_sqls($data, $front = ' AND ', $in_column = false) {
if($in_column && is_array($data)) {
$ids = '\''.implode('\',\'', $data).'\'';
$sql = "$in_column IN ($ids)";
return $sql;
} else {
if ($front == '') {
$front = ' AND ';
}
if(is_array($data) && count($data) > 0) {
$sql = '';
foreach ($data as $key => $val) {
$sql .= $sql ? " $front `$key` = '$val' " : " `$key` = '$val' ";
}
return $sql;
} else {
return $data;
}
}
}
/**
* 分页函数
*
* @param $num 信息总数
* @param $curr_page 当前分页
* @param $perpage 每页显示数
* @param $urlrule URL规则
* @param $array 需要传递的数组,用于增加额外的方法
* @return 分页
*/
function pages($num, $curr_page, $perpage = 20, $urlrule = '', $array = array(),$setpages = 10) {
if(defined('URLRULE') && $urlrule == '') {
$urlrule = URLRULE;
$array = $GLOBALS['URL_ARRAY'];
} elseif($urlrule == '') {
$urlrule = url_par('page={$page}');
// $urlrule =get_url();
}
$multipage = '';
if($num > $perpage) {
$page = $setpages+1;
$offset = ceil($setpages/2-1);
$pages = ceil($num / $perpage);
if (defined('IN_ADMIN') && !defined('PAGES')) define('PAGES', $pages);
$from = $curr_page - $offset;
$to = $curr_page + $offset;
$more = 0;
if($page >= $pages) {
$from = 2;
$to = $pages-1;
} else {
if($from <= 1) {
$to = $page-1;
$from = 2;
} elseif($to >= $pages) {
$from = $pages-($page-2);
$to = $pages-1;
}
$more = 1;
}
$multipage .= '<a class="a1">'.$num.L('page_item').'</a>';
if($curr_page>0) {
$multipage .= ' <a href="'.pageurl($urlrule, $curr_page-1, $array).'" class="a1">'.L('previous').'</a>';
if($curr_page==1) {
$multipage .= ' <span>1</span>';
} elseif($curr_page>6 && $more) {
$multipage .= ' <a href="'.pageurl($urlrule, 1, $array).'">1</a>..';
} else {
$multipage .= ' <a href="'.pageurl($urlrule, 1, $array).'">1</a>';
}
}
for($i = $from; $i <= $to; $i++) {
if($i != $curr_page) {
$multipage .= ' <a href="'.pageurl($urlrule, $i, $array).'">'.$i.'</a>';
} else {
$multipage .= ' <span>'.$i.'</span>';
}
}
if($curr_page<$pages) {
if($curr_page<$pages-5 && $more) {
$multipage .= ' ..<a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>';
} else {
$multipage .= ' <a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>';
}
} elseif($curr_page==$pages) {
$multipage .= ' <span>'.$pages.'</span> <a href="'.pageurl($urlrule, $curr_page, $array).'" class="a1">'.L('next').'</a>';
} else {
$multipage .= ' <a href="'.pageurl($urlrule, $pages, $array).'">'.$pages.'</a> <a href="'.pageurl($urlrule, $curr_page+1, $array).'" class="a1">'.L('next').'</a>';
}
}
return $multipage;
}
/**
* 返回分页路径
*
* @param $urlrule 分页规则
* @param $page 当前页
* @param $array 需要传递的数组,用于增加额外的方法
* @return 完整的URL路径
*/
function pageurl($urlrule, $page, $array = array()) {
if(strpos($urlrule, '~')) {
$urlrules = explode('~', $urlrule);
$urlrule = $page < 2 ? $urlrules[0] : $urlrules[1];
}
$findme = array('{$page}');
$replaceme = array($page);
if (is_array($array)) foreach ($array as $k=>$v) {
$findme[] = '{$'.$k.'}';
$replaceme[] = $v;
}
$url = str_replace($findme, $replaceme, $urlrule);
$url = str_replace(array('http://','//','~'), array('~','/','http://'), $url);
return $url;
}
/**
* URL路径解析,pages 函数的辅助函数
*
* @param $par 传入需要解析的变量 默认为,page={$page}
* @param $url URL地址
* @return URL
*/
function url_par($par, $url = '') {
if($url == '') $url = get_url();
$pos = strpos($url, '?');
if($pos === false) {
$url .= '?'.$par;
} else {
$querystring= $querystring = substr(strstr($url, '?'), 1); //
$ps= strpos($querystring,'&page');
if ($ps){ $querystring= substr($querystring,0,$ps);}
/*parse_str($querystring, $pars);
$query_array = array();
foreach($pars as $k=>$v) {
if($k != 'page') $query_array[$k] = $v;
}
$querystring = http_build_query($query_array).'&'.$par;*/
$querystring = $querystring.'&'.$par;
$url = substr($url, 0, $pos).'?'.$querystring;
}
return $url;
}
/**
* 安全过滤函数
*
* @param $string
* @return string
*/
function safe_replace($string) {
$string = str_replace('%20','',$string);
$string = str_replace('%27','',$string);
$string = str_replace('%2527','',$string);
$string = str_replace('*','',$string);
$string = str_replace('"','"',$string);
$string = str_replace("'",'',$string);
$string = str_replace('"','',$string);
$string = str_replace(';','',$string);
$string = str_replace('<','<',$string);
$string = str_replace('>','>',$string);
$string = str_replace("{",'',$string);
$string = str_replace('}','',$string);
$string = str_replace('\\','',$string);
return $string;
}
/**
* 获取当前页面完整URL地址
*/
function get_url() {
$sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
// $php_self = $_SERVER['PHP_SELF'] ? safe_replace($_SERVER['PHP_SELF']) : safe_replace($_SERVER['SCRIPT_NAME']);
//$path_info = isset($_SERVER['PATH_INFO']) ? safe_replace($_SERVER['PATH_INFO']) : '';
$relate_url = safe_replace($_SERVER['REQUEST_URI']) . $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.safe_replace($_SERVER['QUERY_STRING']) : $path_info);
$relate_url=str_replace("&", "&", $relate_url);
return $relate_url;
}
/**
* 语言文件处理
*
* @param string $language 标示符
* @param array $pars 转义的数组,二维数组 ,'key1'=>'value1','key2'=>'value2',
* @param string $modules 多个模块之间用半角逗号隔开,如:member,guestbook
* @return string 语言字符
*/
function L($language = 'no_language',$pars = array(), $modules = '') {
static $LANG = array();
static $LANG_MODULES = array();
static $lang = '';
if(defined('IN_ADMIN')) {
$lang = SYS_STYLE ? SYS_STYLE : 'zh-cn';
} else {
$lang = jae_base::load_config('system','lang');
}
if(!$LANG) {
require_once JAE_PATH.'jae'.DIRECTORY_SEPARATOR.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'system.lang.php';
if(defined('IN_ADMIN')) require_once JAE_PATH.'jae'.DIRECTORY_SEPARATOR.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.'system_menu.lang.php';
if(file_exists(JAE_PATH.'jae'.DIRECTORY_SEPARATOR.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php')) require JAE_PATH.'jae'.DIRECTORY_SEPARATOR.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.ROUTE_M.'.lang.php';
}
if(!empty($modules)) {
$modules = explode(',',$modules);
foreach($modules AS $m) {
if(!isset($LANG_MODULES[$m])) require JAE_PATH.'jae'.DIRECTORY_SEPARATOR.'languages'.DIRECTORY_SEPARATOR.$lang.DIRECTORY_SEPARATOR.$m.'.lang.php';
}
}
if(!array_key_exists($language,$LANG)) {
return $language;
} else {
$language = $LANG[$language];
if($pars) {
foreach($pars AS $_k=>$_v) {
$language = str_replace('{'.$_k.'}',$_v,$language);
}
}
return $language;
}
}
/**
* 模板调用
*
* @param $module
* @param $template
* @param $istag
* @return unknown_type
*/
function template($module = 'content', $template = 'index', $style = '') {
$module = str_replace('/', DIRECTORY_SEPARATOR, $module);
if(!empty($style) && preg_match('/([a-z0-9\-_]+)/is',$style)) {
} elseif (empty($style) && !defined('STYLE')) {
if(defined('SITEID')) {
$siteid = SITEID;
} else {
//$siteid = param::get_cookie('siteid');
}
if (!$siteid) $siteid = 1;
$sitelist = getcache('sitelist','commons');
if(!empty($siteid)) {
$style = $sitelist[$siteid]['default_style'];
}
} elseif (empty($style) && defined('STYLE')) {
$style = STYLE;
} else {
$style = 'default';
}
if(!$style) $style = 'default';
$template_cache = jae_base::load_sys_class('template_cache');
$compiledtplfile = JAE_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
if(file_exists(JAE_PATH.'jae'.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) {
if(!file_exists($compiledtplfile) || (@filemtime(JAE_PATH.'jae'.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > @filemtime($compiledtplfile))) {
$template_cache->template_compile($module, $template, $style);
}
} else {
$compiledtplfile = JAE_PATH.'caches'.DIRECTORY_SEPARATOR.'caches_template'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.php';
if(!file_exists($compiledtplfile) || (file_exists(JAE_PATH.'jae'.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') && filemtime(JAE_PATH.'jae'.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html') > filemtime($compiledtplfile))) {
$template_cache->template_compile($module, $template, 'default');
} elseif (!file_exists(JAE_PATH.'jae'.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) {
showmessage('Template does not exist.'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html');
}
}
return $compiledtplfile;
}
/**
* 模板调用
*
* @param $module
* @param $template
* @param $istag
* @return unknown_type
*/
function template0000($module = 'content', $template = 'index', $style = '') {
$module = str_replace('/', DIRECTORY_SEPARATOR, $module);
$siteid=SITEID;
if (!$siteid) $siteid = 1;
if (empty($style)){
$sitelist = getcache('sitelist','commons');
$style = $sitelist[$siteid]['default_style'];
}
if(!$style) $style = 'default';
$compiledtplfile = JAE_PATH.'jae'.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html';
if(file_exists(JAE_PATH.'jae'.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) {
} else {
$compiledtplfile = JAE_PATH.'jae'.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html';
if (!file_exists(JAE_PATH.'jae'.DIRECTORY_SEPARATOR.'templates'.DIRECTORY_SEPARATOR.'default'.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html')) {
showmessage('Template does not exist.'.DIRECTORY_SEPARATOR.$style.DIRECTORY_SEPARATOR.$module.DIRECTORY_SEPARATOR.$template.'.html');
}
}
return $compiledtplfile;
}
/**
* 写入缓存,默认为文件缓存,不加载缓存配置。
* @param $name 缓存名称
* @param $data 缓存数据
* @param $filepath 数据路径(模块名称) caches/cache_$filepath/
* @param $type 缓存类型[file,memcache,apc]
* @param $config 配置名称
* @param $timeout 过期时间
*/
function setcache($name, $data, $filepath='', $type='file', $config='', $timeout=0) {
jae_base::load_sys_class('cache_factory','',0);
if($config) {
$cacheconfig = jae_base::load_config('cache');
$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
} else {
$cache = cache_factory::get_instance()->get_cache($type);
}
return $cache->set($name, $data, $timeout, '', $filepath);
}
//调用数据库缓存
function getcache_sql($name, $filepath='', $type='file', $config='') {
$cache_db = jae_base::load_model('cache_model');
$datas=$cache_db->get_one( "filename = '".$name.".cache.php'" );
$data=string2array($datas['data']);
return $data;
}
/**
* 读取缓存,默认为文件缓存,不加载缓存配置。
* @param string $name 缓存名称
* @param $filepath 数据路径(模块名称) caches/cache_$filepath/
* @param string $config 配置名称
*/
function getcache($name, $filepath='', $type='file', $config='') {
jae_base::load_sys_class('cache_factory','',0);
if($config) {
$cacheconfig = jae_base::load_config('cache');
$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
} else {
$cache = cache_factory::get_instance()->get_cache($type);
}
return $cache->get($name, '', '', $filepath);
}
/**
* 删除缓存,默认为文件缓存,不加载缓存配置。
* @param $name 缓存名称
* @param $filepath 数据路径(模块名称) caches/cache_$filepath/
* @param $type 缓存类型[file,memcache,apc]
* @param $config 配置名称
*/
function delcache($name, $filepath='', $type='file', $config='') {
jae_base::load_sys_class('cache_factory','',0);
if($config) {
$cacheconfig = jae_base::load_config('cache');
$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
} else {
$cache = cache_factory::get_instance()->get_cache($type);
}
return $cache->delete($name, '', '', $filepath);
}
/**
* 读取缓存,默认为文件缓存,不加载缓存配置。
* @param string $name 缓存名称
* @param $filepath 数据路径(模块名称) caches/cache_$filepath/
* @param string $config 配置名称
*/
function getcacheinfo($name, $filepath='', $type='file', $config='') {
jae_base::load_sys_class('cache_factory');
if($config) {
$cacheconfig = jae_base::load_config('cache');
$cache = cache_factory::get_instance($cacheconfig)->get_cache($config);
} else {
$cache = cache_factory::get_instance()->get_cache($type);
}
return $cache->cacheinfo($name, '', '', $filepath);
}
/**
* 获取站点的信息
* @param $siteid 站点ID
*/
function siteinfo($siteid) {
static $sitelist;
if (empty($sitelist)) $sitelist = getcache('sitelist','commons');
$site_db = jae_base::load_model('site_model');
$siteinfo=$site_db->get_one("siteid=$siteid");
$sitelist[$siteid]['version']=$siteinfo['version'];
$sitelist[$siteid]['date']=$siteinfo['date'];
return isset($sitelist[$siteid]) ? $sitelist[$siteid] : '';
}
/**
* 提示信息页面跳转,跳转地址如果传入数组,页面会提示多个地址供用户选择,默认跳转地址为数组的第一个值,时间为5秒。
* showmessage('登录成功', array('默认跳转地址'=>'http://www.phpcms.cn'));
* @param string $msg 提示信息
* @param mixed(string/array) $url_forward 跳转地址
* @param int $ms 跳转等待时间
*/
function showmessage($msg, $url_forward = 'goback', $ms = 1.250, $dialog = '', $returnjs = '') {
if(defined('IN_ADMIN')) {
include(admin::admin_tpl('showmessage', 'admin'));
} else {
include(template('content', 'message'));
}
exit;
}
/**
* 字符截取 支持UTF8/GBK
* @param $string
* @param $length
* @param $dot
*/
function str_cut($string, $length, $dot = '...') {
$strlen = strlen($string);
if($strlen <= $length) return $string;
$string = str_replace(array(' ',' ', '&', '"', ''', '“', '”', '—', '<', '>', '·', '…'), array(' ',' ', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), $string);
$strcut = '';
if(strtolower(CHARSET) == 'utf-8') {
$length = intval($length-strlen($dot)-$length/3);
$n = $tn = $noc = 0;
while($n < strlen($string)) {
$t = ord($string[$n]);
if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
$tn = 1; $n++; $noc++;
} elseif(194 <= $t && $t <= 223) {
$tn = 2; $n += 2; $noc += 2;
} elseif(224 <= $t && $t <= 239) {
$tn = 3; $n += 3; $noc += 2;
} elseif(240 <= $t && $t <= 247) {
$tn = 4; $n += 4; $noc += 2;
} elseif(248 <= $t && $t <= 251) {
$tn = 5; $n += 5; $noc += 2;
} elseif($t == 252 || $t == 253) {
$tn = 6; $n += 6; $noc += 2;
} else {
$n++;
}
if($noc >= $length) {
break;
}
}
if($noc > $length) {
$n -= $tn;
}
$strcut = substr($string, 0, $n);
$strcut = str_replace(array('∵', '&', '"', "'", '“', '”', '—', '<', '>', '·', '…'), array(' ', '&', '"', ''', '“', '”', '—', '<', '>', '·', '…'), $strcut);
} else {
$dotlen = strlen($dot);
$maxi = $length - $dotlen - 1;
$current_str = '';
$search_arr = array('&',' ', '"', "'", '“', '”', '—', '<', '>', '·', '…','∵');
$replace_arr = array('&',' ', '"', ''', '“', '”', '—', '<', '>', '·', '…',' ');
$search_flip = array_flip($search_arr);
for ($i = 0; $i < $maxi; $i++) {
$current_str = ord($string[$i]) > 127 ? $string[$i].$string[++$i] : $string[$i];
if (in_array($current_str, $search_arr)) {
$key = $search_flip[$current_str];
$current_str = str_replace($search_arr[$key], $replace_arr[$key], $current_str);
}
$strcut .= $current_str;
}
}
return $strcut.$dot;
}
/**
* 获取站点配置信息
* @global type $pdo
* @return type
*/
function rGetSiteConfig()
{
$pdo=new PDO();
$res = array();
$sql = 'SELECT `value`, `alias` FROM site_config';
if (!$result = $pdo->query($sql))
{
$sql_info = $pdo->errorInfo(); //取得错误信息数组(注意此处取的是$pdo的errorInfo而不是$sql的)
echo '错误:' . $sql_info[2]; //输出错误信息
}
else
{
foreach ($pdo->query($sql) as $row)
{
$res[$row['alias']] = $row['value'];
}
$siteConfigCacheSet = $cacheService->set('siteConfig', $res, 0);
return $res;
}
}
/**
* 获取推荐位数组
* @global type $pdo
* @param type $type type:goods article shop
* @return type
*/
function rGetPromotePositionArr($type)
{
$pdo=new PDO();
$res = array();
$sql = 'SELECT `posid`, `name` FROM `jae_position` ';
if (!$result = $pdo->query($sql))
{
$sql_info = $pdo->errorInfo(); //取得错误信息数组(注意此处取的是$pdo的errorInfo而不是$sql的)
echo '错误:' . $sql_info[2]; //输出错误信息
}
else
{
foreach ($pdo->query($sql) as $row)
{
$res[$row['posid']] = $row['name'];
}
return $res;
}
}
/**
* 获取频道数组
* @global type $pdo
* @return type
*/
function rGetPindaoArr()
{
$pdo=new PDO();
$res = array();
$sql = 'SELECT `id`, `name` FROM `jae_channel`';
if (!$result = $pdo->query($sql))
{
$sql_info = $pdo->errorInfo(); //取得错误信息数组(注意此处取的是$pdo的errorInfo而不是$sql的)
echo '错误:' . $sql_info[2]; //输出错误信息
}
else
{
foreach ($pdo->query($sql) as $row)
{
$res[$row['id']] = $row['name'];
}
return $res;
}
}
/**
* 获取分类数组
* @global type $pdo
* @return type
*/
function rGetCategoryArr($limit = 100)
{
$pdo=new PDO();
$res = array();
$sql = 'SELECT `typeid`, `name` FROM `jae_goods_type` ORDER BY `typeid` ASC LIMIT ' . $limit;
if (!$result = $pdo->query($sql))
{
$sql_info = $pdo->errorInfo(); //取得错误信息数组(注意此处取的是$pdo的errorInfo而不是$sql的)
echo '错误:' . $sql_info[2]; //输出错误信息
}
else
{
foreach ($pdo->query($sql) as $row)
{
$res[$row['typeid']] = $row['name'];
}
return $res;
}
}
/**
* URL验证规则
* @param type $attribute
* @return boolean
*/
function rRuleUrl($attribute)
{
if (preg_match('/^http:\/\/.*?i/', $attribute))
return TRUE;
else
return FALSE;
}
/**
* 数字验证规则
* @param type $attribute
* @return boolean
*/
function rRuleNum($attribute)
{
if (preg_match('/^\d+$/', $attribute))
return TRUE;
else
return FALSE;
}
/**
* 数字字母验证规则
* @param type $attribute
* @return boolean
*/
function rRuleLetterAndNum($attribute)
{
if (preg_match('/[^a-zA-Z0-9]/', $attribute))
return TRUE;
else
return FALSE;
}
/**
* 字母验证规则
* @param type $attribute
* @return boolean
*/
function rRuleLetter($attribute)
{
if (preg_match('/[^a-zA-Z]/', $attribute))
return TRUE;
else
return FALSE;
}
/**
* 价格验证规则
* @param type $attribute
* @return boolean
*/
function rRulePrice($attribute)
{
if (preg_match('/^\d+(\.\d+)?$/', $attribute))
return TRUE;
else
return FALSE;
}
/**
*
* @return
*/
function rRuleClient()
{
echo 'CTMDb13xD';
}
/**
* 获取相应推荐位的商品
* @global type $pdo
* @param type $promoteAlias 推荐位系统别名
* @param type $categoryId 商品所属分类
* @param type $limit 数量
* @return type
*/
function rGetPromoteGoods($posid, $categoryId = -1, $limit = 20)
{
$pdo=new PDO();
$resultArr = array();
$sql = 'SELECT * FROM `jae_position` WHERE `posid`="' . $posid . '"';
$rs = $pdo->query($sql);
$row = $rs->fetch();
if (isset($row['id']))
{
if (intval($categoryId != -1))
$sql = 'SELECT * FROM `jae_goods` WHERE `promote_id`="' . $row['id'] . '" AND `end_time`>' . time() .' AND `begin_time`<'. time() . ' AND `category_id`="' . $categoryId . '" ORDER BY `id` DESC LIMIT ' . $limit;
else
$sql = 'SELECT * FROM `jae_goods` WHERE `promote_id`="' . $row['id'] . '" ORDER BY `end_time` DESC LIMIT ' . $limit;
$rs = $pdo->query($sql);
$resultArr = $rs->fetchAll();
}
return $resultArr;
}
/**
* 获取相应推荐位的商品
* @global type $pdo
* @param type $promoteAlias 推荐位系统别名
* @param type $categoryId 商品所属分类
* @param type $limit 数量
* @return type
*/
function get_goods( $promote_id , $limit = 10)
{
$pdo=new PDO();
// if (intval($categoryId != -1))
// $sql = 'SELECT * FROM `goods` WHERE `promote_id`="' .$promote_id . '" AND `end_time`>' . time() .' AND `begin_time`<'. time(). ' AND `category_id`="' . $categoryId . '" ORDER BY `id` DESC LIMIT ' . $limit;
// else
$sql = 'SELECT * FROM `jae_goods` WHERE `promote_id`= "'.$promote_id. '" AND `begin_time`< "' . time() .'" ORDER BY `listorder`,`id` DESC LIMIT ' . $limit;
$rs = $pdo->query($sql);
$resultArr = $rs->fetchAll();
return $resultArr;
}
function get_goods_asc( $promote_id , $limit = 10)
{
$pdo=new PDO();
// if (intval($categoryId != -1))
// $sql = 'SELECT * FROM `goods` WHERE `promote_id`="' .$promote_id . '" AND `end_time`>' . time() .' AND `begin_time`<'. time(). ' AND `category_id`="' . $categoryId . '" ORDER BY `id` DESC LIMIT ' . $limit;
// else
$sql = 'SELECT * FROM `jae_goods` WHERE `promote_id`= "'.$promote_id.'" AND `listorder`!= 0 ORDER BY `listorder`,`id` ASC LIMIT ' . $limit;
$rs = $pdo->query($sql);
$resultArr = $rs->fetchAll();
return $resultArr;
}
/**
* 获取相应推荐位的商品
* @global type $pdo
* @param type $promoteAlias 推荐位系统别名
* @param type $categoryId 商品所属分类
* @param type $limit 数量
* @return type
*/
function get_array( $num_iid , $limit = 100)
{
$pdo=new PDO();
// if (intval($categoryId != -1))
// $sql = 'SELECT * FROM `goods` WHERE `promote_id`="' .$promote_id . '" AND `end_time`>' . time() .' AND `begin_time`<'. time(). ' AND `category_id`="' . $categoryId . '" ORDER BY `id` DESC LIMIT ' . $limit;
// else
$sql = 'SELECT * FROM `jae_goods` WHERE `num_iid` in ('.$num_iid.') ORDER BY `id` DESC LIMIT ' . $limit;
$rs = $pdo->query($sql);
$resultArr = $rs->fetchAll();
//print_r($resultArr);
return $resultArr;
}
/**
* 获取友情链接(合作伙伴)
* @global type $pdo
* @param type $limit
* @return type
*/
function rGetFriendLink($limit = 10)
{
$pdo=new PDO();
$sql = 'SELECT * FROM `friend_link` WHERE 1 ORDER BY `id` DESC LIMIT ' . $limit;
$rs = $pdo->query($sql);
$resultArr = $rs->fetchAll();
return $resultArr;
}
/**
* 获取推荐位详细信息
* @global type $pdo
* @param type $alias
* @return type
*/
function rGetPromotePositionDetail($alias)
{
$pdo=new PDO();
$resultArr = array();
$sql = 'SELECT * FROM `jae_position` WHERE `alias`="' . $alias . '"';
$rs = $pdo->query($sql);
$row = $rs->fetch();
return $row;
}
/**
* 判断商品是否存在;返回1 or 0
* @global type $pdo
* @param type $numIid
* @return type
*/
function rGetGoodsExists($numIid)
{
$pdo=new PDO();
$sql = 'SELECT `id` FROM `jae_goods` WHERE `num_iid`="' . $numIid . '"';
$result = $pdo->exec($sql);
return $result;
}
/**
* 获取分类详细信息
* @global type $pdo
* @param type $id
* @return type
*/
function rGetCategoryDetail($id = 0, $alias = '')
{
$pdo=new PDO();
if ($alias == '')
$sql = 'SELECT * FROM `category` WHERE `id`=' . $id;
else
$sql = 'SELECT * FROM `category` WHERE `alias`="' . $alias . '"';
$rs = $pdo->query($sql);
$result = $rs->fetch($sql);
return $result;
}
?><file_sep>/jae/modules/member/index.php
<?php
defined('IN_JAE') or exit('No permission resources.');
jae_base::load_top('topclient');
jae_base::load_top('ItemGetRequest');
jae_base::load_app_class('foreground');
class index extends foreground{
public function __construct(){
//$this->menu_db = jae_base::load_model('menu_model');
//$this->db =jae_base::load_sys_class('mysql');
$this->point_db=jae_base::load_model('point_model');
$this->member_db=jae_base::load_model('member_model');
$this->goods_db=jae_base::load_model('goods_model');
$this->point_set_db=jae_base::load_model('point_set_model');
/*$this->table='jae_member';
$this->point='jae_point';
$this->goods='jae_goods';
$this->point_set='jae_point_set';*/
$this->point =jae_base::load_app_class('point','point');
parent::__construct();
}
public function init ()
{ $memberinfo = $this->memberinfo;
include template('point','point');
}
public function login (){
include template('member','login');
}
public function point_task (){
$memberinfo = $this->memberinfo;
include template('member','point_task');
}
public function setinfo (){
$memberinfo = $this->memberinfo;
if(isset($_POST['dopost'])){
$data=$_POST['info'];
if(empty($data['wangwang'])) {showmessage(L('请填写正确的旺旺'),'/index.php?m=member&c=index&a=setinfo');}
if(empty($data['nickname'])) {showmessage(L('请填写正确的姓名'),'/index.php?m=member&c=index&a=setinfo');}
if(empty($data['mobile'])) {showmessage(L('请填写正确的手机'),'/index.php?m=member&c=index&a=setinfo');}
if(empty($data['address'])) {showmessage(L('请填写正确的地址'),'/index.php?m=member&c=index&a=setinfo');}
/*if(empty($data['zipcode'])) {showmessage(L('请填写正确的邮编'),'/index.php?m=member&c=index&a=setinfo');}
if(empty($data['email'])) {showmessage(L('请填写正确的邮箱'),'/index.php?m=member&c=index&a=setinfo');}
$wangwang=$this->member_db->get_one("wangwang = $data[wangwang]") ;
if ($wangwang['userid']) {showmessage(L('该旺旺已存在'),'/index.php?m=member&c=index&a=setinfo');}
$mobile=$this->member_db->get_one("mobile = $data[mobile]") ;
if ($wangwang['userid']) {showmessage(L('该旺旺已存在'),'/index.php?m=member&c=index&a=setinfo');}
$email=$this->member_db->get_one("email = $data[email]") ;
if ($wangwang['email']) {showmessage(L('该旺旺已存在'),'/index.php?m=member&c=index&a=setinfo');}
*/
$data['shop_profile']=htmlspecialchars($_POST['info']);
$this->member_db->update($data,'username="'.$memberinfo['username'].'"');
$setting=getcache_sql('point_setinfo', 'commons');
if($memberinfo['vip']==0 && $setting['enable']==1) {
$array_point=array('userid'=>$memberinfo['userid'],'point'=>$setting['point'],'title'=>$setting['title'],'date'=>SYS_TIME,'picture'=>$setting['thumb'],'description'=>$setting['description'],'status'=>'2','module'=>'setinfo');
$this->point->change_point($array_point);//
$this->member_db->update(array('vip'=>1),'username="'.$memberinfo['username'].'"');
}
$result=$this->member_db->get_one ('username="'.$memberinfo['username'].'"');
@extract($result);
showmessage(L('资料更新成功'),'/index.php');
include template('member','setinfo');
}
else{
$result=$this->member_db->get_one ('username="'.$memberinfo['username'].'"' );
@extract($result);
include template('member','setinfo');
}
}
public function seller_apply (){
$memberinfo = $this->memberinfo;
if(isset($_POST['dopost'])){
$data=$_POST['info'];
$data['groupid']=2;//groupid=2为卖家
$data['islock']=0;
$this->member_db->update($data,'userid="'.$memberinfo['userid'].'"');
$result=$this->member_db->get_one ('userid="'.$memberinfo['userid'].'"');
@extract($result);
$msg="<font color=#FF0000>申请已经提交</font>";
include template('member','setinfo');
}
else{
$result=$this->member_db->get_one ('userid="'.$memberinfo['userid'].'"' );
@extract($result);
include template('member','seller_apply');
}
}
public function goods_apply (){
$memberinfo = $this->memberinfo;
if ($memberinfo['groupid']==2 && $memberinfo['islock']==1 ){
$msg="您还不是馆内卖家";
}
//获取站点配置信息
$siteinfo=siteinfo(SITEID);
$appkey =$siteinfo['appkey'];
$secret =$siteinfo['secretkey'];
jae_base::load_top('topclient');
jae_base::load_top('ItemGetRequest');
//初始化变量
$pindaoArr = rGetPindaoArr();
$categoryArr = rGetCategoryArr();
$dopost = isset($_POST['dopost']) ? $_POST['dopost'] : '';
$createMessage='';
$begin_time = isset($_POST['begin_time']) ? strtotime($_POST['begin_time']) : time();
$end_time = isset($_POST['end_time']) ? strtotime($_POST['end_time']) : time()+604800;
$detail_url = isset($_POST['detail_url']) ? $_POST['detail_url'] : '';
$freight_payer = isset($_POST['freight_payer']) ? $_POST['freight_payer'] : '';
$nick = isset($_POST['nick']) ? $_POST['nick'] : '';
$price = isset($_POST['price']) ? $_POST['price'] : 0;
$coupon_price = isset($_POST['coupon_price']) ? $_POST['coupon_price'] : 0;
$num = isset($_POST['num']) ? $_POST['num'] : 0;
$pic_url = isset($_POST['pic_url']) ? $_POST['pic_url'] : '';
$category_id = isset($_POST['category_id']) ? $_POST['category_id'] : 0;
$title = isset($_POST['title']) ? $_POST['title'] : '';
$desctiption = isset($_POST['desctiption']) ? $_POST['desctiption'] : '';
$pindao_id =isset($_POST['pindao_id']) ? $_POST['pindao_id'] : 0;
$num_iid = isset($_POST['num_iid']) ? trim($_POST['num_iid']) : '';
$shop_url=$memberinfo['shop_url']?$memberinfo['shop_url']:'';
if ($dopost == 'caiji')
{
if ($num_iid != "" && rRuleNum($num_iid))
{
$c = new TopClient;
$c->appkey = $appkey; //top appkey
$c->secretKey = $secret; //top secretkey
//实例化具体API对应的Request类
$req = new ItemGetRequest(); //top 封装的php文件
$req->setFields("num_iid,title,pic_url,detail_url,price,num,nick,freight_payer");
$req->setNumIid($num_iid);
$resp = $c->execute($req);
if ($resp->item)
{
$detail_url = $resp->item->detail_url; //商品链接
$num_iid = $resp->item->num_iid; //商品ID
$title = $resp->item->title; //商品标题
$nick = $resp->item->nick; //卖家昵称
$pic_url = $resp->item->pic_url; //商品主图
$num = $resp->item->num; //商品数量
$price = $resp->item->price; //商品原价格
$freight_payer = $resp->item->freight_payer; //商品原价格
}else
$createMessage = '不存在这个商品';
}
else
{
$createMessage = "商品ID【不能为空】并且【必须是数字】。";
}
}
if ($dopost == 'create')
{
$pdo=new PDO();
if($end_time-$begin_time>604800){
$createMessage = '失败!促销时间不能超过七天,请填写正确的开始时间和结束时间';
}
elseif ($num_iid == "" || $detail_url == "" || $title == "" || $pic_url == "" || $price == "" || $coupon_price == "" || intval($coupon_price)==0)
{
$createMessage = "失败!请把商品信息填写完整,星号为必填项!!";
}
else
{
$sql1 = 'SELECT * FROM `jae_goods` WHERE `num_iid`="' . $num_iid . '" OR `title`="' . $title . '"';
$rs1 = $pdo->query($sql1);
$row1 = $rs1->fetchAll(); //è?μ??ùóD????
$sql2 = 'SELECT * FROM `jae_goods` WHERE `num_iid`="' . $num_iid . '" OR `title`="' . $title . '"';
$rs2 = $pdo->query($sql2);
$row2 = $rs2->fetchAll(); //è?μ??ùóD????
if (count($row1)+count($row2) == 0)
{
if (rRuleUrl($detail_url) && rRuleNum($num_iid) && rRulePrice($price) && rRulePrice($coupon_price))
{
$datetime = date("Y-m-d H:i:s");
$sql = 'INSERT INTO `jae_goods` SET `num_iid`="' . $num_iid . '", `title`="' . $title .
'", `pic_url`="' . $pic_url . '", `detail_url`="' . $detail_url . '", `shop_url`="' . $shop_url . '", `price`="' . $price .
'", `coupon_price`="' . $coupon_price . '", `num`="' . $num . '", `userid`="' . $memberinfo[userid] . '", `create_time`="' . time() .
'", `description`="' . $description . '", `category_id`="' . $category_id .
'", `end_time`="' . $end_time . '", `freight_payer`="' . $freight_payer .
'", `nick`="' . $nick . '", `begin_time`="' . $begin_time . '", `pindao_id`="' . $pindao_id . '"';
$count = $pdo->exec($sql);
if ($count > 0)
{
$createMessage = "新增成功";
}
else
{
echo $sql;
$createMessage = "添加失败";
}
}
else
{
if (!rRuleUrl($detail_url))
$createMessage.='商品链接url填写不规范,带http://模式<br>';
elseif (!rRuleNum($num_iid))
$createMessage.='商品id填写不规范,数字模式<br>';
elseif (!rRulePrice($price))
$createMessage.='商品价格填写不规范,小数模式:10.00<br>';
elseif (!rRulePrice($coupon_price))
$createMessage.='促销价格填写不规范,小数模式:10.00<br>';
}
}
else
{
$createMessage = "商品已经存在【同一id或者同一标题】!!";
}
}
}
include template('member','goods_apply');
}
public function goods_manage (){
$memberinfo = $this->memberinfo;
$manage=$_GET['manage']?$_GET['manage']:'refuse';
if ($_GET['manage']=='pass')
{$data=$this->goods_db->listinfo("userid='$memberinfo[userid]' AND status=1 ","id DESC",$page,10);}
elseif ($_GET['manage']=='check')
{ $data=$this->goods_db->listinfo("userid='$memberinfo[userid]' AND status=0 ","id DESC",$page,10);}
else if ($_GET['manage']=='refuse')
{$data=$this->goods_db->listinfo("userid='$memberinfo[userid]' AND status=-1 ","id DESC",$page,10);}
include template('member','goods_manage');
}
public function apply_task (){
$memberinfo = $this->memberinfo;
include template('member','apply_task');
}
public function delete (){
$memberinfo = $this->memberinfo;
$_GET['id'] = intval($_GET['id']);
$this->goods_db->delete('id='.$_GET['id'].' AND userid ='.$memberinfo['userid'] );
showmessage(L('operation_success'));
header('location:/index.php?m=member&c=index&a=goods_manage');
}
public function edit (){
$memberinfo = $this->memberinfo;
$pindaoArr = rGetPindaoArr();
$categoryArr = rGetCategoryArr();
if(isset($_POST['dosubmit'])) {
$id = intval($_GET['id']);
$data=$_POST['info'];
$data['status']=0;
$this->goods_db->update($data,'id='.$id.' AND userid ='.$memberinfo['userid'] );
$msg="修改成功,请等待审核";
$r=$this->goods_db->get_one('id='.$id.' AND userid ='.$memberinfo['userid'] );
if($r) extract($r);
include template('member','goods_edit');
//showmessage(L('operation_success'));
//include template('member','login');
} else {
$id = intval($_GET['id']);
$r=$this->goods_db->get_one('id='.$id.' AND userid ='.$memberinfo['userid'] );
if($r) extract($r);
include template('member','goods_edit');
}
}
}
<file_sep>/jae/modules/point/point_set.php
<?php
defined('IN_JAE') or exit('No permission resources.');
defined('IN_ADMIN') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
jae_base::load_app_func('global','admin');
class point_set extends admin {
public function __construct() {
parent::__construct();
$this->db =jae_base::load_sys_class('mysql');
$this->table='jae_point_set';
$this->menuid=36;
}
public function init () {
$where=1;
$page=$_GET['page'];
$data=$this->db->listinfo("*",$this->table,$where,"id DESC",$page,1000);
$pages=$this->db->pages;
include $this->admin_tpl('point_set');
}
function add() {
if(isset($_POST['dosubmit'])) {
$data=$_POST['info'];
$this->db->insert($data,$this->table);
include $this->admin_tpl('weblink_add');
showmessage(L('add_success'));
} else {
include $this->admin_tpl('point_set_add');
}
}
function delete() {
$_GET['id'] = intval($_GET['id']);
$this->db->delete($this->table,'id='.$_GET['id']);
showmessage(L('operation_success'));
}
function edit() {
if(isset($_POST['dosubmit'])) {
$id = intval($_POST['id']);
$data=$_POST['info'];
$this->db->update($data,$this->table,'id='.$id);
showmessage(L('operation_success'));
include $this->admin_tpl('point_set_edit');
} else {
$id = intval($_GET['id']);
$r=$this->db->get_one('*',$this->table,'id='.$id);
if($r) extract($r);
include $this->admin_tpl('point_set_edit');
}
}
function point_task(){
$m_db = jae_base::load_model('module_model');
$data = $m_db->get_one(array('module'=>'point'));//array('module'=>'prize')
$setting = string2array($data['setting']);
@extract($setting);
if(isset($_POST['dosubmit'])) {
$variable = $_POST['setting'];
//更新模型数据库,重设setting 数据.
foreach ($variable as $key => $value) {
$sets[$key]=$value;
}
$sets=new_html_special_chars($sets);
$set = array2string($sets);
setcache('point', $sets, 'commons');
$m_db->update(array('setting'=>$set), array('module'=>ROUTE_M));
showmessage(L('setting_updates_successful'));
} else {
include $this->admin_tpl('point_task');
}
}
//完善资料获取积分
function point_setinfo(){
if(isset($_POST['dosubmit'])) {
$variable = $_POST['setting'];
foreach ($variable as $key => $value) {
$sets[$key]=$value;
}
$sets=new_html_special_chars($sets);
$set = array2string($sets);
setcache('point_setinfo', $sets, 'commons');
showmessage(L('setting_updates_successful'));
} else {
$setting=getcache_sql('point_setinfo','commons');
@extract($setting);
include $this->admin_tpl('point_setinfo');
}
}
//point_invite 邀请会员赚积分
function point_invite(){
if(isset($_POST['dosubmit'])) {
$variable = $_POST['setting'];
foreach ($variable as $key => $value) {
$sets[$key]=$value;
}
$sets=new_html_special_chars($sets);
$set = array2string($sets);
setcache('point_invite', $sets, 'commons');
showmessage(L('setting_updates_successful'));
} else {
$setting=getcache_sql('point_invite', 'commons');
@extract($setting);
include $this->admin_tpl('point_invite');
}
}
}<file_sep>/caches/caches_template/default/prize/index_f.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head');
?>
<link href="/statics/css/prize.css" rel="stylesheet" type="text/css" />
<div class="game-wrap">
<div class="game-content clearfix">
<div class="period"><?php echo $setting['title']?> 只有在本馆填写了正确的收货地址的亲才能收到奖品哦! <a target="_blank" href="/index.php?m=member&c=index&a=setinfo" title="编辑我的收货地址">编辑我的收货地址>></a> </div>
<div class="info-wrap">
<!--中奖名单Begin -->
<div class="winner-list-wrap">
<div class="title">达人中奖榜</div>
<div class="winner-list-item-wrap" id="J_WinnerList" style="position: relative; ">
<ul class="j-winner-list" style="position: absolute; top: 0px; ">
<li class="clearfix ks-switchable-panel-internal224" style="display: block; ">
<?php foreach ($prize_data as $v){?>
<div class="winner-list-item">
<div class="nick"><?php echo str_cut(get_memberinfo($v['userid'],'username'),6,"****") ?></div>
<div class="prize" title="<?php echo $v['title']?>"><?php echo $v['title']?></div>
</div>
<?php }?>
</li>
</ul>
</div>
</div>
<!-- 中奖名单End -->
<!-- 我的奖品按钮Begin -->
<a target="_blank" class="my-prize-btn" href="/index.php?m=prize&c=index&a=my_prize" title="查看我的奖品">我的奖品>></a>
<!-- 我的奖品按钮End -->
</div>
<div class="lottery-wrap">
<div class="msg"></div>
<div id="J_Lottery" class="lottery-content">
<?php foreach ($prize_arr as $k=> $v){ $k=$k+1; ?>
<div class="tm-prize-item prize-<?php echo $k;?>" > <a target="_blank" href="<?php echo $v['url']?>"> <img src="<?php echo $v['picture']?>" class="prize-img" alt="<?php echo $v['title']?>" title="<?php echo $v['title']?>"> </a> </div>
<?php }?>
<a href="/index.php?m=prize&c=index&a=check" >
<div id="J_LotteryBtn" class="lotty-btn" >点击抽奖</div>
</a> </div>
<div class="rule-wrap"> <span class="rule-content">抽奖规则:每次抽奖使用<?php echo abs($setting['point'])?>个积分,每天抽奖次数不限! </span> <a target="_blank" href="/index.php?m=prize&c=index&a=rules" class="rule-more-btn">查看详细规则</a> </div>
</div>
</div>
</div>
<div class="page-rules page-content">
<div class="bcontent-wrap">
<div class="rules-content">
<h1>抽奖规则:</h1>
<div class="rules-list">
<?php echo htmlspecialchars_decode($rules['rules']);?>
</div>
</div>
</div>
</div>
<file_sep>/jae/modules/exchange/templates/exchange_add.tpl(2014-0422-2227--Administrator--2014-04-30-00,19,31).php
<?php include $this->admin_tpl('head','admin'); ?>
<font color="red"><?php echo $message;?></font>
<form name="form1" method="post" action="/admin.php?m=exchange&c=exchange&a=add&menuid=<?php $menuid?>" >
<table class="table_form contentWrap" cellpadding="0" cellspacing="0" border="0">
<tr>
<th width="145" align="right">
商品ID:
</td>
<td align="left">
<input class="input-text" type="text" name="numIid" value="<?php echo $numIid; ?>" size="80">
<input type="hidden" name="dopost" value="caiji">
<input type="submit" class="button" value="获取">
</td>
</tr>
</table>
</form>
<form name="form2" method="post" action="/admin.php?m=exchange&c=exchange&a=add">
<table class="table_form" cellpadding="0" cellspacing="0" border="0">
<tr>
<th width="145">
*商品ID(如果是采集的请不要更改):
</th>
<td>
<input class="input-text" type="text" name="info[num_iid]" value="<?php echo $num_iid; ?>">
</td>
<td rowspan="13" style="vertical-align:top;align:center;">
<a target="_blank" href="<?php echo $detail_url; ?>"><img border="0" src="<?php echo $pic_url; ?>" width="200" height="200" /></a>
</td>
</tr>
<tr>
<th width="145">*上线时间段:</th>
<td>
<ul>
<li>
<label class="tit" for="J_DepDate">开始时间:</label>
<input name="info[begin_time]" class="kg_datePicker input-text" type="text" value="<?php echo date('Y-m-d H:i:s', time()); ?>"/>
</li>
<li>
<label class="tit" for="J_RetDate">结束时间:</label>
<input name="info[end_time]" class="kg_datePicker input-text" type="text" value="<?php echo date('Y-m-d H:i:s', time()+604800); ?>"/>
</li>
</ul>
</td>
</tr>
<tr>
<th width="145">*商品链接:</th>
<td><input class="input-text" type="text" name="info[detail_url]" size="50" value="<?php echo $detail_url; ?>"></td>
</tr>
<tr>
<th width="145">*商品标题:</th>
<td><input class="input-text" type="text" name="info[title]" size="50" value="<?php echo $title; ?>"></td>
</tr>
<tr>
<th width="145">*商品图片:</th>
<td><input class="input-text" type="text" name="info[pic_url]" size="50" value="<?php echo $pic_url; ?>"></td>
</tr>
<tr>
<th width="145">*包邮:</th>
<td>
<select name="info[freight_payer]">
<option<?php if($freight_payer=='seller'){?> selected="selected"<?php }; ?> value="seller">是</option>
<option<?php if($freight_payer=='buyer'){?> selected="selected"<?php }; ?> value="buyer">否</option>
</select>
</tr>
<tr>
<th width="145">*商家昵称:</th>
<td><input class="input-text" type="text" name="info[nick]" size="50" value="<?php echo $nick; ?>"></td>
</tr>
<tr>
<th width="145">*商品原价:</th>
<td><input class="input-text" type="text" name="info[price]" size="50" value="<?php echo $price; ?>"></td>
</tr>
<tr>
<th width="145">*商品现价:</th>
<td><input class="input-text" type="text" name="info[coupon_price]" value=""></td>
</tr>
<tr>
<th width="145">*兑换积分:</th>
<td><input class="input-text" type="text" name="info[point]" value=""></td>
</tr>
<tr>
<th width="145">*商品数量:</th>
<td><input class="input-text" type="text" name="info[num]" size="50" value="<?php echo $num; ?>"></td>
</tr>
<tr>
<th width="145">卖点描述:</th>
<td>
<textarea style="width:350px;height:80px" name="description"></textarea>
</td>
</tr>
</table>
<div class="btns"><input type="submit" id="dosubmit" class="button" name="dosubmit" value="提交"></div>
</form>
<?php include $this->admin_tpl('foot','admin');?><file_sep>/caches/caches_template/default/prize/my_prize.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php
include template('content','head');
?>
<link href="/statics/css/member.css" rel="stylesheet" type="text/css" />
<div class="blank"></div>
<div class="wrap">
<dl class="ui-tab clearfix" id="">
<dt>我的奖品</dt>
<!-- <dd data-type="all" class="j_nativeHistory all <?php if($trad=='all') echo "select"?> " data-template=""><a href="/index.php?m=point&c=index&a=sign&trad=all">积分明细</a></dd>
<dd data-type="income" class="j_nativeHistory income <?php if($trad=='income') echo "select"?>" data-template="/point/detail/income"><a href="/index.php?m=point&c=index&a=sign&trad=income ">积分收入</a></dd>
<dd data-type="used" class="j_nativeHistory used <?php if($trad=='used') echo "select"?>" data-template="/point/detail/used"><a href="/index.php?m=point&c=index&a=sign&trad=used">积分支出</a></dd>
<dd data-type="expired" class="j_nativeHistory expired" data-template="/point/detail/expired"><a href="/index.php?m=member&c=index&a=point_task">积分任务说明</a></dd>
<dd data-type="freezed" class="j_nativeHistory freezed" data-template="/point/detail/freezed">冻结积分</dd>-->
</dl>
<div class="border">
<div class="pd20">
<div class="content">
<!-- point .summary END -->
<div class="detail">
<div class="masthead clearfix"><span class="why">奖品名称</span><span class="what">奖品状态</span><span class="when">日期</span><span class="notes">备注</span></div>
<div id="J_pointDetail">
<ul class="item-list" id="J_item-list">
<?php foreach ($data as $v){?>
<li class="item clearfix">
<div class="why"><a class="img" href="<?php echo $v['url']?>" target="_blank"><img src="<?php echo $v['picture']?>" width="60" height="60" alt="小积分抽大奖"></a><a class="title" href="<?php echo $v['url']?>" target="_blank"><?php echo $v['title']?></a><span class="order-number">编号:<?php echo $v['id']?></span></div>
<div class="express"><span class=" plus "><?php if($v['status']==0) {echo "未发送" ;} else { echo "已经发送"; echo $v['express_name'].":<br>". $v['express_num'] ;}?></span></div>
<div class="when"><?php echo date('Y-m-d H:i:s',$v['date'])?></div>
<div class="notes"><?php echo $v['description']?></div>
</li>
<?php }?>
</ul>
</div>
<div id="J_pointError" class="hidden error"></div>
<div id="J_pointPager" class="pages">
<?php echo $pages;?>
</div>
</div>
<!-- point .detail END --></div>
<div class="blank"></div>
<div class="m_main"> </div>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<div class="blank"></div>
<file_sep>/jae/modules/admin/templates/site_list.tpl.php
<?php
defined('IN_JAE') or exit('No permission resources.');
include $this->admin_tpl('head');
?>
<div class="pad_10">
<div class="table-list">
<table width="100%" cellspacing="0">
<tr class="thead">
<th width="80">Siteid</th>
<th><?php echo L('site_name')?></th>
<th><?php echo L('site_domain')?></th>
<th ><?php echo L('template')?></th>
<th width="150"><?php echo L('operations_manage')?></th>
</tr>
<tbody>
<?php
foreach($list as $v){
?>
<tr >
<td width="80" align="center"><?php echo $v['siteid']?></td>
<td><?php echo $v['name']?></td>
<td><?php echo $v['domain']?></td>
<td><?php foreach ($template_list as $key=> $val){ if($val['dirname']== $v['template']) { echo $val['name']; } } ?></td>
<td ><a href="/admin.php?m=admin&c=site&a=set_site&siteid=<?php echo $v['siteid']?>&menuid=<?php echo $menuid?>"><?php echo L('设成当前站点')?></a> |<a href="/admin.php?m=admin&c=site&a=edit&siteid=<?php echo $v['siteid']?>&menuid=<?php echo $menuid?>"><?php echo L('edit')?></a> |
<?php if($v['siteid']!=1) { ?><a href="?m=admin&c=site&a=del&siteid=<?php echo $v['siteid']?>" onclick="return confirm('<?php echo new_addslashes(htmlspecialchars(L('confirm', array('message'=>$v['name']))))?>')"><?php echo L('delete')?></a><?php } else { ?><font color="#cccccc"><?php echo L('delete')?></font><?php } ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
<div id="pages"><?php echo $pages?></div>
<?php
include $this->admin_tpl('foot');
?><file_sep>/jae/libs/classes/user.class.php
<?php
/**
* user.class.php 数据模型基类
*
* @copyright (C) 20013-2014 JAE
* @license http://www.ehoneycomb.com/
* @lastmodify 2014-6-7
* @淘宝网获取头像和混肴昵称
*/
class User {
public $userId;
public $nick;
}
class context {
function getbrowser(){
return new User();
}
function getSiteOwner(){
return new User();
}
}
//当前用户头像用法
$browser=$context->getbrowser();
$nick=$browser->nick;
//echo '<img src="/_RS/user/picture?mixUserNick='.urlencode($nick,"UTF-8").'" /> ';
?><file_sep>/upgrade/20140704.sql
ALTER TABLE `jae_block` ADD COLUMN `siteid` smallint(5) UNSIGNED default '0' AFTER `id`;
UPDATE jae_site SET date='20140704' ;
UPDATE jae_site SET version='141';<file_sep>/statics/js/login.json.js
var $=jQuery;
// $getJSON('/count.php?callback=?',{},function(data){console.log(data)});
//$get('/count.php?callback=jsonp',{"data":1},function(data){console.log(data.status)});
$ajax({
//指定 callback 的参数,请求 url 会生成 "url?callback={$jsonpCallback}"
jsonpCallback: "jsonp",
//指定 callback 的别名,请求url会生成 "url?{$jsonp}=jsonp123456", 默认就是callback
jsonp: "callback",
//url 地址
url: "/api.php?op=login",
//string|json发起请求需要附加的数据,默认为 null
//data: {"p": 1,"encodeCpt":encodeURIComponent("中文1测试成功"),"encode":encodeURI("中文2测试成功")},
data: {"p": 1,"encodeCpt":encodeURIComponent("中文1测试成功"),"encode":encodeURI("中文2测试成功")},
// contentType: "application/x-www-form-urlencoded; charset=utf-8",
// function请求成功的回调,回调参数为 data(内容),textStatus(请求状态),xhr(ajax对象)
success: function (data, textStatus, xhr) {
$(".member_sign a").html(data.login) ; $(".member_points a").html(data.point) ; $(".tips").html(data.tips) ;
},
//function 请求完成的回调,在 success 调用之后触发,参数同 success
complete: function (data) {
},
// 请求错误时的回调
error: function () {
console.log("KissyIO Error");
},
//发送请求类型是jsonp
dataType: "jsonp"
});
<file_sep>/api.php
<?php
define('JAE_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR);
if($_GET['m']=='admin') exit('No permission resources.');
include JAE_PATH.'/jae/base.php';
$op = isset($_GET['op']) && trim($_GET['op']) ? trim($_GET['op']) : exit('Operation can not be empty');
if (isset($_GET['callback']) && !preg_match('/^[a-zA-Z_][a-zA-Z0-9_]+$/', $_GET['callback'])) unset($_GET['callback']);
if (!preg_match('/([^a-z_]+)/i',$op) && file_exists(JAE_PATH.'api/'.$op.'.php')) {
include JAE_PATH.'api/'.$op.'.php';
} else {
exit('API handler does not exist');
}
?><file_sep>/jae/modules/admin/templates/cache_all.tpl.php
<style type="text/css">
.sbs{}
.sbul{margin:10px;}
.sbul li{line-height:30px;}
.button{margin-top:20px;}
.subnav,.ifm{display:none;}
</style>
<?php
defined('IN_ADMIN') or exit('No permission resources.');
include $this->admin_tpl('head','admin');?>
<div class="pad-10">
<form action="?m=admin&c=cache_all&a=init&pc_hash=<?php echo $_SESSION['pc_hash']?>" target="cache_if" method="post" id="myform" name="myform">
<input type="hidden" name="dosubmit" value="1">
<div class="col-2">
<h6><?php echo L('tip_zone')?></h6>
<div class="sbs" id="update_tips" style="height:360px; overflow:auto;">
<ul id="file" class="sbul">
</ul>
</div>
</div>
<!-- <input name="dosubmit" type="submit" class="dialog" id="dosubmit" value="<?php echo L('start_update')?>" onclick="$('#file').html('');return true;" class="button"> -->
</form>
</div>
<?php
include $this->admin_tpl('foot','admin');?><file_sep>/demo/message.php
<?php
include("top/RequestCheckUtil.php");
include("top/TmcMessagesConsumeRequest.php");
include("top/topclient.php");
include("top/TmcMessagesConfirmRequest.php");
//实例化TopClient类
$c = new TopClient;
$c->appkey = "1021689808";
$c->secretKey = "sandboxfce138a560854d453bc4a1544";
$c->gatewayUrl = "http://gw.api.tbsandbox.com/router/rest";
// $c->format = "json";
//实例化具体API对应的Request类
$req = new TmcMessagesConsumeRequest;
$req->setGroupName("vip_user");
$req->setQuantity(10);
$resp = $c->execute($req);
print_r($resp);
for ($i=0; $i<count($resp->messages->tmc_message); $i++)
{
$messages_ids.=$resp->messages->tmc_message[$i]->id.",";
}
$messages_ids = substr($messages_ids,0,strlen($messages_ids)-1);
/*
* do something
*
* */
//echo $messages_ids;
//确认消息
$req2 = new TmcMessagesConfirmRequest;
$req2->setSMessageIds($messages_ids);
$resp2 = $c->execute($req2);
// stdClass Object ( [messages] => stdClass Object ( [tmc_message] => Array ( [0] => stdClass Object ( [user_id] => 0 [content] => {"buyer_nick":"钟01sFPHkvIUn+0iz7SFXIznPxzFidsYny1qVs/ZHI2U3s4\u003d","auction_id":36261151986,"paid_fee":990,"auction_count":1,"auction_title":"韩国风味 水果茶 蜜炼蜂蜜柚子茶248g 玻璃瓶子 买2瓶送勺子包邮"} [id] => 7112500108330773705 [pub_time] => 2014-04-11 23:38:23 [pub_app_key] => 12497914 [topic] => jae_trade_PaidSuccessed ) ) ) )
?><file_sep>/demo/dir.php
<?php
$pdo = new PDO();
$count = $pdo->exec("INSERT INTO `jae_menu` (`name`, `language`, `parentid`, `m`, `c`, `a`, `data`, `listorder`, `display`, `project1`, `project2`, `project3`, `project4`, `project5`) VALUES
('扩展', 'extend', 0, 'admin', 'extend', 'init', '', 10, '1', 1, 1, 1, 1, 1);");
$appLog->info("洞彻洞彻洞彻洞彻洞彻");
$targetdir = './';
$dir=dir($targetdir);
while($entry=$dir->read())
{
if($entry == '.' || $entry == '..') continue;
echo $entry.'<br>';
}
?>
<file_sep>/jae/modules/admin/templates/channel_edit.tpl.php
<?php include $this->admin_tpl('head');?>
<form name="myform" id="myform" action="/admin.php?m=admin&c=channel&a=edit" method="post">
<table width="100%" class="table_form contentWrap">
<tbody><tr>
<th width="250"> 频道名称(唯一):</th>
<td><input style="width:300px;" type="text" name="info[name]" value="<?php echo $name?>" id="language" class="input-text"></td>
</tr>
<tr>
<th> 系统调用别名(英文 系统识别用 唯一):</th>
<td><input style="width:300px;" type="text" name="info[alias]" value="<?php echo $alias?>" id="language" class="input-text"><div id="languageTip" class="onShow"></div></td>
</tr>
<tr>
<th> URL链接:</th>
<td> <input style="width:300px;" type="text" name="info[url]" value="<?php echo $url?>" id="language" class="input-text"><div id="languageTip" class="onShow"></div></td>
</tr>
<tr>
<th>状态:</th>
<td><input type="checkbox" name="info[status]" value="1" <?php if( $status==1){echo "checked='checked'";}?> ><div id="nameTip" class="onShow"></div></td>
</tr>
</tbody></table>
<!--table_form_off-->
<div class="btns"><input name="id" type="hidden" value="<?php echo $id?>"><input type="submit" id="dosubmit" class="button" name="dosubmit" value="提交"></div>
</form>
<?php include $this->admin_tpl('foot');?><file_sep>/jae/modules/admin/category.php
<?php
defined('IN_JAE') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
jae_base::load_sys_class('form','',0);
class category extends admin {
function __construct() {
parent::__construct();
$this->category_db = jae_base::load_model('category_model');
$this->db= jae_base::load_model('category_model');
$this->menuid=84;
$this->siteid = $this->get_siteid();
}
function init () {
$types = array(0 => L('category_type_system'),1 => L('category_type_page'),2 => L('category_type_link'));
$models = getcache('model','commons');
$page=$_GET['page'];
$data=$this->category_db->listinfo($where,$order = 'listorder ASC',$page, $pages = '12');
$pages=$this->category_db->pages;
include $this->admin_tpl('category_list');
}
function add() {
$models = getcache('model','commons');
$type = $_GET['type'];
if(isset($_POST['dosubmit'])) {
$data=$_POST['info'];
//$data['url']=$models[$data['modelid']['url'];
$data['siteid']=$this->siteid;
$data['module']="content";
$data['setting']=array2string($models[$data['modelid']]);
$this->category_db->insert($data);
$insert_id=$this->category_db->insert_id();
if ($data['type']== 0 ){$this->update_url($insert_id);}
$this->cache();
showmessage(L('add_success'));
include $this->admin_tpl('category_add');
} else {
if($type==0) {
$exists_model = false;
$models = getcache('model','commons');
foreach($models as $_m) {
if($this->siteid == $_m['siteid']) {
$exists_model = true;
break;
}
}
if(!$exists_model) showmessage(L('please_add_model'),'?m=content&c=sitemodel&a=init&menuid=59',5000);
include $this->admin_tpl('category_add');
} elseif ($type==1) {
include $this->admin_tpl('category_page_add');
} else {
include $this->admin_tpl('category_link');
}
}
}
function delete() {
$_GET['catid'] = intval($_GET['catid']);
$this->category_db->delete('catid='.$_GET['catid']);
showmessage(L('operation_success'));
}
function edit() {
$models = getcache('model','commons');
if(isset($_POST['dosubmit'])) {
$catid = intval($_POST['catid']);
$data=$_POST['info'];
$this->category_db->update($data,'catid='.$catid);
if ($data['type']== 0 ){$this->update_url($catid);}
$this->cache();
showmessage(L('operation_success'));
include $this->admin_tpl('category_edit');
} else {
$catid = intval($_GET['catid']);
$r=$this->category_db->get_one('catid='.$catid);
if($r) extract($r);
//$type = $_GET['type'];
if($type==0) {
include $this->admin_tpl('category_edit');
} elseif ($type==1) {
include $this->admin_tpl('category_page_edit');
} else {
include $this->admin_tpl('category_link_edit');
}
}
}
function listorder() {
if(isset($_POST['dosubmit'])) {
foreach($_POST['listorders'] as $catid => $listorder) {
$listorder = !empty($listorder) ? $listorder : '0';
$this->category_db->update(array('listorder'=>$listorder),'catid='.$catid);
}
showmessage(L('operation_success'));
} else {
showmessage(L('operation_failure'));
}
}
/**
* 更新栏目链接地址
*/
private function update_url($catid) {
$catid = intval($catid);
if (!$catid) return false;
$data = array('url' =>'/index.php?m=content&c=index&a=lists&catid='.$catid);
$where = array('catid' => $catid );
$this->category_db->update($data,'catid='.$catid);
// $url = jae_base::load_app_class('url', 'content'); //调用URL实例
// return $url->category_url($catid);
}
/**
* 更新缓存并修复栏目
*/
public function public_cache() {
//$this->repair();
$this->cache();
showmessage(L('operation_success'),'/admin.php?m=admin&c=category&a=init&module=admin&menuid=83');
}
/**
* 更新缓存
*/
public function cache() {
$categorys = array();
$models = getcache('model','commons');
foreach ($models as $modelid=>$model) {
$datas = $this->db->select(array('modelid'=>$modelid),'catid,type,items',10000);
$array = array();
foreach ($datas as $r) {
if($r['type']==0) $array[$r['catid']] = $r['items'];
}
setcache('category_items_'.$modelid, $array,'commons');
}
$array = array();
$categorys = $this->db->select('`module`=\'content\'','catid,siteid',20000,'listorder ASC');
foreach ($categorys as $r) {
$array[$r['catid']] = $r['siteid'];
}
setcache('category_content',$array,'commons');
$categorys = $this->categorys = array();
$this->categorys = $this->db->select(array('siteid'=>$this->siteid, 'module'=>'content'),'*',10000,'listorder ASC');
foreach($this->categorys as $r) {
unset($r['module']);
$setting = string2array($r['setting']);
/*$r['create_to_html_root'] = $setting['create_to_html_root'];
$r['ishtml'] = $setting['ishtml'];
$r['content_ishtml'] = $setting['content_ishtml'];
$r['category_ruleid'] = $setting['category_ruleid'];
$r['show_ruleid'] = $setting['show_ruleid'];
$r['workflowid'] = $setting['workflowid'];
$r['isdomain'] = '0';
if(!preg_match('/^(http|https):\/\//', $r['url'])) {
$r['url'] = siteurl($r['siteid']).$r['url'];
} elseif ($r['ishtml']) {
$r['isdomain'] = '1';
}*/
$categorys[$r['catid']] = $r;
}
setcache('category_content_'.$this->siteid,$categorys,'commons');
return true;
}
}
?><file_sep>/caches/caches_template/default/content/foot.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><!-- µ×²¿1 -->
<div class="bder">
<div class="wrap">
<div class="dilo">
<img height="70" src="<?php echo $site_setting['foot_logo'] ?>">
</div>
<div class="tle">
<div class="ti">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=23 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
<ul>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=23 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><li><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></li>
<?php }
?>
</ul>
</div>
<div class="tle">
<div class="ti">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=23 ORDER BY listorder,id ASC LIMIT 4,1 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
<ul>
<li>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=23 ORDER BY listorder,id ASC LIMIT 5,3 ');
foreach ($result as $v) {
?><li><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></li>
<?php }
?>
</ul>
</div>
<div class="tle">
<div class="ti">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=23 ORDER BY listorder,id ASC LIMIT 8,1 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
<ul>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=23 ORDER BY listorder,id ASC LIMIT 9,3 ');
foreach ($result as $v) {
?><li><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></li>
<?php }
?>
</ul>
</div>
<div class="tle" style="margin:0px;">
<div class="ti">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=23 ORDER BY listorder,id ASC LIMIT 12,1 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
<ul>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=23 ORDER BY listorder,id ASC LIMIT 13,3 ');
foreach ($result as $v) {
?><li><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></li>
<?php }
?>
</ul>
</div>
<div class="wx">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=23 ORDER BY listorder,id ASC LIMIT 16,1 ');
foreach ($result as $v) {
?><img src="<?php echo $v['picture'];?>" />
<?php }
?>
</div>
<div class="shux"></div>
<div class="tle jaelx">
<div class="ti">
</div>
<ul>
<li></li>
<li></li>
</ul>
</div>
</div>
</div>
<!-- µ×²¿ end -->
<file_sep>/jae/modules/weblink/templates/weblink_type_list.tpl.php
<?php include $this->admin_tpl('head','admin');?>
<form name="myform" action="/admin.php?m=admin&c=focus&a=listorder" method="post">
<div class="pad-lr-10">
<div class="table-list">
<table width="100%" cellspacing="0" class="table_form">
<tbody>
<tr class="thead">
<th width="30"><?php echo L('id');?></th>
<th width="30">名称</th>
<th width="80">描述</th>
<th width="80">所属站点</th>
<th width="200" align=""><?php echo L('operations_manage');?></th>
</tr>
<?php foreach ($data as $r){?>
<tr>
<td align=""><?php echo $r['typeid'];?></td>
<td align=""><?php echo $r['name'];?> </td>
<td align=""><?php echo $r['description'];?></td>
<td align=""><?php echo $sitelist[$r['siteid']]['name'];?></td>
<td align=""><?php echo '<a href="/admin.php?m=weblink&c=weblink&a=add&typeid='.$r['typeid'].'&menuid=59">添加子页面链接</a> | <a href="/admin.php?m=weblink&c=weblink_type&a=edit&typeid='.$r['typeid'].'&menuid='.$menuid.'">'.L('modify').'</a> | <a href="/admin.php?m=weblink&c=weblink_type&a=delete&typeid='.$r['typeid'].'&menuid='.$menuid.'">'.L('delete').'</a> ';?></td>
</tr>
<?php }?>
</tbody>
</table>
<div class="btns"><input type="submit" class="button" name="dosubmit" value="<?php echo L('listorder')?>" /></div> </div>
</div>
</div>
</form>
<div class="pages"><?php echo $pages;?></div>
<?php include $this->admin_tpl('foot','admin');?><file_sep>/jae/modules/upgrade/index.php
<?php
defined('IN_JAE') or exit('No permission resources.');defined('IN_ADMIN') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
class index extends admin {
public function __construct() {
$this->db= jae_base::load_model('member_model');
parent::__construct();
}
public function init() {
$targetdir = JAE_PATH.'upgrade'.DIRECTORY_SEPARATOR;
$siteinfo=siteinfo(get_siteid());
$dir=dir($targetdir);
while($entry=$dir->read())
{
if($entry == '.' || $entry == '..') continue;
$date=substr($entry, 0, 8);
if($date > $siteinfo['date']) {$pathlist[]=$entry;}
}
if(isset($_POST['dosubmit'])) {
sort($pathlist);
foreach ($pathlist as $key => $value) {
$sql_files=file_get_contents($targetdir.$value);
$sqls=explode(';', $sql_files);
foreach ($sqls as $exec) {
$this->db->query($exec);
}
}
showmessage(L('operation_success'),'/admin.php?m=upgrade&c=index&a=init&menuid=103');
}
include $this->admin_tpl('upgrade_index','upgrade');
}
}
?><file_sep>/caches/caches_template/default/seckill/index.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head'); ?>
<link href="/statics/css/seckill.css" rel="stylesheet" type="text/css" />
<div style=" background:<?php echo $page_setting['bg_color']?>; display:block" >
<div class="i_step i_step1" style="height: 440px;
background: url(<?php echo $page_setting['bg_img']?>) no-repeat center 0;" >
<div style="width: 990px;margin: 0 auto;position: relative;"><a target="_blank" href="/index.php?m=seckill&c=index&a=rules"> <img style="display:block" src="<?php echo $page_setting['img']?>"></a></div>
</div>
<div class="mslbgz">
<?php echo htmlspecialchars_decode($page_setting['rules'])?>
</div>
<div class="blank"></div>
<?php foreach($data as $v){?>
<div class="detail-main" >
<div class="normal-pic-wrapper floatleft" data-spm="ne" data-spm-max-idx="2">
<div class="normal-pic"> <a href="http://item.taobao.com/item.htm?id=<?php echo $v['num_iid'];?>" target="_blank" data-spm-anchor-id="608.7065813.ne.1"> <img data-ks-lazyload="<?php echo $v['pic_url'];?>" width="300" height="300" class="J_zoom "></a> </div>
</div>
<div class="detail-status floatleft ">
<div class="main-box avil">
<div class="name-box">
<h2 class="name"> <?php echo $v['title'];?></h2>
</div>
<div class="description"><h2 class="name" style="color: #CC0000; font-weight:bold;"> 开始时间:<?php echo date("Y-m-d H:i:s",$v['begin_time']);?></h2><?php echo $v['description'];?></div>
<div class="status-banner J_juBuyBtns "> <span class="currentPrice floatleft"> <?php echo $v['point'];?> <small>积分</small> </span>
<div class="floatleft">
<div class="discount"> 节省 <small></small> </div>
<del class="originPrice">¥ <?php echo $v['price'];?></del> </div>
<form class="J_BuySubForm" data-ccb="0" data-ques="0" action="/index.php?m=order&c=index&a=seckill_submit_pre" method="post">
<input name="_tb_token_" type="hidden" value="<PASSWORD>">
<input type="hidden" name="_input_charset" value="utf-8">
<input type="hidden" name="num_iid" value="<?php echo $v['num_iid'];?>">
<input type="hidden" name="id" value="<?php echo $v['id'];?>">
<input type="hidden" name="module" value="seckill">
<input type="hidden" name="auction_num" value="1">
<input type="submit" class="buyaction J_BuySubmit" title="马上抢" value="马上抢">
</form>
</div>
<div class="time-banner">
<p class="tit"></p>
<div class="J_TWidget ju-spltimer" data-widget-type="Countdown" data-widget-config="{'endTime': '<?php if($v['num']==0){ echo 0;} else{ if($v['begin_time']<SYS_TIME) { echo ($v['end_time']- SYS_TIME)*1000 ;} else { echo ($v['begin_time']- SYS_TIME)*1000 ; } } ?>', 'interval': 1000, 'timeRunCls': '.ks-countdown-run','timeUnitCls':{'d': '.ks-d','h': '.ks-h','m': '.ks-m','s': '.ks-s','i': '.ks-i'},'minDigit': 1,'timeEndCls': '.ks-countdown-end'}">
<!-- 倒计时结束时隐藏-->
<!--可以写多个 -->
<div class="ks-countdown-run">
距 <span><?php if($v['begin_time']<SYS_TIME) { echo "结束" ;} else { echo "开始" ; }?></span>还有
<span class="ks-d"></span>天
<span class="ks-h"></span>小时
<span class="ks-m"></span>分
<!-- 如果有0.1秒级别的变化建议以gif背景图片的形式变化 -->
<span class="ks-s"></span>秒
<span class="buy"><a target="_blank" href="http://item.taobao.com/item.htm?id=<?php echo $v['num_iid'];?>">直接去购买</a></span>
</div>
<!-- 倒计时结束时显示-->
<!--可以写多个 -->
<?php if ($v['num']==0){ ?>
<div class=" sell_end" style="">
<img src="/statics/images/sell_end.png">
</div>
<?php }?>
</div>
</div>
</div>
</div>
<div class="invite_copy">
快来邀请您的朋友成为本馆会员,通过下面的专属链接邀请朋友成为会员,每成功邀请1位可以获得<span><?php $data=getcache_sql('point_invite','commons'); echo $data['point']?></span>积分哟!
<div class="fxcp"><textarea><?php echo $data['content_url']."\r\n".$siteinfo['domain']."index.php?fromuserid=".$memberinfo['userid'] ; ?></textarea></div>
</div>
<div class="clear"></div>
</div>
<div class="blank"></div>
<?php }?>
<div id="J_pointPager" class="pages">
<?php echo $pages;?>
</div>
<div class="blank"></div>
</div>
<file_sep>/jae/modules/position/position.php
<?php
defined('IN_JAE') or exit('No permission resources.');defined('IN_ADMIN') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
class position extends admin {
function __construct() {
parent::__construct();
$this->db = jae_base::load_model('position_model');
$this->db_data = jae_base::load_model('position_data_model');
$this->menuid=51;
}
function init () {
$sitelist=getcache('sitelist','commons');
$models = getcache('model','commons');
$page=$_GET['page'];
$data=$this->db->listinfo($where, $order = 'listorder DESC,posid DESC', $page, $pagesize = 20);
$pages=$this->db->pages;
include $this->admin_tpl('position_list');
}
function add() {
$sitelist=getcache('sitelist','commons');
$models = getcache('model','commons');
if(isset($_POST['dosubmit'])) {
$data=$_POST['info'];
$this->db->insert($data);
include $this->admin_tpl('position_add');
showmessage(L('add_success'));
} else {
include $this->admin_tpl('position_add');
}
}
function delete() {
$_GET['posid'] = intval($_GET['posid']);
$this->db->delete('posid='.$_GET['posid']);
showmessage(L('operation_success'));
}
function edit() {
$sitelist=getcache('sitelist','commons');
$models = getcache('model','commons');
if(isset($_POST['dosubmit'])) {
$posid = intval($_POST['posid']);
$data=$_POST['info'];
echo $this->db->update($data,'posid='.$posid);
showmessage(L('operation_success'),'/admin.php?m=position&c=position&a=init&menuid='.$this->menuid);
include $this->admin_tpl('position_edit');
} else {
$posid = intval($_GET['posid']);
$info=$this->db->get_one('posid='.$posid);
include $this->admin_tpl('position_edit');
}
}
/**
* 推荐位文章统计
* @param $posid 推荐位ID
*/
public function content_count($posid) {
$posid = intval($posid);
$where = array('posid'=>$posid);
$infos = $this->db_data->get_one($where, $data = 'count(*) as count');
return $infos['count'];
}
/**
* 移出推荐位文章列表
*/
public function public_item() {
if(isset($_POST['dosubmit'])) {
$items = count($_POST['items']) > 0 ? $_POST['items'] : showmessage(L('posid_select_to_remove'),HTTP_REFERER);
if(is_array($items)) {
$sql = array();
foreach ($items as $item) {
$_v = explode('-', $item);
$sql['id'] = $_v[0];
$sql['modelid']= $_v[1];
$sql['posid'] = intval($_POST['posid']);
$this->db_data->delete($sql);
$this->content_pos($sql['id'],$sql['modelid']);
}
}
showmessage(L('operation_success'),HTTP_REFERER);
} else {
$posid = intval($_GET['posid']);
$MODEL = getcache('model','commons');
$siteid = $this->get_siteid();
$CATEGORY = getcache('category_content_'.$siteid,'commons');
$page = $_GET['page'] ? $_GET['page'] : '1';
$pos_arr = $this->db_data->listinfo(array('posid'=>$posid,'siteid'=>$siteid),'listorder DESC', $page, $pagesize = 20);
$pages = $this->db_data->pages;
$infos = array();
foreach ($pos_arr as $_k => $_v) {
$r = string2array($_v['data']);
$r['catname'] = $CATEGORY[$_v['catid']]['catname'];
$r['modelid'] = $_v['modelid'];
$r['posid'] = $_v['posid'];
$r['id'] = $_v['id'];
$r['listorder'] = $_v['listorder'];
$r['catid'] = $_v['catid'];
//$r['url'] = go($_v['catid'], $_v['id']);
$key = $r['modelid'].'-'.$r['id'];
$infos[$key] = $r;
}
$big_menu = array('javascript:window.top.art.dialog({id:\'add\',iframe:\'?m=admin&c=position&a=add\', title:\''.L('posid_add').'\', width:\'500\', height:\'300\', lock:true}, function(){var d = window.top.art.dialog({id:\'add\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'add\'}).close()});void(0);', L('posid_add'));
include $this->admin_tpl('position_items');
}
}
/**
* 推荐位文章管理
*/
public function public_item_manage() {
if(isset($_POST['dosubmit'])) {
$posid = intval($_POST['posid']);
$modelid = intval($_POST['modelid']);
$id= intval($_POST['id']);
$pos_arr = $this->db_data->get_one(array('id'=>$id,'posid'=>$posid));
$array = string2array($pos_arr['data']);
$array['inputtime'] = strtotime($_POST['info']['inputtime']);
$array['title'] = trim($_POST['info']['title']);
$array['thumb'] = trim($_POST['info']['thumb']);
$array['description'] = trim($_POST['info']['description']);
$thumb = $_POST['info']['thumb'] ? 1 : 0;
$array = array('data'=>array2string($array),'synedit'=>intval($_POST['synedit']),'thumb'=>$thumb);
$this->db_data->update($array,array('id'=>$id,'posid'=>$posid));
showmessage(L('operation_success'));
} else {
$posid = intval($_GET['posid']);
$modelid = intval($_GET['modelid']);
$id = intval($_GET['id']);
if($posid == 0 ) showmessage(L('linkage_parameter_error'), HTTP_REFERER);
$pos_arr = $this->db_data->get_one(array('id'=>$id,'posid'=>$posid));
extract(string2array($pos_arr['data']));
$synedit = $pos_arr['synedit'];
$show_validator = true;
$show_header = true;
include $this->admin_tpl('position_item_manage');
}
}
/**
* 推荐位文章排序
*/
public function public_item_listorder() {
if(isset($_POST['posid'])) {
foreach($_POST['listorders'] as $_k => $listorder) {
$pos = array();
$pos = explode('-', $_k);
$this->db_data->update(array('listorder'=>$listorder),array('id'=>$pos[1],'catid'=>$pos[0],'posid'=>$_POST['posid']));
}
showmessage(L('operation_success'),HTTP_REFERER);
} else {
showmessage(L('operation_failure'),HTTP_REFERER);
}
}
/**
* 推荐位添加栏目加载
*/
function delete_item() {
$id = intval($_GET['id']);
$modelid = intval($_GET['modelid']);
$posid = intval($_GET['posid']);
$data=$this->db_data->delete(array('id'=>$id,'modelid'=>$modelid,'posid'=>$posid));
showmessage(L('operation_success'),HTTP_REFERER);
}
}
?><file_sep>/statics/js/admin_common.js
var $ = jQuery;
var url_forward=$('.showMsg').attr('data-url');
var ms=$('.showMsg').attr('data-url');
console.log(url_forward);
console.log(ms);
//setTimeout("redirect('url_forward');",ms);<file_sep>/upgrade/20140718.sql
ALTER TABLE `jae_weblink` ADD `siteid` SMALLINT(5) UNSIGNED NULL DEFAULT '0' AFTER `id`;
ALTER TABLE `jae_weblink_type` ADD `siteid` SMALLINT(5) UNSIGNED NULL DEFAULT '0' AFTER `typeid`;
UPDATE jae_site SET date='20140718' ;
UPDATE jae_site SET version='144';<file_sep>/jae/base.php
<?php
define('IN_JAE', true);
//JAE¿ò¼Ü·¾¶
define('JAE_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR);
if(!defined('JAE_PATH')) define('JAE_PATH', JAE_PATH.'..'.DIRECTORY_SEPARATOR);
//»º´æÎļþ¼ÐµØÖ·
define('CACHE_PATH', JAE_PATH.'caches'.DIRECTORY_SEPARATOR);
//Ö÷»úÐÒé
define('SITE_PROTOCOL', isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://');
//µ±Ç°·ÃÎʵÄÖ÷»úÃû
define('SITE_URL', (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''));
//À´Ô´
//define('SITE_IP', (isset($_SERVER["HTTP_CLIENT_IP"]) ?$_SERVER["HTTP_CLIENT_IP"] : ''));
define('HTTP_REFERER', isset($_SERVER['HTTP_REFERER']) ? htmlspecialchars_decode($_SERVER['HTTP_REFERER']) : '');
//ϵͳ¿ªÊ¼Ê±¼ä
//echo $time =strtotime(date('Y-m-d H:i:s'));
//define('SYS_START_TIME', $time);
date_default_timezone_set("Asia/Hong_Kong");
//echo date('Y-m-d H:i:s',$time);
//¼ÓÔØ¹«Óú¯Êý¿â
jae_base::load_sys_func('global');
jae_base::load_sys_func('extention');
jae_base::auto_load_func();
define('SITEID', get_siteid());
//ÉèÖñ¾µØÊ±²î
//function_exists('date_default_timezone_set') && date_default_timezone_set(jae_base::load_config('system','timezone'));
//µ±Ç°Ê±¼ä ¾«È·µ½Ãë
define('SYS_TIME', time());
//µ±Ç°Ê±¼ä ¾«È·µ½ºÁÃë
define('MICRO_TIME', microtime(true));
//echo SYS_TIME;
//¶¨ÒåÍøÕ¾¸ù·¾¶
define('WEB_PATH',jae_base::load_config('system','web_path'));
//js ·¾¶
define('JS_PATH',jae_base::load_config('system','js_path'));
//css ·¾¶
define('CSS_PATH',jae_base::load_config('system','css_path'));
//img ·¾¶
define('IMG_PATH',jae_base::load_config('system','img_path'));
//¶¯Ì¬³ÌÐò·¾¶
define('APP_PATH',jae_base::load_config('system','app_path'));
//
define('UPLOAD_PATH',jae_base::load_config('system','upload_path'));
//Ó¦Óþ²Ì¬Îļþ·¾¶
define('PLUGIN_STATICS_PATH',WEB_PATH.'statics/plugin/');
class jae_base {
/**
* ³õʼ»¯Ó¦ÓóÌÐò
*/
public static function creat_app() {
return self::load_sys_class('application');
}
/**
* ¼ÓÔØÏµÍ³Àà·½·¨
* @param string $classname ˈ̞
* @param string $path À©Õ¹µØÖ·
* @param intger $initialize ÊÇ·ñ³õʼ»¯
*/
public static function load_sys_class($classname, $path = '', $initialize = 1) {
return self::_load_class($classname, $path, $initialize);
}
/**
* ¼ÓÔØÓ¦ÓÃÀà·½·¨
* @param string $classname ˈ̞
* @param string $m Ä£¿é
* @param intger $initialize ÊÇ·ñ³õʼ»¯
*/
public static function load_app_class($classname, $m = '', $initialize = 1) {
$m = empty($m) && defined('ROUTE_M') ? ROUTE_M : $m;
if (empty($m)) return false;
return self::_load_class($classname, 'modules'.DIRECTORY_SEPARATOR.$m.DIRECTORY_SEPARATOR.'classes', $initialize);
}
/**
* ¼ÓÔØÊý¾ÝÄ£ÐÍ
* @param string $classname ˈ̞
*/
public static function load_model($classname) {
return self::_load_class($classname,'model');
}
/**
* ¼ÓÔØÀàÎļþº¯Êý
* @param string $classname ˈ̞
* @param string $path À©Õ¹µØÖ·
* @param intger $initialize ÊÇ·ñ³õʼ»¯
*/
private static function _load_class($classname, $path = '', $initialize = 1) {
static $classes = array();
if (empty($path)) $path = 'jae'.DIRECTORY_SEPARATOR.'libs'.DIRECTORY_SEPARATOR.'classes';
else $path='jae'.DIRECTORY_SEPARATOR.$path;
$key = md5($path.$classname);
if (isset($classes[$key])) {
if (!empty($classes[$key])) {
return $classes[$key];
} else {
return true;
}
}
if (file_exists(JAE_PATH.$path.DIRECTORY_SEPARATOR.$classname.'.class.php')) {
//include '../jae/libs/classes/application.class.php';
//echo JAE_PATH.$path.DIRECTORY_SEPARATOR.$classname.'.class.php////////////////';
include JAE_PATH.$path.DIRECTORY_SEPARATOR.$classname.'.class.php';
$name = $classname;
if ($my_path = self::my_path(JAE_PATH.$path.DIRECTORY_SEPARATOR.$classname.'.class.php')) {
include $my_path;
$name = 'MY_'.$classname;
}
if ($initialize) {
$classes[$key] = new $name;
} else {
$classes[$key] = true;
}
return $classes[$key];
} else { //echo "this file is no exist.";
return false;
}
}
/**
* ¼ÓÔØÏµÍ³µÄº¯Êý¿â
* @param string $func º¯Êý¿âÃû
*/
public static function load_sys_func($func) {
return self::_load_func($func);
}
/**
* ×Ô¶¯¼ÓÔØautoloadĿ¼Ïº¯Êý¿â
* @param string $func º¯Êý¿âÃû
*/
public static function auto_load_func($path='') {
return self::_auto_load_func($path);
}
/**
* ¼ÓÔØÓ¦Óú¯Êý¿â
* @param string $func º¯Êý¿âÃû
* @param string $m Ä£ÐÍÃû
*/
public static function load_app_func($func, $m = '') {
$m = empty($m) && defined('ROUTE_M') ? ROUTE_M : $m;
if (empty($m)) return false;
return self::_load_func($func, 'jae'.DIRECTORY_SEPARATOR.'modules'.DIRECTORY_SEPARATOR.$m.DIRECTORY_SEPARATOR.'functions');
}
/**
* ¼ÓÔØ²å¼þÀà¿â
*/
public static function load_plugin_class($classname, $identification = '' ,$initialize = 1) {
$identification = empty($identification) && defined('PLUGIN_ID') ? PLUGIN_ID : $identification;
if (empty($identification)) return false;
return jae_base::load_sys_class($classname, 'plugin'.DIRECTORY_SEPARATOR.$identification.DIRECTORY_SEPARATOR.'classes', $initialize);
}
/**
* ¼ÓÔØ²å¼þº¯Êý¿â
* @param string $func º¯ÊýÎļþÃû³Æ
* @param string $identification ²å¼þ±êʶ
*/
public static function load_plugin_func($func,$identification) {
static $funcs = array();
$identification = empty($identification) && defined('PLUGIN_ID') ? PLUGIN_ID : $identification;
if (empty($identification)) return false;
$path = 'plugin'.DIRECTORY_SEPARATOR.$identification.DIRECTORY_SEPARATOR.'functions'.DIRECTORY_SEPARATOR.$func.'.func.php';
$key = md5($path);
if (isset($funcs[$key])) return true;
if (file_exists(JAE_PATH.$path)) {
include JAE_PATH.$path;
} else {
$funcs[$key] = false;
return false;
}
$funcs[$key] = true;
return true;
}
/**
* ¼ÓÔØ²å¼þÊý¾ÝÄ£ÐÍ
* @param string $classname ˈ̞
*/
public static function load_plugin_model($classname,$identification) {
$identification = empty($identification) && defined('PLUGIN_ID') ? PLUGIN_ID : $identification;
$path = 'plugin'.DIRECTORY_SEPARATOR.$identification.DIRECTORY_SEPARATOR.'model';
return self::_load_class($classname,$path);
}
/**
* ¼ÓÔØº¯Êý¿â
* @param string $func º¯Êý¿âÃû
* @param string $path µØÖ·
*/
private static function _load_func($func, $path = '') {
static $funcs = array();
if (empty($path)) $path = 'jae'.DIRECTORY_SEPARATOR.'libs'.DIRECTORY_SEPARATOR.'functions';
$path .= DIRECTORY_SEPARATOR.$func.'.func.php';
$key = md5($path);
if (isset($funcs[$key])) return true;
if (file_exists(JAE_PATH.$path)) {
include JAE_PATH.$path;
} else {
$funcs[$key] = false;
return false;
}
$funcs[$key] = true;
return true;
}
/**
* ¼ÓÔØº¯Êý¿â
* @param string $func º¯Êý¿âÃû
* @param string $path µØÖ·
*/
private static function _auto_load_func($path = '') {
if (empty($path)) $path = 'libs'.DIRECTORY_SEPARATOR.'functions'.DIRECTORY_SEPARATOR.'autoload';
$path .= DIRECTORY_SEPARATOR.'*.func.php';
$auto_funcs = glob(JAE_PATH.DIRECTORY_SEPARATOR.$path);
if(!empty($auto_funcs) && is_array($auto_funcs)) {
foreach($auto_funcs as $func_path) {
include $func_path;
}
}
}
/**
* ÊÇ·ñÓÐ×Ô¼ºµÄÀ©Õ¹Îļþ
* @param string $filepath ·¾¶
*/
public static function my_path($filepath) {
$path = pathinfo($filepath);
if (file_exists($path['dirname'].DIRECTORY_SEPARATOR.'MY_'.$path['basename'])) {
return $path['dirname'].DIRECTORY_SEPARATOR.'MY_'.$path['basename'];
} else {
return false;
}
}
/**
* ¼ÓÔØÅäÖÃÎļþ
* @param string $file ÅäÖÃÎļþ
* @param string $key Òª»ñÈ¡µÄÅäÖüö
* @param string $default ĬÈÏÅäÖᣵ±»ñÈ¡ÅäÖÃÏîĿʧ°Üʱ¸ÃÖµ·¢Éú×÷Óá£
* @param boolean $reload Ç¿ÖÆÖØÐ¼ÓÔØ¡£
*/
public static function load_config($file, $key = '', $default = '', $reload = false) {
static $configs = array();
if (!$reload && isset($configs[$file])) {
if (empty($key)) {
return $configs[$file];
} elseif (isset($configs[$file][$key])) {
return $configs[$file][$key];
} else {
return $default;
}
}
$path = CACHE_PATH.'configs'.DIRECTORY_SEPARATOR.$file.'.php';
if (file_exists($path)) {
$configs[$file] = include $path;
}
if (empty($key)) {
return $configs[$file];
} elseif (isset($configs[$file][$key])) {
return $configs[$file][$key];
} else {
return $default;
}
}
/**
* ¼ÓÔØÌÔ±¦TOPÅäÖÃÎļþ
* @param string $file ÅäÖÃÎļþ
* @param string $key Òª»ñÈ¡µÄÅäÖüö
* @param string $default ĬÈÏÅäÖᣵ±»ñÈ¡ÅäÖÃÏîĿʧ°Üʱ¸ÃÖµ·¢Éú×÷Óá£
* @param boolean $reload Ç¿ÖÆÖØÐ¼ÓÔØ¡£
*/
public static function load_top($file, $key = '', $default = '', $reload = false) {
static $configs = array();
if (!$reload && isset($configs[$file])) {
if (empty($key)) {
return $configs[$file];
} elseif (isset($configs[$file][$key])) {
return $configs[$file][$key];
} else {
return $default;
}
}
$path = JAE_PATH.'top'.DIRECTORY_SEPARATOR.$file.'.php';
if (file_exists($path)) {
$configs[$file] = include $path;
}
if (empty($key)) {
return $configs[$file];
} elseif (isset($configs[$file][$key])) {
return $configs[$file][$key];
} else {
return $default;
}
}
}
?><file_sep>/caches/caches_template/neimeng/content/index.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head');?>
<link rel="stylesheet" href="/statics/css/lows.css" />
<div class="lows-banner J_TWidget" style="display:none" id="J_LowsBanner" data-widget-type="Carousel" data-widget-config="{'navCls':'ks-switchable-nav','contentCls':'ks-switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'active','autoplay':'true','interval':3,'prevBtnCls': 'prev', 'nextBtnCls': 'next', 'disableBtnCls': 'disable' }">
<div class="trigger-wrap">
<span class="close J_LowsClose"></span>
<span class="prev"></span>
<span class="next"></span>
<ol class="lows-trigger ks-switchable-nav">
<li class="ks-switchable-trigger-internal297 active"></li>
<li class="ks-switchable-trigger-internal297 "></li>
<li class="ks-switchable-trigger-internal297"></li>
</ol>
</div>
<ul class="ks-switchable-content clear-fix">
<li class="pic1 ks-switchable-panel-internal298" style="display: block; opacity: 0; position: absolute; z-index: 1; "><div class="banner-pic" style="background: url(http://img03.taobaocdn.com/imgextra/i3/1863579612/TB2_FMOXVXXXXX7XpXXXXXXXXXX-1863579612.png) no-repeat 0 0;"></div></li>
<li class="pic2 ks-switchable-panel-internal298" style="display: block; opacity: 1; position: absolute; z-index: 9; "><div class="banner-pic" style="background: url(http://img04.taobaocdn.com/imgextra/i4/1863579612/TB2VhgOXVXXXXbaXXXXXXXXXXXX-1863579612.png) no-repeat 0 0;"></div></li>
<li class="pic3 ks-switchable-panel-internal298" style="display: block; opacity: 0; position: absolute; z-index: 1; "><div class="banner-pic" style="background: url(http://img02.taobaocdn.com/imgextra/i2/1863579612/TB2G4ZOXVXXXXXGXXXXXXXXXXXX-1863579612.png) no-repeat 0 0;"></div></li>
</ul>
</div>
<div class="body_w">
<!--banner-->
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=21 ORDER BY listorder,id ASC LIMIT 1,1 ');
foreach ($result as $v) { if(!empty($v['picture'])){
?><a target="_blank" href="<?php echo $v['link'];?>" ><div style="background-image:url(<?php echo $v['picture'];?>); display:block; height:<?php echo $v['description'];?>px;background-repeat: no-repeat;background-position: center top;"></a></div>
<?php } }
?>
<!--banner end-->
<!--首焦-->
<div class="wrap" style="height:420px; position:relative;">
<div class="root61" style="z-index:22">
<div class=" smCategorys">
<div class="sm-c-wrap">
<div class="menu switchable-nav">
<div class="item fore1">
<i class="i1"></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=10 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=10 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore2">
<i class="i2"></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=16 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=16 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore3">
<i class="i3"></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=17 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=17 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore4">
<i class="i4"></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=18 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=18 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore5">
<i class="i5"></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=19 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=19 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="J_MallSlide" class=" timeLine scrollable mall-slide J_TWidget dd" data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'curr','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<!--banner-->
<div class="tl-theme">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=21 ORDER BY listorder,id ASC LIMIT 2,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img width="290" height="68" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<!--banner end-->
<div class="mt">
<i class="line"></i>
<div class="tl-tab-item clearfix switchable-nav">
<a class="curr"><span ><?php echo position(7) ?></span><b></b><i></i></a>
<a><span><?php echo position(8) ?></span><b></b><i></i></a>
<a><span><?php echo position(9) ?></span><b></b><i></i></a>
<a><span><?php echo position(10) ?></span><b></b><i></i></a>
</div>
</div>
<div class="mc switchable-content" style="position: relative; ">
<div class="item ui-switchable-panel" style="position: absolute; ">
<ul class="clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=23d41b6cd54902fea23248fbba7ca327&action=position&posid=7&order=listorder+asc&num=9\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=23d41b6cd54902fea23248fbba7ca327&action=position&posid=7&order=listorder+asc&num=9\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'7','order'=>'listorder asc','limit'=>'9',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li>
<div class="p-img">
<a href="<?php echo $r['url']?>" target="_blank">
<img class="err-product pimg1029168" width="80" height="80" data-img="1" alt="<?php echo $r['title']?> " src="<?php echo $r['thumb']?>">
</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
<div class="item ui-switchable-panel" style="position: absolute; ">
<ul class="clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=3f28fccf3eb9f9f44cf0d8bbab24eff7&action=position&posid=8&order=listorder+asc&num=9\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=3f28fccf3eb9f9f44cf0d8bbab24eff7&action=position&posid=8&order=listorder+asc&num=9\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'8','order'=>'listorder asc','limit'=>'9',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li>
<div class="p-img">
<a href="<?php echo $r['url']?>" target="_blank">
<img class="err-product pimg1029168" width="80" height="80" data-img="1" alt="<?php echo $r['title']?> " src="<?php echo $r['thumb']?>">
</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
<div class="item ui-switchable-panel selected" style="position: absolute; ">
<ul class="clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=bdb08adf73b10b33225d29cd0e1de972&action=position&posid=9&order=listorder+asc&num=9\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=bdb08adf73b10b33225d29cd0e1de972&action=position&posid=9&order=listorder+asc&num=9\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'9','order'=>'listorder asc','limit'=>'9',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li>
<div class="p-img">
<a href="<?php echo $r['url']?>" target="_blank">
<img class="err-product pimg1029168" width="80" height="80" data-img="1" alt="<?php echo $r['title']?> " src="<?php echo $r['thumb']?>">
</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
<div class="item ui-switchable-panel" style="position: absolute; ">
<ul class="clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=1dd374337241126adce764052856a0bf&action=position&posid=10&order=listorder+asc&num=9\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=1dd374337241126adce764052856a0bf&action=position&posid=10&order=listorder+asc&num=9\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'10','order'=>'listorder asc','limit'=>'9',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li>
<div class="p-img">
<a href="<?php echo $r['url']?>" target="_blank">
<img class="err-product pimg1029168" width="80" height="80" data-img="1" alt="<?php echo $r['title']?> " src="<?php echo $r['thumb']?>">
</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
</div>
</div>
<!--shoujiao-->
<div class="focus J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'tab-nav','contentCls':'tab-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [1920], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<div class="prev"></div><div class="next"></div>
<div class="tab-content">
<?php $sql="SELECT * FROM jae_focus WHERE status=1 ORDER BY listorder ASC ";
$r_focus=query($sql); foreach ($r_focus as $r) {?>
<div><a href="<?php echo $r["link"]?>" target="_blank"> <img src="<?php echo $r["picture"]?>" width="710" height="400"/></a></div>
<?php }?>
</div>
<div class="tab-nav">
<?php $r_focuss=query($sql); foreach ($r_focuss as $k=>$rs) {?>
<div class="v<?php echo $k?>"></div>
<?php }?>
</div>
</div>
<!--shoujia end-->
</div>
<!--banner-->
<div class="banad">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=21 ORDER BY listorder,id ASC LIMIT 3,1 ');
foreach ($result as $v) { if(!empty($v['picture'])){
?><a target="_blank" href="<?php echo $v['link'];?>"><img width="1210" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php } }
?>
</div>
<!--banner end-->
<!--抽奖 -->
<div style="height:20px; clear:both;"></div>
<div class="wrap root61">
<h2>会员抽奖</h2>
<div class="abenti">
<div class="chojdkm">
<div class="bejsl">
<?php $result=query('SELECT * FROM jae_prize_set WHERE status=1 ORDER BY listorder,id ASC LIMIT 0,6 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['url'];?>"><img data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="zjsl">
<a target="_blank" href="/index.php?m=prize&c=index&a=init"><img data-ks-lazyload="/statics/images/cjaniu.jpg"></a>
</div>
<div class="bejsl">
<?php $result=query('SELECT * FROM jae_prize_set WHERE status=1 ORDER BY listorder,id ASC LIMIT 6,6 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['url'];?>"><img data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="clr"></div>
</div>
</div>
</div>
<!--抽奖end -->
<!--秒杀-->
<div class="wrap root61 m sm-wrap">
<div class=" seckilling" >
<div class="mt">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?><h2><?php echo $v['title'];?></h2>
<?php }
?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?><span class="describe"><?php echo $v['description'];?></span>
<?php }
?>
</div>
</div>
<div class="mc J_TWidget" data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'curr','prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable','autoplay':'true','duration':'1'}">
<div class="sk-time" style="z-index:10">
</div>
<!-- 时间tab -->
<div class="sk-tab" style="z-index:10">
<i class="line"></i>
<div class="sk-clock morning" style="left: -29px; "></div>
<div class="sk-tab-item switchable-nav">
<a href="javascript:void(0)" class="left ui-switchable-item killing curr">
<b></b>
<span><?php echo position(14) ?></span>
</a>
<a href="javascript:void(0)" class="center ui-switchable-item">
<b></b>
<span><?php echo position(15) ?></span>
</a>
<a href="javascript:void(0)" class="right ui-switchable-item">
<b></b>
<span><?php echo position(16) ?></span>
</a>
</div>
</div>
<!-- 时间tab end -->
<div class="sk-con switchable-content" >
<div class="sk-item ui-switchable-panel morning selected" style="z-index: 1; opacity: 1; ">
<div class="sk-item-bg">
<span class="sun"></span>
</div>
<ul class="clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=e3d497a1453d66f99c00e3ee3e389da8&action=position&posid=14&order=listorder+asc&num=3\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=e3d497a1453d66f99c00e3ee3e389da8&action=position&posid=14&order=listorder+asc&num=3\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'14','order'=>'listorder asc','limit'=>'3',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><div class="p-img"><a href="<?php echo $r['url'];?>" target="_blank"><img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img width="180" height="180" data-ks-lazyload="<?php echo $r['thumb'];?>" ></a></div><div class="p-name"><a href="<?php echo $r['detail_url'];?>" target="_blank"><?php echo $r['title'];?></a></div><div class="p-price"><strong>¥<?php echo $r['coupon_price'];?></strong><del><?php echo $r['price'];?></del></div><div class="p-btn"><a class="btn-m seckilling" href="<?php echo $r['detail_url'];?>" target="_blank">立即秒杀</a></div></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
<div class="sk-item ui-switchable-panel noon" style="opacity: 0; ">
<div class="sk-item-bg">
<span class="sun"></span>
</div>
<ul class="clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=2b38c84325e03ed3e994931b9f529303&action=position&posid=15&order=listorder+asc&num=3\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=2b38c84325e03ed3e994931b9f529303&action=position&posid=15&order=listorder+asc&num=3\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'15','order'=>'listorder asc','limit'=>'3',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><div class="p-img"><a href="<?php echo $r['url'];?>" target="_blank"><img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img width="180" height="180" data-ks-lazyload="<?php echo $r['thumb'];?>" ></a></div><div class="p-name"><a href="<?php echo $r['detail_url'];?>" target="_blank"><?php echo $r['title'];?></a></div><div class="p-price"><strong>¥<?php echo $r['coupon_price'];?></strong><del><?php echo $r['price'];?></del></div><div class="p-btn"><a class="btn-m seckilling" href="<?php echo $r['detail_url'];?>" target="_blank">立即秒杀</a></div></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
<div class="sk-item ui-switchable-panel night" style="opacity: 0; ">
<div class="sk-item-bg">
<span class="sun"></span>
</div>
<ul class="clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=a3c43e88164a75d4d2c59aa689deadbc&action=position&posid=16&order=listorder+asc&num=3\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=a3c43e88164a75d4d2c59aa689deadbc&action=position&posid=16&order=listorder+asc&num=3\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'16','order'=>'listorder asc','limit'=>'3',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><div class="p-img"><a href="<?php echo $r['url'];?>" target="_blank"><img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img width="180" height="180" data-ks-lazyload="<?php echo $r['thumb'];?>" ></a></div><div class="p-name"><a href="<?php echo $r['detail_url'];?>" target="_blank"><?php echo $r['title'];?></a></div><div class="p-price"><strong>¥<?php echo $r['coupon_price'];?></strong><del><?php echo $r['price'];?></del></div><div class="p-btn"><a class="btn-m seckilling" href="<?php echo $r['detail_url'];?>" target="_blank">立即秒杀</a></div></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
</div>
</div>
</div>
<div class="freshSale" clstag="firsttype|keycount|chaoshi|02">
<div class="mt">
<h2><?php echo position(17) ?></h2>
<div class="ext">
<span class="describe"></span>
</div>
</div>
<div class="mc">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=7c348b093c472c0b4473574bd5be472f&action=position&posid=17&order=listorder+asc&num=1\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=7c348b093c472c0b4473574bd5be472f&action=position&posid=17&order=listorder+asc&num=1\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'17','order'=>'listorder asc','limit'=>'1',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="p-img">
<a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg1050332480" width="240" height="240" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" data-ks-lazyload="<?php echo $r['thumb'];?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a>
</div>
<div class="p-ext">
特价优惠,限时抢购!
</div>
<div class="p-price" sku="1050332480">
<strong>¥<?php echo $r['coupon_price'];?></strong>
<del>¥<?php echo $r['price'];?></del>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
<div class="clr" style="clear:both;"></div>
</div>
<div style="height:20px; clear:both;"></div>
<!--9.9包邮 -->
<div class="wrap root61">
<!-- 新鲜速递 -->
<div class=" freshExpress m sm-wrap J_TWidget" data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [1210], 'circular': true, 'activeTriggerCls':'selected','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable'}" >
<div class="mt">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 1,1 ');
foreach ($result as $v) {
?><h2><?php echo $v['title'];?></h2>
<?php }
?>
<div class="ext switchable-nav">
<a href="javascript:void(0)" class="filter-item selected"><b><?php echo position(18) ?></b></a>
<a href="javascript:void(0)" class="filter-item"><b><?php echo position(20) ?></b></a>
<a href="javascript:void(0)" class="filter-item"><b><?php echo position(21) ?></b></a>
</div>
</div>
<div class="mc switchable-content" style="position: relative; ">
<div class="item ui-switchable-panel selected" style="background-color: rgb(254, 195, 191); position: absolute; z-index: 1; opacity: 1; ">
<span class="fe-pic">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=24 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" alt="" width="350" height="310" class="err-product" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</span>
<ul class="fe-list clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=dd29aabfc85582cc71ad80af9956b07b&action=position&posid=18&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=dd29aabfc85582cc71ad80af9956b07b&action=position&posid=18&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'18','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg1053862480" width="150" height="150" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" data-ks-lazyload="<?php echo $r['thumb'];?>">
</a>
</div>
<div class="p-price" sku="1053862480"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn"><a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a></div>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div><div class="item ui-switchable-panel selected" style="background-color: rgb(254, 195, 191); position: absolute; z-index: 1; opacity: 1; ">
<span class="fe-pic">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=24 ORDER BY listorder,id ASC LIMIT 1,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" alt="" width="350" height="310" class="err-product" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</span>
<ul class="fe-list clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=366626f77e5750ad5bc359123d14f417&action=position&posid=20&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=366626f77e5750ad5bc359123d14f417&action=position&posid=20&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'20','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg1053862480" width="150" height="150" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" data-ks-lazyload="<?php echo $r['thumb'];?>">
</a>
</div>
<div class="p-price" sku="1053862480"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn"><a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a></div>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div><div class="item ui-switchable-panel selected" style="background-color: rgb(254, 195, 191); position: absolute; z-index: 1; opacity: 1; ">
<span class="fe-pic">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=24 ORDER BY listorder,id ASC LIMIT 2,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" alt="" width="350" height="310" class="err-product" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</span>
<ul class="fe-list clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=7b82308ea73efd075db8a04fe7adc31d&action=position&posid=21&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=7b82308ea73efd075db8a04fe7adc31d&action=position&posid=21&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'21','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg1053862480" width="150" height="150" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" data-ks-lazyload="<?php echo $r['thumb'];?>">
</a>
</div>
<div class="p-price" sku="1053862480"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn"><a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a></div>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
</div>
</div>
<!-- 新鲜速递 end -->
<div class="clr"></div>
</div>
<div style="height:20px; clear:both;"></div>
<!-- 特色品类 -->
<div class="wrap root61">
<!-- 新鲜速递 -->
<div class="sort m sm-wrap J_TWidget" data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [1210], 'circular': true, 'activeTriggerCls':'selected','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable'}" >
<div class="mt">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 2,1 ');
foreach ($result as $v) {
?><h2><?php echo $v['title'];?></h2>
<?php }
?>
<div class="ext switchable-nav">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 3,1 ');
foreach ($result as $v) {
?><a href="javascript:void(0)" class="filter-item selected"><b><?php echo $v['title'];?></b></a>
<?php }
?>
</div>
</div>
<div class="mc switchable-content" style="position: relative; ">
<div class="item ui-switchable-panel selected" style="background-color: rgb(255, 255, 255); position: absolute; z-index: 1; opacity: 1; ">
<div class="left">
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(5);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 1,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(6);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 2,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(7);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 3,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(8);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 4,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(9);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 5,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(10);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 6,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(11);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 7,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(12);?> </div>
</div>
</div>
</div><div class="right">
<div class="r1">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 8,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img width="220" height="220" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="r1">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 9,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img width="220" height="220" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
</div>
<div class="clr"></div>
</div>
</div>
</div>
<!-- 新鲜速递 end -->
</div>
<!--banner----->
<div class="banad">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=21 ORDER BY listorder,id ASC LIMIT 4,1 ');
foreach ($result as $v) { if(!empty($v['picture'])){
?><a target="_blank" href="<?php echo $v['link'];?>"><img width="1210" data-ks-lazyload="<?php echo $v['picture'];?>"></a><div style="height:25px; clear:both;"></div>
<?php } }
?>
</div>
<!--banner end----->
<!-- 本周精选 -->
<div class="wrap" style="height:600px;">
<div class="m sm-wrap snacks" >
<div class="mc" style="position: relative; ">
<div class="item ui-switchable-panel J_TWidget" data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [1210], 'circular': true, 'activeTriggerCls':'selected','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable'}" >
<div class="sub-list switchable-nav">
<a href="javascript:void(0)" class="fore8 sub-tab selected"><strong><em><?php echo position(22) ?></em></strong></a>
<a href="javascript:void(0)" class="fore1 sub-tab"><strong><em><?php echo position(23) ?></em></strong></a>
<a href="javascript:void(0)" class="fore2 sub-tab"><strong><em><?php echo position(24) ?></em></strong></a>
<a href="javascript:void(0)" class="fore3 sub-tab"><strong><em><?php echo position(25) ?></em></strong></a>
<a href="javascript:void(0)" class="fore4 sub-tab"><strong><em><?php echo position(26) ?></em></strong></a>
<a href="javascript:void(0)" class="fore5 sub-tab"><strong><em><?php echo position(27) ?></em></strong></a>
<a href="javascript:void(0)" class="fore6 sub-tab"><strong><em><?php echo position(28) ?></em></strong></a>
<a href="javascript:void(0)" class="fore7 sub-tab"><strong><em><?php echo position(29) ?></em></strong></a>
</div>
<div class="sub-con switchable-content">
<div >
<ul class="clearfix sub-item" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=0a165ba46ac16fc858d58adf76da5219&action=position&posid=22&order=listorder+asc&num=15\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=0a165ba46ac16fc858d58adf76da5219&action=position&posid=22&order=listorder+asc&num=15\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'22','order'=>'listorder asc','limit'=>'15',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg787703" width="170" height="170" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" data-ks-lazyload="<?php echo $r['thumb'];?>">
</a>
</div>
<div class="p-price" sku="787703"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div><div >
<ul class="clearfix sub-item" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=89ccda12493796ef2e85472eef2adefc&action=position&posid=23&order=listorder+asc&num=15\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=89ccda12493796ef2e85472eef2adefc&action=position&posid=23&order=listorder+asc&num=15\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'23','order'=>'listorder asc','limit'=>'15',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg787703" width="170" height="170" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" data-ks-lazyload="<?php echo $r['thumb'];?>">
</a>
</div>
<div class="p-price" sku="787703"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div><div >
<ul class="clearfix sub-item" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=1b723b2cec0a56cc87fd4a456198d996&action=position&posid=24&order=listorder+asc&num=15\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=1b723b2cec0a56cc87fd4a456198d996&action=position&posid=24&order=listorder+asc&num=15\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'24','order'=>'listorder asc','limit'=>'15',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg787703" width="170" height="170" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" data-ks-lazyload="<?php echo $r['thumb'];?>">
</a>
</div>
<div class="p-price" sku="787703"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div><div >
<ul class="clearfix sub-item" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=fe47eed182f445fcff20a9ecf5e57bf7&action=position&posid=25&order=listorder+asc&num=15\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=fe47eed182f445fcff20a9ecf5e57bf7&action=position&posid=25&order=listorder+asc&num=15\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'25','order'=>'listorder asc','limit'=>'15',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg787703" width="170" height="170" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" data-ks-lazyload="<?php echo $r['thumb'];?>">
</a>
</div>
<div class="p-price" sku="787703"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div><div >
<ul class="clearfix sub-item" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=13d38c50ee27548d9ec83ae1cdf2461a&action=position&posid=26&order=listorder+asc&num=15\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=13d38c50ee27548d9ec83ae1cdf2461a&action=position&posid=26&order=listorder+asc&num=15\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'26','order'=>'listorder asc','limit'=>'15',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg787703" width="170" height="170" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" data-ks-lazyload="<?php echo $r['thumb'];?>">
</a>
</div>
<div class="p-price" sku="787703"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div><div >
<ul class="clearfix sub-item" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=d1a75d916830c9dcb07c1c352c6545c4&action=position&posid=27&order=listorder+asc&num=15\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=d1a75d916830c9dcb07c1c352c6545c4&action=position&posid=27&order=listorder+asc&num=15\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'27','order'=>'listorder asc','limit'=>'15',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg787703" width="170" height="170" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" data-ks-lazyload="<?php echo $r['thumb'];?>">
</a>
</div>
<div class="p-price" sku="787703"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div><div >
<ul class="clearfix sub-item" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=bcf7f5cf1d8b386bc89ffe511730d1c6&action=position&posid=28&order=listorder+asc&num=15\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=bcf7f5cf1d8b386bc89ffe511730d1c6&action=position&posid=28&order=listorder+asc&num=15\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'28','order'=>'listorder asc','limit'=>'15',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg787703" width="170" height="170" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" data-ks-lazyload="<?php echo $r['thumb'];?>">
</a>
</div>
<div class="p-price" sku="787703"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div><div >
<ul class="clearfix sub-item" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=623bd87327cdfadf729f62f0dcfdc3f3&action=position&posid=29&order=listorder+asc&num=15\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=623bd87327cdfadf729f62f0dcfdc3f3&action=position&posid=29&order=listorder+asc&num=15\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'29','order'=>'listorder asc','limit'=>'15',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg787703" width="170" height="170" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" data-ks-lazyload="<?php echo $r['thumb'];?>">
</a>
</div>
<div class="p-price" sku="787703"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
</div>
</div>
</div>
</div>
</div>
<!-- 美食地理 -->
<div class="wrap root61">
<!-- 美食地理 -->
<div class=" cookingGeology m sm-wrap" clstag="firsttype|keycount|chaoshi|08">
<div class="mt">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 6,1 ');
foreach ($result as $v) {
?><h2><?php echo $v['title'];?></h2>
<?php }
?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 6,1 ');
foreach ($result as $v) {
?><span class="describe"><?php echo $v['description'];?></span>
<?php }
?>
</div>
</div>
<div class="mc">
<!-- 触发器 -->
<div class="cg-trigger">
</div>
<!-- 触发器 end -->
<div class="cg-hide">
<span class="cg-h-close"></span>
<div class="cg-h-title"></div>
</div>
<!-- 隐藏优惠券 end -->
<!-- 遮罩 -->
<div class="cg-mask left"></div>
<div class="cg-mask right"></div>
<!-- 遮罩 end -->
<!-- 左侧国内 -->
<div class="cookingGeologyLeft cg-wrap left J_TWidget" data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [1210], 'circular': true, 'activeTriggerCls':'curr','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable'}" >
<div class="cg-w-tab">
<div class="cg-w-t-item switchable-nav">
<a class="fore1 ui-switchable-item curr" href="javascript:void(0)">
<div class="cg-w-t-label" style="left:-6px; top: -50px; display:none "></div> <b></b>
<span style="width:80px; text-align:left; margin-left:-1px;"><?php echo position(30) ?></span>
</a>
<a class="fore3 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left:-6px; top: -50px; display:none "></div> <b></b>
<span><?php echo position(31) ?></span>
</a>
<a class="fore5 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left:-6px; top: -50px; display:none "></div> <b></b>
<span><?php echo position(32) ?></span>
</a>
<a class="fore6 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left:-6px; top: -50px; display:none "></div> <b></b>
<span><?php echo position(33) ?></span>
</a>
<a class="fore8 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left:-6px; top: -50px; display:none "></div> <b></b>
<span><?php echo position(34) ?></span>
</a>
<a class="fore10 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left:-6px; top: -50px; display:none "></div> <b></b>
<span style="width:80px; text-align:left; margin-left:-1px;"><?php echo position(35) ?></span>
</a>
</div>
</div>
<div class="cg-w-con switchable-content" style="position: relative; ">
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=4199c485353c0fd7054e30d119458431&action=position&posid=30&order=listorder+asc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=4199c485353c0fd7054e30d119458431&action=position&posid=30&order=listorder+asc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'30','order'=>'listorder asc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=aca062b790508c9d35f604b53326f39d&action=position&posid=31&order=listorder+asc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=aca062b790508c9d35f604b53326f39d&action=position&posid=31&order=listorder+asc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'31','order'=>'listorder asc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=308c25c32e624547180eb48b61d96f85&action=position&posid=32&order=listorder+asc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=308c25c32e624547180eb48b61d96f85&action=position&posid=32&order=listorder+asc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'32','order'=>'listorder asc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=c6a802048e3e572187a3a5611625efe5&action=position&posid=33&order=listorder+asc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=c6a802048e3e572187a3a5611625efe5&action=position&posid=33&order=listorder+asc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'33','order'=>'listorder asc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=52a554d2a832293e554d5b2a57231d9d&action=position&posid=34&order=listorder+asc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=52a554d2a832293e554d5b2a57231d9d&action=position&posid=34&order=listorder+asc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'34','order'=>'listorder asc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=d4b75644b9d649d162961811e671cf18&action=position&posid=35&order=listorder+asc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=d4b75644b9d649d162961811e671cf18&action=position&posid=35&order=listorder+asc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'35','order'=>'listorder asc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
</div>
</div>
<!-- 左侧国内 end-->
<!-- 右侧国际 -->
<div class="cookingGeologyRight cg-wrap right J_TWidget " data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [1210], 'circular': true, 'activeTriggerCls':'curr','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable'}" >
<div class="cg-w-tab">
<div class="cg-w-t-item switchable-nav">
<a class="fore1 ui-switchable-item curr" href="javascript:void(0)">
<div class="cg-w-t-label" style="left: -13px; top: -50px; display:none; "></div> <b></b>
<span style="width:90px; text-align:left; margin-left:-15px;"><?php echo position(40) ?></span>
</a>
<a class="fore3 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left: -13px; top: -50px; display:none; "></div> <b></b>
<span style="width:80px; text-align:left; margin-left:-10px"><?php echo position(41) ?></span>
</a>
<a class="fore4 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left: -13px; top: -50px; display:none; "></div> <b></b>
<span style="width:80px; text-align:left; margin-left:-10px"><?php echo position(36) ?></span>
</a>
<a class="fore5 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left: -13px; top: -50px; display:none; "></div> <b></b>
<span style="width:80px; text-align:left; margin-left:-10px"><?php echo position(37) ?></span>
</a>
<a class="fore6 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left: -13px; top: -50px; display:none; "></div> <b></b>
<span style="width:80px; text-align:left; margin-left:-10px"><?php echo position(38) ?></span>
</a>
<a class="fore8 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left: -13px; top: -50px; display:none; "></div> <b></b>
<span style="width:80px; text-align:left; margin-left:-10px"><?php echo position(39) ?></span>
</a>
</div>
</div>
<div class="cg-w-con switchable-content" style="position: relative; ">
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=f098a5075be4d0a3fbe45a50cb07c4a1&action=position&posid=40&order=listorder+asc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=f098a5075be4d0a3fbe45a50cb07c4a1&action=position&posid=40&order=listorder+asc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'40','order'=>'listorder asc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=3c948671a8d108e2aaf9d75c647d325d&action=position&posid=41&order=listorder+asc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=3c948671a8d108e2aaf9d75c647d325d&action=position&posid=41&order=listorder+asc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'41','order'=>'listorder asc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=81119c00cf2e32f1ad1cafd231060d45&action=position&posid=36&order=listorder+asc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=81119c00cf2e32f1ad1cafd231060d45&action=position&posid=36&order=listorder+asc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'36','order'=>'listorder asc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=de9afa92bfbce97279098b3fb4ac40b8&action=position&posid=37&order=listorder+asc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=de9afa92bfbce97279098b3fb4ac40b8&action=position&posid=37&order=listorder+asc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'37','order'=>'listorder asc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=6772a2f0e2a7dfd87ec1bbf4688dc43b&action=position&posid=38&order=listorder+asc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=6772a2f0e2a7dfd87ec1bbf4688dc43b&action=position&posid=38&order=listorder+asc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'38','order'=>'listorder asc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=f3f7774c39f2d10f572652e66b439cea&action=position&posid=39&order=listorder+asc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=f3f7774c39f2d10f572652e66b439cea&action=position&posid=39&order=listorder+asc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'39','order'=>'listorder asc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
</div>
</div>
</div>
</div>
<!-- 美食地理 end -->
<div class="clr" style="clear:both;"></div>
</div>
<div style="height:20px; clear:both;"></div>
<!-- 专题 -->
<div style="height:20px; clear:both;"></div>
<div class="wrap">
<div class="special">
<ul><li class="s1">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=22 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?><h1><?php echo $v['title'];?></h1><div class="grace"><?php echo $v['description'];?></div><a href="<?php echo $v['link'];?>" target="_blank"><img height="240" width="240" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</li><li class="s2">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=22 ORDER BY listorder,id ASC LIMIT 1,1 ');
foreach ($result as $v) {
?><h1><?php echo $v['title'];?></h1><div class="grace"><?php echo $v['description'];?></div><a href="<?php echo $v['link'];?>" target="_blank"><img height="240" width="240" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</li><li class="s3">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=22 ORDER BY listorder,id ASC LIMIT 2,1 ');
foreach ($result as $v) {
?><h1><?php echo $v['title'];?></h1><div class="grace"><?php echo $v['description'];?></div><a href="<?php echo $v['link'];?>" target="_blank"><img height="240" width="240" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</li><li class="s4">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=22 ORDER BY listorder,id ASC LIMIT 3,1 ');
foreach ($result as $v) {
?><h1><?php echo $v['title'];?></h1><div class="grace"><?php echo $v['description'];?></div><a href="<?php echo $v['link'];?>" target="_blank"><img height="240" width="240" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</li><li class="s5">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=22 ORDER BY listorder,id ASC LIMIT 4,1 ');
foreach ($result as $v) {
?><h1><?php echo $v['title'];?></h1><div class="grace"><?php echo $v['description'];?></div><a href="<?php echo $v['link'];?>" target="_blank"><img height="240" width="240" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</li>
</ul> </div>
</div>
<!-- 专题 -->
<!--banner-->
<div class="banad">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=21 ORDER BY listorder,id ASC LIMIT 5,1 ');
foreach ($result as $v) { if(!empty($v['picture'])){
?><div style="height:15px; clear:both;"></div><a target="_blank" href="<?php echo $v['link'];?>"><img width="1210" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php } }
?>
</div>
<div style="height:15px; clear:both;"></div>
<!--banner end-->
<div class="wrap root61">
<!-- 第1层-->
<div data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'none',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'selected','autoplay':'true','prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable','duration':'0' }" class=" smFloor1 sm-floor m J_TWidget" >
<!-- tab -->
<div class="sf-tab">
<ul class="clearfix switchable-nav">
<li class="ui-switchable-item selected"><a href="javascript:void(0)"><?php echo position(48) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(49) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(50) ?></a></li>
</ul>
</div>
<!-- tab end -->
<!-- left -->
<div class="sf-l">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 7,1 ');
foreach ($result as $v) {
?><h2><?php echo $v['title'];?></h2><div class="sf-l-pic"><a href="<?php echo $v['link'];?>" target="_blank"><img data-img="2" width="240" height="415" class="err-product" data-ks-lazyload="<?php echo $v['picture'];?>" data-lazy-img="done"></a></div>
<?php }
?>
</div>
<!-- left end -->
<!-- right -->
<div class="sf-r switchable-content">
<div class="item ui-switchable-panel" style="display:block;">
<ul class="item-l clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=7516a3e5acc201767d6514df91348b45&action=position&posid=48&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=7516a3e5acc201767d6514df91348b45&action=position&posid=48&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'48','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=12 AND listorder!=0 AND passed=1 ORDER BY listorder ASC LIMIT 0,5 ');
foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel">
<ul class="item-l clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=de71265a119882c1e2d262e1d0f5a4ec&action=position&posid=49&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=de71265a119882c1e2d262e1d0f5a4ec&action=position&posid=49&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'49','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=12 AND listorder!=0 AND passed=1 ORDER BY listorder ASC LIMIT 0,5 ');
foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" ></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel">
<ul class="item-l clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=10cf0921fe072d0bb96d56175e40059f&action=position&posid=50&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=10cf0921fe072d0bb96d56175e40059f&action=position&posid=50&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'50','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=12 AND listorder!=0 AND passed=1 ORDER BY listorder ASC LIMIT 0,5 ');
foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>"></a> </li>
<?php }
?>
</ul>
</div>
</div>
<!-- right end -->
</div>
<!-- 第1层 end-->
<div class="blank"></div>
<!-- 第2层-->
<div data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'none',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'selected','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable','duration':'0' }" class=" smFloor2 sm-floor m J_TWidget" >
<!-- tab -->
<div class="sf-tab">
<ul class="clearfix switchable-nav">
<li class="ui-switchable-item selected"><a href="javascript:void(0)"><?php echo position(52) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(53) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(54) ?></a></li>
</ul>
</div>
<!-- tab end -->
<!-- left -->
<div class="sf-l">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 8,1 ');
foreach ($result as $v) {
?><h2><?php echo $v['title'];?></h2><div class="sf-l-pic"><a href="<?php echo $v['link'];?>" target="_blank"><img data-img="2" width="240" height="415" class="err-product" data-ks-lazyload="<?php echo $v['picture'];?>" data-lazy-img="done"></a></div>
<?php }
?>
</div>
<!-- left end -->
<!-- right -->
<div class="sf-r switchable-content">
<div class="item ui-switchable-panel" style="display:block;">
<ul class="item-l clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=0806114b2d7e29e00292655d9593da01&action=position&posid=52&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=0806114b2d7e29e00292655d9593da01&action=position&posid=52&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'52','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=13 AND listorder!=0 AND passed=1 ORDER BY listorder ASC LIMIT 0,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel">
<ul class="item-l clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=7eac08aa006f42d1a399aee0961a4b67&action=position&posid=53&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=7eac08aa006f42d1a399aee0961a4b67&action=position&posid=53&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'53','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=13 AND listorder!=0 AND passed=1 ORDER BY listorder ASC LIMIT 0,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel">
<ul class="item-l clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=a3f0160848efdce1e09db65d6969e76e&action=position&posid=54&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=a3f0160848efdce1e09db65d6969e76e&action=position&posid=54&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'54','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=13 AND listorder!=0 AND passed=1 ORDER BY listorder ASC LIMIT 0,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
</div>
<!-- right end -->
</div>
<!-- 第2层 end-->
<div class="blank"></div>
<!-- 第3层-->
<div data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'none',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'selected','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable','duration':'0' }" class=" smFloor3 sm-floor m J_TWidget" >
<!-- tab -->
<div class="sf-tab">
<ul class="clearfix switchable-nav">
<li class="ui-switchable-item selected"><a href="javascript:void(0)"><?php echo position(56) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(57) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(59) ?></a></li>
</ul>
</div>
<!-- tab end -->
<!-- left -->
<div class="sf-l">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 9,1 ');
foreach ($result as $v) {
?><h2><?php echo $v['title'];?></h2><div class="sf-l-pic"><a href="<?php echo $v['link'];?>" target="_blank"><img data-img="2" width="240" height="415" class="err-product" data-ks-lazyload="<?php echo $v['picture'];?>" data-lazy-img="done"></a></div>
<?php }
?>
</div>
<!-- left end -->
<!-- right -->
<div class="sf-r switchable-content">
<div class="item ui-switchable-panel" style="display:block;">
<ul class="item-l clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=603344870232f794a9084e81a9e78222&action=position&posid=56&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=603344870232f794a9084e81a9e78222&action=position&posid=56&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'56','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=14 AND listorder!=0 AND passed=1 ORDER BY listorder ASC LIMIT 0,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel">
<ul class="item-l clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=f0dda6caf5ec09acf940b161f0cdc9fe&action=position&posid=57&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=f0dda6caf5ec09acf940b161f0cdc9fe&action=position&posid=57&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'57','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=14 AND listorder!=0 AND passed=1 ORDER BY listorder ASC LIMIT 0,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel">
<ul class="item-l clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=61ef407b39663a3eaa735c790dc7830f&action=position&posid=59&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=61ef407b39663a3eaa735c790dc7830f&action=position&posid=59&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'59','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=14 AND listorder!=0 AND passed=1 ORDER BY listorder ASC LIMIT 0,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
</div>
<!-- right end -->
</div>
<!-- 第3层 end-->
<div class="blank"></div>
<!-- 第4层-->
<div data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'none',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'selected','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable','duration':'0' }" class=" smFloor1 sm-floor m J_TWidget" >
<!-- tab -->
<div class="sf-tab">
<ul class="clearfix switchable-nav">
<li class="ui-switchable-item selected"><a href="javascript:void(0)"><?php echo position(61) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(62) ?></a></li>
</ul>
</div>
<!-- tab end -->
<!-- left -->
<div class="sf-l">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 10,1 ');
foreach ($result as $v) {
?><h2><?php echo $v['title'];?></h2><div class="sf-l-pic"><a href="<?php echo $v['link'];?>" target="_blank"><img data-img="2" width="240" height="415" class="err-product" data-ks-lazyload="<?php echo $v['picture'];?>" data-lazy-img="done"></a></div>
<?php }
?>
</div>
<!-- left end -->
<!-- right -->
<div class="sf-r switchable-content">
<div class="item ui-switchable-panel" style="display:block;">
<ul class="item-l clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=b6a7ba2bf1d3d1e1edd9e652e18118bc&action=position&posid=61&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=b6a7ba2bf1d3d1e1edd9e652e18118bc&action=position&posid=61&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'61','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=15 AND listorder!=0 AND passed=1 ORDER BY listorder ASC LIMIT 0,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel">
<ul class="item-l clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=3dcf9490e2187bf451a712944a236b78&action=position&posid=62&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=3dcf9490e2187bf451a712944a236b78&action=position&posid=62&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'62','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=15 AND listorder!=0 AND passed=1 ORDER BY listorder ASC LIMIT 0,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
</div>
<!-- right end -->
</div>
<!-- 第4层 end-->
<div class="blank"></div>
<!--banner-->
<div class="banad">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=21 ORDER BY listorder,id ASC LIMIT 6,3 ');
foreach ($result as $v) { if(!empty($v['picture'])){
?><div style="height:5px; clear:both;"></div><a target="_blank" href="<?php echo $v['link'];?>"><img width="1210" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php } }
?>
</div>
<!--banner end-->
</div>
<!-- 友链 -->
<div class="wrap">
<div class="jh">
<?php $result=query('SELECT * FROM jae_link WHERE typeid=0 AND listorder!=0 AND passed=1 ORDER BY listorder ASC LIMIT 0,50 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img data-ks-lazyload="<?php echo $v['logo'];?>"></a>
<?php }
?>
</div>
</div>
<!-- 友链 end-->
<div style="clear:both;"></div>
<?php include template('content','foot');?>
</div>
<file_sep>/upgrade/20140624.sql
DROP TABLE IF EXISTS site_config ;
DROP TABLE IF EXISTS jae_seckill_person;
CREATE TABLE `jae_seckill_person` (
`id` INT(8) NOT NULL AUTO_INCREMENT,
`userid` INT(8) UNSIGNED NOT NULL,
`username` VARCHAR(255) NOT NULL,
`goodsid` INT(8) UNSIGNED NULL DEFAULT NULL,
`date` DOUBLE UNSIGNED NOT NULL,
`regdate` INT(10) UNSIGNED NULL DEFAULT NULL,
`begin_time` INT(10) UNSIGNED NULL DEFAULT NULL,
`end_time` INT(10) UNSIGNED NULL DEFAULT NULL,
PRIMARY KEY (`id`)
)
ENGINE=MyISAM
AUTO_INCREMENT=10;
UPDATE jae_site SET date='20140624' ;
UPDATE jae_site SET version='139';<file_sep>/jae/modules/weblink/templates/weblink_list.tpl.php
<?php include $this->admin_tpl('head','admin');?>
<form name="myform" action="/admin.php?m=weblink&c=weblink&a=init&menuid=<?php echo $this->menuid?>" method="post">
<table class="admin-form-table" cellpadding="0" cellspacing="0" border="0">
<tr>
<th width="145">分类查询</th>
<td width="185"> <select name="info[typeid]">
<option value="0">无分类</option>
<?php
foreach($type as $r){; ?>
<option value="<?php echo $r['typeid']; ?>" <?php if ($r['typeid']==$typeid) echo "selected";?>><?php echo $r['name']; ?></option>
<?php }; ?>
</select></td><td width="60">关键字</td><td><input type="text" name="kw" class=' input-text' value="<?php echo $kw;?>"> <input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>" /> </td> <td> </td><td> </td></tr></table>
</form>
<form name="myform" action="/admin.php?m=weblink&c=weblink&a=listorder" method="post">
<div class="pad-lr-10">
<div class="table-list">
<table width="100%" cellspacing="0" class="table_form">
<tbody>
<tr class="thead">
<th width="20">id</th>
<th width="20">排序</th>
<th width="140">标题</th>
<th width="80">图片</th>
<th width="80">链接</th>
<th width="80" align="center">链接描述</th>
<th width="100">所属站点</th>
<th align=""><?php echo L('operations_manage');?></th>
</tr>
<?php foreach ($data as $r){?>
<tr>
<td><?php echo $r['id'];?></td>
<td ><input name='listorders[<?php echo $r['id'];?>]' type='text' size='3' value='<?php echo $r['listorder'];?>' class='input-text-c input-text'></td>
<td align=""><input style="width:140px;" type="text" name="title[<?php echo $r['id'];?>]" value="<?php echo $r['title'];?>" class="input-text"> </td>
<td align=""><input style="width:140px;" type="text" name="picture[<?php echo $r['id'];?>]" value="<?php echo $r['picture'];?>" class="input-text"></td>
<td align=""><input style="width:140px;" type="text" name="link[<?php echo $r['id'];?>]" value="<?php echo $r['link'];?>" class="input-text"></td>
<td align=""><input style="width:140px;" type="text" name="description[<?php echo $r['id'];?>]" value="<?php echo $r['description'];?>" class="input-text"></td>
<td align=""><?php echo $sitelist[$r['siteid']]['name'];?></td>
<td align=""><?php echo '<a href="/admin.php?m=weblink&c=weblink&a=edit&id='.$r['id'].'&menuid='.$menuid.'">'.L('modify').'</a> | <a href="/admin.php?m=weblink&c=weblink&a=delete&id='.$r['id'].'&menuid='.$menuid.'">'.L('delete').'</a> ';?></td>
</tr>
<?php }?>
</tbody>
</table>
<div class="btns"><input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>" /></div> </div>
</div>
</div>
</form>
<div class="pages"><?php echo $pages;?></div>
<?php include $this->admin_tpl('foot','admin');?><file_sep>/caches/caches_template/default/exchange/show_ex.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head');?>
<link rel="stylesheet" href="/statics/css/exchange.css" />
<div class="jfhgymbg">
<img src="http://img03.taobaocdn.com/imgextra/i3/1089118323/TB2NkSpXFXXXXaMXpXXXXXXXXXX-1089118323.jpg">
</div>
<div class="wrap">
<div class="ex_detail">
<div class="ex_gallery">
<div class="tm-brand"><em><a href="<?php $shop_url?>" target="_blank"> <?php echo $nick;?> </a> </em></div>
<div class="ex_pic"><a href="<?php echo $detail_url ?>" target="_blank"><img width="360" height="360" src="<?php echo $pic_url?>"></a> </div>
</div>
<div class="ex_property">
<div class="tb-detail-hd">
<h3><?php echo $title;?> </h3>
<p> <?php echo $description;?> </p>
</div>
<ul class="tm-fcs-panel">
<li class="tm-promo-panel" id="J_PromoPrice" data-label="促销" style=""><div class="tm-promo-price tm-promo-cur"><em class="tm-yen"></em> <span class="tm-price"><?php echo $point;?></span><em class="tm-promo-type">积分</em> </div></li><li class="tm-price-panel" id="J_StrPriceModBox">原价 <em class="tm-yen"></em> <span class="tm-price"><?php echo $price;?> </span><span>开始时间: <?php echo date("Y-m-d H:i",$begin_time)?></span> <span>结束时间: <?php echo date("Y-m-d H:i",$end_time)?></span></li>
<li class="tm-delivery-panel tm-clear" id="J_RSPostageCont">
</li>
<li class="tm-fcs-corner"></li><li class="tm-fcs-bottom"></li><li class="tm-fcs-label">兑换</li></ul>
<div class="tb-key">
<div class="tb-skin">
<div class="tb-sku"><dl class="tb-amount tm-clear">
<dt class="tb-metatit">数量</dt>
<dd id="J_Amount"><span class="tb-amount-widget mui-amount-wrap">
<?php echo $num?> <span class="mui-amount-unit">件</span>
</span>
<span id="J_StockTips">
</span>
</dd>
</dl>
<div class="tb-action " style="">
<div class="tb-btn-buy tb-btn-sku">
<a href="/index.php?m=order&c=index&a=convert&id=<?php echo $id;?>&module=exchange" data-addfastbuy="true" title="点击此按钮,到下一步确认购买信息。">立刻兑换<b></b></a>
</div>
<div class="tb-btn-basket tb-btn-sku"><a href="<?php echo $detail_url ?>" id="J_LinkBasket" target="_blank">前往原价购买<b></b></a></div>
</div>
</div>
</div>
</div>
<div style=" height:40px; clear:both;"></div>
<div class="hgxqyxux"></div>
<div class="invite_copy">
快来邀请您的朋友成为本馆会员,通过下面的专属链接邀请朋友成为会员,每成功邀请1位可以获得<span><?php $data=getcache_sql('point_invite','commons'); echo $data['point']?></span>积分哟!
<div class="fxcp"><textarea><?php echo $data['content_url']."\r\n".$siteinfo['domain']."index.php?fromuserid=".$memberinfo['userid'] ; ?></textarea></div>
</div>
</div>
</div>
<div class="clear"></div>
<div style=" height:10px; clear:both;"></div>
<div class="jfxqy">
<div class="jfxqyxbt">
宝贝详情 | 换购需知
</div>
<?php $setting=getcache_sql('exchange', 'commons'); echo htmlspecialchars_decode($setting['content']); ?>
</div>
</div>
<file_sep>/jae/modules/mysql/functions/global.func.php
<?php
/**
* 对字段两边加反引号,以保证数据库安全
* @param $value 数组值
*/
function add_special_char(&$value) {
if('*' == $value || false !== strpos($value, '(') || false !== strpos($value, '.') || false !== strpos ( $value, '`')) {
//不处理包含* 或者 使用了sql方法。
} else {
$value = '`'.trim($value).'`';
}
if (preg_match("/\b(select|insert|update|delete)\b/i", $value)) {
$value = preg_replace("/\b(select|insert|update|delete)\b/i", '', $value);
}
return $value;
}
/**
* 对字段值两边加引号,以保证数据库安全
* @param $value 数组值
* @param $key 数组key
* @param $quotation
*/
function escape_string(&$value, $key='', $quotation = 1) {
if ($quotation) {
$q = '"';
} else {
$q = '';
}
$value = '"'.htmlspecialchars($value).'"';
return $value;
}
/**
* 格式化数组成为 INSERT INTO语句
* @param $data 数组值
* @param $replace 布尔值 是否生成 REPLACE INTO 语句
*/
function mysqldump ($table,$data,$replace) {
$variable=array_keys($data[0]);
foreach ($variable as $value) {
if (!intval($value) && $value!=0 && $value!='jae_tenant_nick') $fielddata[]=$value;/*取得数组键名*/
}
array_walk($fielddata, 'add_special_char');
$field = implode (',', $fielddata);
foreach ($data as $z) {
foreach ($z as $k=>$v) {
if (!intval($k) && $k!=0 && $k!='jae_tenant_nick') $valuedata[$k]=$v; //取得数组值
}
array_walk($valuedata, 'escape_string');
$value = implode (',', $valuedata);
$cmd = $replace ? 'REPLACE INTO' : 'INSERT INTO';
$sql.= $cmd.' `'.$table.'`('.$field.') VALUES ('.$value.');';
$sql.= "\r\n";
}
return $sql;
}
?><file_sep>/jae/modules/prize/prize.php
<?php
defined('IN_JAE') or exit('No permission resources.');
defined('IN_ADMIN') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
jae_base::load_app_func('global','admin');
class prize extends admin {
public function __construct() {
parent::__construct();
$this->db = jae_base::load_model('prize_model');
$this->menuid=33;
}
public function init () {
$where=" typeid=2 ";
$page=$_GET['page'];
$data=$this->db->listinfo($where,$order = 'id DESC',$page, $pages = '10');
$pages=$this->db->pages;
include $this->admin_tpl('prize_list');
}
public function prize_real () {
$where=" typeid=0 ";
$page=$_GET['page'];
$data=$this->db->listinfo($where,$order = 'id DESC',$page, $pages = '10');
$pages=$this->db->pages;
include $this->admin_tpl('prize_list');
}
public function add() {
if(isset($_POST['dosubmit'])) {
$data=$_POST['info'];
$this->db->insert($data);
showmessage(L('add_success'));
} else {
$prize_type=jae_base::load_config('prize_type');
include $this->admin_tpl('prize_add');
}
}
public function delete() {
$_GET['id'] = intval($_GET['id']);
$this->db->delete('id='.$_GET['id']);
showmessage(L('operation_success'));
}
public function edit() {
if(isset($_POST['dosubmit'])) {
$id = intval($_POST['id']);
$data=$_POST['info'];
$data['status']=1;
$this->db->update($data,'id='.$id);
showmessage(L('operation_success'));
} else {
$prize_type=jae_base::load_config('prize_type');
$id = intval($_GET['id']);
$r=$this->db->get_one('id='.$id ,'*');
if($r) extract($r);
include $this->admin_tpl('prize_edit');
}
}
/**
* 排序
*/
public function listorder() {
if(isset($_POST['dosubmit'])) {
foreach($_POST['listorders'] as $id => $listorder) {
$listorder = !empty($listorder) ? $listorder : '0';
$this->db->update(array('listorder'=>$listorder),'id='.$id);
$status = isset($_POST["status"][$id]) ? $_POST["status"][$id] : '0';
$this->db->update(array('status'=>$status),'id='.$id);
}
showmessage(L('operation_success'));
} else {
showmessage(L('operation_failure'));
}
}
/**
* 抽奖模块配置
*/
public function setting() {
$m_db = jae_base::load_model('module_model');
$data = $m_db->get_one(array('module'=>'prize'));//array('module'=>'prize')
$setting = string2array($data['setting']);
if(isset($_POST['dosubmit'])) {
$variable = $_POST['setting'];
//更新模型数据库,重设setting 数据.
foreach ($variable as $key => $value) {
$sets[$key]=$value;
}
$sets=new_html_special_chars($sets);
$set = array2string($sets);
setcache('prize', $sets, 'commons');
$m_db->update(array('setting'=>$set), array('module'=>ROUTE_M));
showmessage(L('setting_updates_successful'), '/admin.php?m=prize&c=prize&a=setting&menuid=76');
} else {
@extract($setting);
include $this->admin_tpl('setting');
}
}
}<file_sep>/jae/languages/zh-cn/position.lang.php
<?php
//position.php
$LANG['posid_manage'] = '推荐位管理';
$LANG['posid_add'] = '添加推荐位';
$LANG['posid_edit'] = '编辑推荐位';
$LANG['posid_catid'] = '所属栏目';
$LANG['posid_modelid'] = '所属模型';
$LANG['posid_name'] = '推荐位名称';
$LANG['posid_operation'] = '管理操作';
$LANG['posid_del_success'] = '删除成功!';
$LANG['posid_del_cofirm'] = '是否删除?';
$LANG['posid_item_view'] = '原文';
$LANG['posid_item_edit'] = '原文编辑';
$LANG['posid_item_remove'] = '移出';
$LANG['posid_select_model'] = '请选择模型';
$LANG['posid_select_to_remove'] = '请选择要移出的文章';
$LANG['position_tips'] = '此处如同时未选择模型与栏目,则该为全站通用;如选择模型未选择栏目,则该推荐位在该模型下通用。';
$LANG['posid_syn'] = '修改文章时同步?';
$LANG['posid_title'] = '推荐位标题';
$LANG['posid_thumb'] = '推荐位图片';
$LANG['posid_desc'] = '描述';
$LANG['posid_url'] = '链接地址';
$LANG['posid_inputtime'] = '推荐时间';
$LANG['posid_item_manage'] = '信息管理';
$LANG['posid_all'] = '全部';
$LANG['maxnum'] = '最大保存条数';
$LANG['posid_num'] = '条';
$LANG['extention_name'] = '扩展字段配置';
$LANG['extention_name_tips'] = '<strong>关于扩展字段</strong>:填写模型字段名称后该字段将保存入推荐位扩展字段中,格式:{字段名称}或者functionA({city},argv1),非开发者慎用!';
?><file_sep>/jae/modules/prize/index.php
<?php
defined('IN_JAE') or exit('No permission resources.');
jae_base::load_app_class('foreground','member');
jae_base::load_app_func('global');
class index extends foreground {
public function __construct() {
$this->prize_set_db = jae_base::load_model('prize_set_model');
$this->point_db = jae_base::load_model('point_model');
$this->prize_db = jae_base::load_model('prize_model');
$this->member_db = jae_base::load_model('member_model');
parent::__construct();
}
//活动报名首页
public function init() {
$rules=getcache('prize','commons');
$memberinfo = $this->memberinfo;
$setting=getcache('prize','commons');
$where=" status=1 ";
$prize_arr=$this->prize_set_db->listinfo($where,$order = 'listorder,id DESC',$page, $pages = '12');
$prize_data=$this->prize_db->listinfo($where2,$order = 'id DESC',$page, $pages = '8');
if($setting['enable']==1) {include template('prize','index_f');}
else {include template('prize','index_unable');}
}
public function my_prize() {
$memberinfo = $this->memberinfo;
$page=$_GET['page'];
$where=" userid= $memberinfo[userid]";
$data=$this->prize_db->listinfo($where,$order = 'id DESC',$page, $pages = '10');
$pages=$this->prize_db->pages;
include template('prize','my_prize');
}
public function check() {
$rules=getcache('prize','commons');
if($rules['enable']==0){showmessage(L('sorry'),'/index.php?m=prize'); }
$memberinfo = $this->memberinfo;
/*if(empty($memberinfo['wangwang'])) {showmessage(L('请填写正确的旺旺'),'/index.php?m=member&c=index&a=setinfo');}
if(empty($memberinfo['nickname'])) {showmessage(L('请填写正确的姓名'),'/index.php?m=member&c=index&a=setinfo');}
if(empty($memberinfo['mobile'])) {showmessage(L('请填写正确的手机'),'/index.php?m=member&c=index&a=setinfo');}
if(empty($memberinfo['address'])) {showmessage(L('请填写正确的地址'),'/index.php?m=member&c=index&a=setinfo');}
if(empty($memberinfo['zipcode'])) {showmessage(L('请填写正确的邮编'),'/index.php?m=member&c=index&a=setinfo');}
if(empty($memberinfo['email'])) {showmessage(L('请填写正确的邮箱'),'/index.php?m=member&c=index&a=setinfo');}*/
$prize_data=$this->prize_db->listinfo($where='',$order = 'id DESC',$page, $pages = '8');
$where=" status=1 ";
$prize_arr=$this->prize_set_db->listinfo($where,$order = 'listorder,id DESC',$page, $pages = '12');
$setting=getcache('prize','commons');
if ($memberinfo['point']>=abs($setting['point'])) {
$data= array('userid'=>$memberinfo['userid'],'date'=>SYS_TIME ,'title'=>$setting['title'] ,'picture'=>$setting['picture'],'point'=>$setting['point'],'description'=>$setting['description'],'status'=>'1','typeid'=>'2','module'=>'prize' );//扣除积分
//'typeid'=>'1'类型为签到
$this->point_db->insert($data);
//更新member表积分
$sum=$this->member_db->query("select sum(point) as point from jae_point where userid=".$memberinfo['userid']);
$row = $sum->fetch();
$this->member_db->update(array('point'=>$row['point']),'userid="'.$memberinfo['userid'].'"');
//
$odds_arr=$this->prize_set_db->listinfo($where,$order = 'listorder,id DESC',$page, $pages = '12');
$pro_arr=array();
foreach ($odds_arr as $key=>$value){
$pro_arr[$value['id']]=$value['odds'];//生成概率数组
}
$result=get_rand($pro_arr);//返回中奖的商品ID
/*只要在当天当了一个实物奖品就不能再中实物奖品*/
$prize=$this->prize_set_db->get_one("id=$result");
$begin_time= strtotime(date('Y-m-d',SYS_TIME)) ;
$end_time =$begin_time+86400;
//echo date('Y-m-d H:i:s',$begin_time);echo date('Y-m-d H:i:s',$end_time)
$zj=$this->prize_db->get_one("userid=$memberinfo[userid] AND typeid=0 AND date >$begin_time AND date<$end_time ");
//echo date('Y-m-d H:s:s',$zj['date']);
//echo $zj['id'];echo $prize['typeid'];
if(!empty($zj['id']) && $prize['typeid']==2){ $prize=$this->prize_set_db->get_one("typeid=0");include template('prize','index'); exit();}
/*只要在当天当了一个实物奖品就不能再中实物奖品END*/
if ($prize['typeid']==0||$prize['num']==0){
$prize=$this->prize_set_db->get_one("typeid=0");
$prize_msg= "很遗憾!您没有中奖";
}
else if ($prize['typeid']==1 && $prize['num']!=0){
$prize_msg= "恭喜您中奖了!";
$data= array('userid'=>$memberinfo['userid'],'date'=>SYS_TIME ,'title'=>$prize['title'] ,'picture'=>$prize['picture'],'point'=>$prize['point'],'description'=>$prize['description'],'status'=>'1','typeid'=>'2','module'=>'prize' );
//'typeid'=>'1'类型为签到
$this->point_db->insert($data);
$this->prize_db->insert($data);
//更新奖品剩余量
$num=$prize['num']-1;
$this->prize_set_db->update(array('num'=>$num),"id=$result");
//更新member表积分
$sum=$this->member_db->query("select sum(point) as point from jae_point where userid=".$memberinfo['userid']);
$row = $sum->fetch();
$this->member_db->update(array('point'=>$row['point']),'userid="'.$memberinfo['userid'].'"');
}
else if ($prize['typeid']==2 && $prize['num']!=0){
$data= array('userid'=>$memberinfo['userid'],'date'=>SYS_TIME ,'title'=>$prize['title'] ,'picture'=>$prize['picture'],'point'=>0,'description'=>$prize['description'],'status'=>'0','url'=>$prize['url'],'module'=>'prize' ); //状态为0 奖品未发
$this->prize_db->insert($data);
//更新奖品剩余量
$num=$prize['num']-1;
$this->prize_set_db->update(array('num'=>$num),"id=$result");
$prize_msg= "<a href='/index.php?m=member&c=index&a=setinfo'>恭喜您中奖了!请填写收货地址!</a>";
}
}else {
$prize_msg="您的积分不够";
}
include template('prize','index');
}
public function rules() {
$data=getcache('prize','commons');
include template('prize','rules');
}
}
?><file_sep>/jae/modules/seckill/templates/seckill_list.tpl.php
<?php include $this->admin_tpl('head','admin');?>
<div class="pad-lr-10">
<div class="table-list">
<form action="/admin.php?m=seckill&c=seckill&a=listorder" method="post">
<table width="100%" cellspacing="0" class="table_form">
<tbody>
<tr class="thead">
<th width="40" >删除</th>
<th width="40" >状态</th>
<th width="40" >排序 </th>
<th width="20" >id</th>
<th width="80" >商品图片</th>
<th width="150" >商品名称</th>
<th width="150" >时间</th>
<th width="80" >商品价格</th>
<th width="50" >数量</th>
<th width="50" >系统秒杀</th>
<th width="100" >问答</th>
<th align="center"><?php echo L('operations_manage');?></th>
</tr>
<?php foreach ($data as $r){?>
<tr>
<td align="center"> <input type="checkbox" name="del[<?php echo $r['id']; ?>]" value="1" ></td>
<td align="center"> <input type="checkbox" name="status[<?php echo $r['id']; ?>]" value="1" <?php if( $r['status']==1){echo "checked='checked'";}?> ></td>
<td align="center"><input name='listorders[<?php echo $r['id'];?>]' type='text' size='3' value='<?php echo $r['listorder'];?>' class='input-text-c input-text'></td>
<td align="center"><?php echo $r['id'];?></td>
<td align="center"><a target="_blank" href="<?php echo $r['detail_url']?>"><img src="<?php echo $r['pic_url'];?>" height="40"></a></td>
<td><a target="_blank" href="<?php echo $r['detail_url']?>"><?php echo $r['title'];?></a></td>
<td align="center">上架:<?php echo date('Y-m-d H:i:s',$r['begin_time']); ?><br>
下架:<?php echo date('Y-m-d H:i:s',$r['end_time']); ?></td>
<td align="center">原价:<?php echo $r['price']; ?><br>
现价:<?php echo $r['coupon_price']; ?></td>
<td align="center"><?php echo $r['num']; ?><br>
</td>
<td align="center"><?php if ($r['iskill']==1){echo "<font color=#f00>是</font>";} else {echo "否";} ?>
</td>
<td align="center"><?php echo $r['question']; ?><br><?php echo $r['answer']; ?>
<td align="center"><?php echo '<a href="/admin.php?m=seckill&c=seckill&a=edit&id='.$r['id'].'&menuid='.$menuid.'">'.L('modify').'</a> | <a href="/admin.php?m=seckill&c=seckill&a=delete&id='.$r['id'].'&menuid='.$menuid.'">'.L('delete').'</a> ';?></td>
</tr>
<?php }?>
</tbody>
</table>
<div class="btns">
<input type="submit" class="button" name="dosubmit" value="<?php echo L('提交')?>" />
</div>
</form>
</div>
</div>
<div class="pages"><?php echo $pages;?></div>
<?php include $this->admin_tpl('foot','admin');?>
<file_sep>/jae/modules/member/templates/show_point.tpl.php
<?php include $this->admin_tpl('head','admin');?>
<div class="pad-lr-10">
<form name="searchform" action="" method="get" accept-charset="UTF-8">
<input type="hidden" value="member" name="m">
<input type="hidden" value="seller" name="c">
<input type="hidden" value="init" name="a">
<input type="hidden" value="<?php echo $this->menuid;?>" name="menuid">
<table width="100%" cellspacing="0" class="search-form">
<tbody>
<tr>
<td><div class="explain-col"> USERID
<input name="userid" type="text" value="<?php echo $userid?>" class="input-text">
用户姓名
<input name="nickname" type="text" value="<?php echo $nickname?>" class="input-text">
手机号
<input name="mobile" type="text" value="<?php echo $mobile?>" class="input-text">
<input type="submit" name="search" class="button" value="搜索">
</div></td>
</tr>
</tbody>
</table>
<input name="pc_hash" type="hidden" value="4ua2L3">
</form>
积分:<?php echo $userinfo['point']?> 昵称:<?php echo $userinfo['nickname']?> 电话:<?php echo $userinfo['mobile']?> 旺旺:<?php echo $userinfo['wangwang']?>
<div class="table-list">
<table width="100%" cellspacing="0" class="table_form">
<tbody>
<tr class="thead">
<th width="30"><?php echo L('id');?></th>
<th width="200">标题</th>
<th width="80">图片</th>
<th width="80">积分 </th>
<th width="80">时间 </th>
<th width="80">类型 </th>
<th width="200" align="center"><?php echo L('operations_manage');?></th>
</tr>
<?php foreach ($data as $r){?>
<tr>
<td align="center"><?php echo $r['id'];?></td>
<td align="center"><?php echo $r['title'];?></td>
<td align="center"><img src="<?php echo $r['picture'];?> " height="40"></td>
<td align="center"><?php echo $r['point'];?></td>
<td align="center"><?php echo date('Y-m-d H:i' ,$r['date']);?></td>
<td align="center"><?php echo $r['module'];?></td>
<td align="center"><?php echo '<a href="/admin.php?m=member&c=buyer&a=delete_point&id='.$r['id'].'&userid='.$r['userid'].'&menuid='.$menuid.'">'.L('delete').'</a> | <a href="/admin.php?m=member&c=buyer&a=edit_point&id='.$r['id'].'&userid='.$r['userid'].'&menuid='.$menuid.'">'.L('edit').'</a> ';?></td>
</tr>
<?php }?>
</tbody>
</table>
<div class="pages"><?php echo $pages?></div>
<div class="btns">
<input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>" />
</div>
</div>
</div>
<?php include $this->admin_tpl('foot','admin');?>
<file_sep>/jae/modules/admin/templates/shop_add.tpl.php
<?php include $this->admin_tpl('head');
?>
<?php
echo $createMessage;
?>
<form name="form1" method="post">
<table class="admin-form-table" cellpadding="0" cellspacing="0" border="0">
<tr>
<th width="145">卖家昵称:</th>
<td>
<input class="f-text" type="text" name="nick" value="<?php echo $nick; ?>" size="80">
<input type="hidden" name="dopost" value="caiji">
<input class="f-btn" type="submit" value="获取">
</td>
</tr>
</table>
</form>
<form name="form2" method="post">
<table class="admin-form-table" cellpadding="0" cellspacing="0" border="0">
<tr>
<th width="145">店家昵称:</th>
<td width="380">
<input class="f-text" type="text" name="nick" size="50" value="<?php echo $nick; ?>">
</td>
<td rowspan="5">
<a target="_blank" href="<?php echo $detail_url; ?>">
<img border="0" src="<?php echo $pic_url; ?>" width="200" height="200" />
</a>
</td>
</tr>
<tr>
<th>店铺连接:</th>
<td>
<input class="f-text" type="text" name="detail_url" size="50" value="<?php echo $detail_url; ?>">
</td>
</tr>
<tr>
<th>店家店标:</th>
<td>
<input class="f-text" type="text" name="pic_url" size="50" value="<?php echo $pic_url; ?>">
</td>
</tr>
<tr>
<th>店铺标题:</th>
<td>
<input class="f-text" type="text" name="shop_title" size="50" value="<?php echo $shop_title; ?>">
</td>
</tr>
<tr>
<th>店铺描述:</th>
<td>
<textarea style="width:370px;height:200px" name="description"><?php echo $description; ?></textarea>
</td>
</tr>
<tr>
<input type="hidden" name="sid" size="50" value="<?php echo $sid; ?>"></td>
</tr>
<tr>
<th colspan="3" style="text-align:center;">
<input type="hidden" name="dopost" value="create">
<input class="f-submit" type="submit" value="提交">
</th>
</tr>
</table>
</form>
<?php include $this->admin_tpl('foot');?><file_sep>/jae/modules/admin/index.php
<?php
defined('IN_JAE') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
jae_base::load_app_func('global','admin');
class index extends admin {
public function __construct() {
//$this->db = $pdo = new PDO();
//$this->menu_db = jae_base::load_model('menu_model');
//$this->db = new PDO();
}
public function init () {
include $this->admin_tpl('main');
}
public function index_manage () {include $this->admin_tpl('index_manage');}
//左侧菜单
public function public_menu_left() {
$menuid = intval($_GET['menuid']);
$datas = admin::admin_menu($menuid);
if (isset($_GET['parentid']) && $parentid = intval($_GET['parentid']) ? intval($_GET['parentid']) : 10) {
foreach($datas as $_value) {
if($parentid==$_value['id']) {
echo '<li id="_M'.$_value['id'].'" class="on top_menu"><a href="javascript:_M('.$_value['id'].',\'?m='.$_value['m'].'&c='.$_value['c'].'&a='.$_value['a'].'\')" hidefocus="true" style="outline:none;">'.L($_value['name']).'</a></li>';
} else {
echo '<li id="_M'.$_value['id'].'" class="top_menu"><a href="javascript:_M('.$_value['id'].',\'?m='.$_value['m'].'&c='.$_value['c'].'&a='.$_value['a'].'\')" hidefocus="true" style="outline:none;">'.L($_value['name']).'</a></li>';
}
}
} else {
include $this->admin_tpl('left');
}
}
//当前位置
public function public_current_pos() {
echo admin::current_pos($_GET['menuid']);
exit;
}
public function public_ajax_add_panel() {
$menuid = isset($_POST['menuid']) ? $_POST['menuid'] : exit('0');
$menuarr = $this->menu_db->get_one(array('id'=>$menuid));
$url = '?m='.$menuarr['m'].'&c='.$menuarr['c'].'&a='.$menuarr['a'].'&'.$menuarr['data'];
$data = array('menuid'=>$menuid, 'userid'=>$_SESSION['userid'], 'name'=>$menuarr['name'], 'url'=>$url, 'datetime'=>SYS_TIME);
$this->panel_db->insert($data, '', 1);
$panelarr = $this->panel_db->listinfo(array('userid'=>$_SESSION['userid']), "datetime");
foreach($panelarr as $v) {
echo "<span><a onclick='paneladdclass(this);' target='right' href='".$v['url'].'&menuid='.$v['menuid']."&jae_hash=".$_SESSION['jae_hash']."'>".L($v['name'])."</a> <a class='panel-delete' href='javascript:delete_panel(".$v['menuid'].");'></a></span>";
}
exit;
}
public function public_ajax_delete_panel() {
$menuid = isset($_POST['menuid']) ? $_POST['menuid'] : exit('0');
$this->panel_db->delete(array('menuid'=>$menuid, 'userid'=>$_SESSION['userid']));
$panelarr = $this->panel_db->listinfo(array('userid'=>$_SESSION['userid']), "datetime");
foreach($panelarr as $v) {
echo "<span><a onclick='paneladdclass(this);' target='right' href='".$v['url']."&jae_hash=".$_SESSION['jae_hash']."'>".L($v['name'])."</a> <a class='panel-delete' href='javascript:delete_panel(".$v['menuid'].");'></a></span>";
}
exit;
}
public function public_main() { echo 22;
jae_base::load_app_func('global');
jae_base::load_app_func('admin');
define('jae_VERSION', jae_base::load_config('version','jae_version'));
define('jae_RELEASE', jae_base::load_config('version','jae_release'));
$admin_username = param::get_cookie('admin_username');
$roles = getcache('role','commons');
$userid = $_SESSION['userid'];
$rolename = $roles[$_SESSION['roleid']];
$r = $this->db->get_one(array('userid'=>$userid));
$logintime = $r['lastlogintime'];
$loginip = $r['lastloginip'];
$sysinfo = get_sysinfo();
$sysinfo['mysqlv'] = mysql_get_server_info();
$show_header = $show_jae_hash = 1;
/*检测框架目录可写性*/
$jae_writeable = is_writable(jae_PATH.'base.php');
$common_cache = getcache('common','commons');
$logsize_warning = errorlog_size() > $common_cache['errorlog_size'] ? '1' : '0';
$adminpanel = $this->panel_db->select(array('userid'=>$userid), '*',20 , 'datetime');
$product_copyright = base64_decode('5LiK5rW355ub5aSn572R57uc5Y+R5bGV5pyJ6ZmQ5YWs5Y+4');
$architecture = base64_decode('546L5Y+C5Yqg');
$programmer = base64_decode('546L5Y+C5Yqg44CB6ZmI5a2m5pe644CB546L5a6Y5bqG44CB5byg5LqM5by644CB6YOd5Zu95paw44CB6YOd5bed44CB6LW15a6P5Lyf');
$designer = base64_decode('5byg5LqM5by6');
ob_start();
include $this->admin_tpl('main');
$data = ob_get_contents();
ob_end_clean();
system_information($data);
}
//后台站点地图
public function public_map() {
$array = admin::admin_menu(0);
$menu = array();
foreach ($array as $k=>$v) {
$menu[$v['id']] = $v;
$menu[$v['id']]['childmenus'] = admin::admin_menu($v['id']);
}
$show_header = true;
include $this->admin_tpl('map');
}
}
?><file_sep>/jae/modules/member/seller.php
<?php
defined('IN_JAE') or exit('No permission resources.');
defined('IN_ADMIN') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
jae_base::load_app_func('global','admin');
class seller extends admin {
public function __construct() {
//$this->db = $pdo = new PDO();
//$this->menu_db = jae_base::load_model('menu_model');
parent::__construct();
$this->menuid=42;
$this->db = jae_base::load_model('member_model');
}
public function init () {
$where=' groupid=2 AND islock=1 ';
//ËÑË÷
$userid = isset($_GET['userid']) ? $_GET['userid'] : '';
$nickname = isset($_GET['nickname']) ? $_GET['nickname'] : '';
$mobile = isset($_GET['mobile']) ? $_GET['mobile'] : '';
if (!empty($userid))$where .= " AND `userid` = '$userid'";
if (!empty($nickname))$where .= " AND `nickname` = '$nickname'";
if (!empty($mobile))$where .= " AND `mobile` = '$mobile'";
//ËÑË÷½áÊø
$page=$_GET['page'];
$data=$this->db->listinfo($where,"userid DESC",$page,10);
$pages=$this->db->pages;
include $this->admin_tpl('seller_list');
}
public function seller_check () {
$where='groupid=2 AND islock=0';
$page=$_GET['page'];
$data=$this->db->listinfo($where,"userid DESC",$page,10);
$pages=$this->db->pages;
include $this->admin_tpl('seller_check');
}
function delete() {
$_GET['userid'] = intval($_GET['userid']);
$this->db->delete('userid='.$_GET['userid']);
showmessage(L('operation_success'));
}
function edit() {
if(isset($_POST['dosubmit'])) {
$typeid = intval($_POST['typeid']);
$data=$_POST['info'];
$this->db->update($data,'typeid='.$typeid);
showmessage(L('operation_success'));
include $this->admin_tpl('goods_type_edit');
} else {
$typeid = intval($_GET['typeid']);
$r=$this->db->get_one('typeid='.$typeid);
if($r) extract($r);
include $this->admin_tpl('goods_type_edit');
}
}
public function seller_pass (){
$userid = intval($_GET['userid']);
$data=array('islock'=>1);
$this->db->update($data,'userid='.$userid);
showmessage(L('operation_success','/admin.php?m=member&c=seller&a=seller_check&menuid='.$this->menuid));
}
public function seller_refuse (){
$userid = intval($_GET['userid']);
$data=array('groupid'=>1,'islock'=>1);
$this->db->update($data,'userid='.$userid);
showmessage(L('operation_success','/admin.php?m=member&c=seller&a=seller_check&menuid='.$this->menuid));
}
}<file_sep>/jae/modules/member/templates/seller_list.tpl.php
<?php include $this->admin_tpl('head','admin');?>
<div class="pad-lr-10">
<form name="searchform" action="" method="get" accept-charset="UTF-8">
<input type="hidden" value="member" name="m">
<input type="hidden" value="seller" name="c">
<input type="hidden" value="init" name="a">
<input type="hidden" value="<?php echo $this->menuid;?>" name="menuid">
<table width="100%" cellspacing="0" class="search-form">
<tbody>
<tr>
<td><div class="explain-col"> USERID
<input name="userid" type="text" value="<?php echo $userid?>" class="input-text">
用户姓名
<input name="nickname" type="text" value="<?php echo $nickname?>" class="input-text">
手机号
<input name="mobile" type="text" value="<?php echo $mobile?>" class="input-text">
<input type="submit" name="search" class="button" value="搜索">
</div></td>
</tr>
</tbody>
</table>
<input name="pc_hash" type="hidden" value="4ua2L3">
</form>
<div class="table-list">
<table width="100%" cellspacing="0" class="table_form">
<tbody>
<tr class="thead">
<th width="30"><?php echo L('userid');?></th>
<th width="200">淘宝混肴昵称</th>
<th width="80">用户姓名</th>
<th width="80">入驻时间 </th>
<th width="80">店铺名称 </th>
<th width="80">店铺地址 </th>
<th width="80">店铺简介 </th>
<th width="200" align="center"><?php echo L('operations_manage');?></th>
</tr>
<?php foreach ($data as $r){?>
<tr>
<td align="center"><?php echo $r['userid'];?></td>
<td align="center"><?php echo $r['username'];?></td>
<td align="center"><?php echo $r['nickname'];?></td>
<td align="center"><?php echo date('Y-m-d h:i' ,$r['regdate']);?></td>
<td align="center"><?php echo $r['shop_title'];?></td>
<td align="center"><a href="<?php echo $r['shop_url'];?>" target="_blank">访问店铺</a></td>
<td align="center"><?php echo str_cut($r['shop_profile'],50);?></td>
<td align="center"><?php echo '<a href="/admin.php?m=member&c=buyer&a=edit&userid='.$r['userid'].'&menuid='.$menuid.'">'.L('modify').'</a> | <a href="/admin.php?m=member&c=buyer&a=delete&userid='.$r['userid'].'&menuid='.$menuid.'">'.L('delete').'</a> ';?></td>
</tr>
<?php }?>
</tbody>
</table>
<div class="pages"><?php echo $pages?></div>
<div class="btns">
<input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>" />
</div>
</div>
</div>
<?php include $this->admin_tpl('foot','admin');?>
<file_sep>/caches/caches_template/default/content/index.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head');?>
<div class="fromuser_tips" style="width:1210px; margin:0 auto"></div>
<div class="body_w">1212
<?php echo $site_setting['head_logo'];?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=6127b1a8cefa78966b2d2113fc1116f7&pos=shuichan-8\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=6127b1a8cefa78966b2d2113fc1116f7&pos=shuichan-8\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'shuichan-8',));?><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=a57326cd9b0765ae7cd93b1709dfe5dd&action=lists&id=67&num=4&order=listorder+ASC\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=a57326cd9b0765ae7cd93b1709dfe5dd&action=lists&id=67&num=4&order=listorder+ASC\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$data = $weblink_tag->lists(array('id'=>'67','order'=>'listorder ASC','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<?php echo $r['id'];?><?php echo $r['title'];?><?php echo $r['picture'];?><?php echo $r['link'];?>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=3357de80c19d29def524accf798f4f5d&action=lists&where=+id%3D68++&order=listorder+ASC&limit=2%2C5\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=3357de80c19d29def524accf798f4f5d&action=lists&where=+id%3D68++&order=listorder+ASC&limit=2%2C5\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$data = $weblink_tag->lists(array('where'=>' id=68 ','order'=>'listorder ASC','limit'=>'20',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<?php echo $r['id'];?><?php echo $r['title'];?><?php echo $r['picture'];?><?php echo $r['link'];?>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=8c163e5b37b5cce6c3583dee31bc64a9&action=position&posid=8&order=listorder+asc&num=3\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=8c163e5b37b5cce6c3583dee31bc64a9&action=position&posid=8&order=listorder+asc&num=3\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'8','order'=>'listorder asc','limit'=>'3',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div>
<font color="#f00"> <?php echo $r['catid'];?> | <?php echo $r['listorder'];?>|<?php echo $r['price'];?>|<?php echo $r['coupon_price'];?>|<?php echo $r['inputtime'];?>|<?php echo $r['id'];?></font><?php echo $r['title'];?><?php echo $r['thumb'];?><?php echo $r['url'];?><?php echo $r['description'];?></div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<!--banner1-->
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=21 ORDER BY listorder,id ASC LIMIT 1,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><div style="background-image:url(<?php echo $v['picture'];?>); display:block; height:<?php echo $v['description'];?>px;background-repeat: no-repeat;background-position: center top;"></a></div>
<?php }
?>
<!--banner end-->
<!--首焦-->
<div class="wrap" style="height:420px; position:relative;">
<div class="root61" style="z-index:22">
<div class=" smCategorys">
<div class="sm-c-wrap">
<div class="menu switchable-nav">
<div class="item fore1">
<i class="i1"></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=10 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=10 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore2">
<i class="i2"></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=16 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=16 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore3">
<i class="i3"></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=17 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=17 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore4">
<i class="i4"></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=18 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=18 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore5">
<i class="i5"></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=19 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=19 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="J_MallSlide" class=" timeLine scrollable mall-slide J_TWidget dd" data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'curr','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<!--banner-->
<div class="tl-theme">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=21 ORDER BY listorder,id ASC LIMIT 2,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img width="290" height="68" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<!--banner end-->
<div class="mt">
<i class="line"></i>
<div class="tl-tab-item clearfix switchable-nav">
<a class="curr"><span ><?php echo position(7) ?></span><b></b><i></i></a>
<a><span><?php echo position(8) ?></span><b></b><i></i></a>
<a><span><?php echo position(9) ?></span><b></b><i></i></a>
<a><span><?php echo position(10) ?></span><b></b><i></i></a>
</div>
</div>
<div class="mc switchable-content" style="position: relative; ">
<div class="item ui-switchable-panel" style="position: absolute; ">
<ul class="clearfix">
<?php $result=get_goods(7,9);foreach( $result as $r){ ?>
<li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" target="_blank">
<img class="err-product pimg1029168" width="80" height="80" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?> " src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['detail_url']?>" target="_blank"><?php echo $r['title']?> </a></div>
<div class="p-price" sku="1029168"><strong>¥<?php echo $r['coupon_price']?></strong></div>
</div>
</li>
<?php }?>
</ul>
</div>
<div class="item ui-switchable-panel" style="position: absolute; ">
<ul class="clearfix">
<?php $result=get_goods(8,9);foreach( $result as $r){ ?>
<li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" target="_blank">
<img class="err-product pimg1029168" width="80" height="80" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?> " src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['detail_url']?>" target="_blank"><?php echo $r['title']?> </a></div>
<div class="p-price" sku="1029168"><strong>¥<?php echo $r['coupon_price']?></strong></div>
</div>
</li>
<?php }?>
</ul>
</div>
<div class="item ui-switchable-panel selected" style="position: absolute; ">
<ul class="clearfix">
<?php $result=get_goods(9,9);foreach( $result as $r){ ?>
<li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" target="_blank">
<img class="err-product pimg1029168" width="80" height="80" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?> " src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['detail_url']?>" target="_blank"><?php echo $r['title']?> </a></div>
<div class="p-price" sku="1029168"><strong>¥<?php echo $r['coupon_price']?></strong></div>
</div>
</li>
<?php }?>
</ul>
</div>
<div class="item ui-switchable-panel" style="position: absolute; ">
<ul class="clearfix">
<?php $result=get_goods(10,9);foreach( $result as $r){ ?>
<li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" target="_blank">
<img class="err-product pimg1029168" width="80" height="80" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?> " src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['detail_url']?>" target="_blank"><?php echo $r['title']?> </a></div>
<div class="p-price" sku="1029168"><strong>¥<?php echo $r['coupon_price']?></strong></div>
</div>
</li>
<?php }?>
</ul>
</div>
</div>
</div>
<div style="height:400px;position:absolute;left:-365px; width:710px; left:210px; overflow:hidden" id="J_MallSlide" class="scrollable mall-slide J_TWidget dd" data-widget-type="Carousel" data-widget-config="{'navCls':'ks-switchable-nav','contentCls':'ks-switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [1920], 'circular': true, 'autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<ul class="ks-switchable-content" >
<?php $sql="SELECT * FROM jae_focus WHERE status=1 ORDER BY listorder ASC ";
$r_focus=query($sql);
foreach ($r_focus as $r) {?>
<li class="big-piclist ks-switchable-panel-internal22" style="position:absolute; display: block; opacity: 1; z-index: 9; "> <a href="<?php echo $r["link"]?>" target="_blank"> <img src="<?php echo $r["picture"]?>" width="710" height="400"/></a> </li>
<?php }?>
</ul>
<ul class="ks-switchable-nav">
<?php $r_focuss=query($sql); foreach ($r_focuss as $k=>$rs) {?>
<li <?php if($k==0) echo "class=ks-active" ?>>
<div class="cover"></div>
</li>
<?php }?>
</li>
</ul>
</div>
</div>
<!--banner-->
<div class="banad">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=21 ORDER BY listorder,id ASC LIMIT 3,1 ');
foreach ($result as $v) { if(!empty($v['picture'])){
?><a target="_blank" href="<?php echo $v['link'];?>"><img width="1210" src="<?php echo $v['picture'];?>"></a>
<?php } }
?>
</div>
<!--banner end-->
<!--抽奖 -->
<!--<div style="height:20px; clear:both;"></div>
<div class="wrap root61">
<h2>会员抽奖</h2>
<div class="abenti">
<div class="bejsl">
<?php $result=query('SELECT * FROM jae_prize_set WHERE status=1 ORDER BY listorder,id ASC LIMIT 0,6 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['url'];?>"><img src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="zjsl">
<a target="_blank" href="/index.php?m=prize&c=index&a=init"><img src="/statics/images/cjaniu.jpg"></a>
</div>
<div class="bejsl">
<?php $result=query('SELECT * FROM jae_prize_set WHERE status=1 ORDER BY listorder,id ASC LIMIT 6,6 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['url'];?>"><img src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="clr"></div>
</div>
</div>-->
<!--抽奖end -->
<!--秒杀-->
<div class="wrap root61 m sm-wrap">
<div class=" seckilling" >
<div class="mt">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?><h2><?php echo $v['title'];?></h2>
<?php }
?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?><span class="describe"><?php echo $v['description'];?></span>
<?php }
?>
</div>
</div>
<div class="mc J_TWidget" data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'curr','prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable','autoplay':'true','duration':'1'}">
<div class="sk-time" style="z-index:10">
<!-- <div class="sk-t-text">秒杀倒计时</div> -->
<!--<div class="sk-t-clock"><span>01</span><i>:</i><span>17</span><i>:</i><span>12</span></div> -->
</div>
<!-- 时间tab -->
<div class="sk-tab" style="z-index:10">
<i class="line"></i>
<div class="sk-clock morning" style="left: -29px; "></div>
<div class="sk-tab-item switchable-nav">
<a href="javascript:void(0)" class="left ui-switchable-item killing curr">
<b></b>
<span><?php echo position(14) ?></span>
</a>
<a href="javascript:void(0)" class="center ui-switchable-item">
<b></b>
<span><?php echo position(15) ?></span>
</a>
<a href="javascript:void(0)" class="right ui-switchable-item">
<b></b>
<span><?php echo position(16) ?></span>
</a>
</div>
</div>
<!-- 时间tab end -->
<div class="sk-con switchable-content" >
<div class="sk-item ui-switchable-panel morning selected" style="z-index: 1; opacity: 1; ">
<div class="sk-item-bg">
<span class="sun"></span>
</div>
<ul class="clearfix">
<?php $result=get_goods(14,3);foreach( $result as $r){ ?>
<li><div class="p-img"><a href="<?php echo $r['detail_url'];?>" target="_blank"><img width="180" height="180" src="<?php echo $r['pic_url'];?>" ></a></div><div class="p-name"><a href="<?php echo $r['detail_url'];?>" target="_blank"><?php echo $r['title'];?></a></div><div class="p-price"><strong>¥<?php echo $r['coupon_price'];?></strong><del><?php echo $r['price'];?></del></div><div class="p-btn"><a class="btn-m seckilling" href="<?php echo $r['detail_url'];?>" target="_blank">立即秒杀</a></div></li>
<?php } ?>
</ul>
</div>
<div class="sk-item ui-switchable-panel noon" style="opacity: 0; ">
<div class="sk-item-bg">
<span class="sun"></span>
</div>
<ul class="clearfix">
<?php $result=get_goods(15,3);foreach( $result as $r){ ?>
<li><div class="p-img"><a href="<?php echo $r['detail_url'];?>" target="_blank"><img width="180" height="180" src="<?php echo $r['pic_url'];?>" ></a></div><div class="p-name"><a href="<?php echo $r['detail_url'];?>" target="_blank"><?php echo $r['title'];?></a></div><div class="p-price"><strong>¥<?php echo $r['coupon_price'];?></strong><del><?php echo $r['price'];?></del></div><div class="p-btn"><a class="btn-m seckilling" href="<?php echo $r['detail_url'];?>" target="_blank">立即秒杀</a></div></li>
<?php } ?>
</ul>
</div>
<div class="sk-item ui-switchable-panel night" style="opacity: 0; ">
<div class="sk-item-bg">
<span class="sun"></span>
</div>
<ul class="clearfix">
<?php $result=get_goods(16,3);foreach( $result as $r){ ?>
<li><div class="p-img"><a href="<?php echo $r['detail_url'];?>" target="_blank"><img width="180" height="180" src="<?php echo $r['pic_url'];?>" ></a></div><div class="p-name"><a href="<?php echo $r['detail_url'];?>" target="_blank"><?php echo $r['title'];?></a></div><div class="p-price"><strong>¥<?php echo $r['coupon_price'];?></strong><del><?php echo $r['price'];?></del></div><div class="p-btn"><a class="btn-m seckilling" href="<?php echo $r['detail_url'];?>" target="_blank">立即秒杀</a></div></li>
<?php } ?>
</ul>
</div>
</div>
</div>
</div>
<div class="freshSale" clstag="firsttype|keycount|chaoshi|02">
<div class="mt">
<h2><?php echo position(17) ?></h2>
<div class="ext">
<span class="describe"></span>
</div>
</div>
<div class="mc">
<?php $result=get_goods(17,1);foreach( $result as $r){ ?>
<div class="p-img">
<a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="err-product pimg1050332480" width="240" height="240" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" src="<?php echo $r['pic_url'];?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a>
</div>
<div class="p-ext">
特价优惠,限时抢购!
</div>
<div class="p-price" sku="1050332480">
<strong>¥<?php echo $r['coupon_price'];?></strong>
<del>¥<?php echo $r['price'];?></del>
</div>
<?php }?>
</div>
</div>
<div class="clr" style="clear:both;"></div>
</div>
<div style="height:20px; clear:both;"></div>
<!--9.9包邮 ----->
<div class="wrap root61">
<!-- 新鲜速递 -->
<div class=" freshExpress m sm-wrap J_TWidget" data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [1210], 'circular': true, 'activeTriggerCls':'selected','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable'}" >
<div class="mt">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 1,1 ');
foreach ($result as $v) {
?><h2><?php echo $v['title'];?></h2>
<?php }
?>
<div class="ext switchable-nav">
<a href="javascript:void(0)" class="filter-item selected"><b><?php echo position(18) ?></b></a>
<a href="javascript:void(0)" class="filter-item"><b><?php echo position(20) ?></b></a>
<a href="javascript:void(0)" class="filter-item"><b><?php echo position(21) ?></b></a>
</div>
</div>
<div class="mc switchable-content" style="position: relative; ">
<div class="item ui-switchable-panel selected" style="background-color: rgb(254, 195, 191); position: absolute; z-index: 1; opacity: 1; ">
<span class="fe-pic">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=24 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" alt="" width="350" height="310" class="err-product" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</span>
<ul class="fe-list clearfix">
<?php $result=get_goods(18,10);foreach( $result as $r){ ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="err-product pimg1053862480" width="150" height="150" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" src="<?php echo $r['pic_url'];?>">
</a>
</div>
<div class="p-price" sku="1053862480"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn"><a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a></div>
</div>
</li>
<?php }?>
</ul>
</div><div class="item ui-switchable-panel selected" style="background-color: rgb(254, 195, 191); position: absolute; z-index: 1; opacity: 1; ">
<span class="fe-pic">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=24 ORDER BY listorder,id ASC LIMIT 1,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" alt="" width="350" height="310" class="err-product" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</span>
<ul class="fe-list clearfix">
<?php $result=get_goods(20,10);foreach( $result as $r){ ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="err-product pimg1053862480" width="150" height="150" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" src="<?php echo $r['pic_url'];?>">
</a>
</div>
<div class="p-price" sku="1053862480"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['ddetail_url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn"><a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a></div>
</div>
</li>
<?php }?>
</ul>
</div><div class="item ui-switchable-panel selected" style="background-color: rgb(254, 195, 191); position: absolute; z-index: 1; opacity: 1; ">
<span class="fe-pic">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=24 ORDER BY listorder,id ASC LIMIT 2,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" alt="" width="350" height="310" class="err-product" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</span>
<ul class="fe-list clearfix">
<?php $result=get_goods(21,10);foreach( $result as $r){ ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="err-product pimg1053862480" width="150" height="150" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" src="<?php echo $r['pic_url'];?>">
</a>
</div>
<div class="p-price" sku="1053862480"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['ddetail_url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn"><a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a></div>
</div>
</li>
<?php }?>
</ul>
</div>
</div>
</div>
<!-- 新鲜速递 end -->
<div class="clr"></div>
</div>
<!--9.9包邮end ----->
<div style="height:20px; clear:both;"></div>
<!-- 特色品类 -->
<div class="wrap root61">
<!-- 特色品类 -->
<div class="sort m sm-wrap J_TWidget" data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [1210], 'circular': true, 'activeTriggerCls':'selected','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable'}" >
<div class="mt">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 2,1 ');
foreach ($result as $v) {
?><h2><?php echo $v['title'];?></h2>
<?php }
?>
<div class="ext switchable-nav">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 3,1 ');
foreach ($result as $v) {
?><a href="javascript:void(0)" class="filter-item selected"><b><?php echo $v['title'];?></b></a>
<?php }
?>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 4,2 ');
foreach ($result as $v) {
?><a href="javascript:void(0)" class="filter-item"><b><?php echo $v['title'];?></b></a>
<?php }
?>
</div>
</div>
<div class="mc switchable-content" style="position: relative; ">
<div class="item ui-switchable-panel selected" style="background-color: rgb(255, 255, 255); position: absolute; z-index: 1; opacity: 1; ">
<div class="left">
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(5);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 1,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(6);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 2,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(7);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 3,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(8);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 4,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(9);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 5,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(10);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 6,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(11);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 7,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(12);?> </div>
</div>
</div>
</div><div class="right">
<div class="r1">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 8,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img width="220" height="220" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="r1">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 9,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img width="220" height="220" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
</div>
<div class="clr"></div>
</div><div class="item ui-switchable-panel selected" style="background-color: rgb(255, 255, 255); position: absolute; z-index: 1; opacity: 1; ">
<div class="left">
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(13);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 1,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(14);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 2,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(15);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 3,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(16);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 4,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(17);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 5,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(18);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 6,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(19);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 7,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(20);?> </div>
</div>
</div>
</div><div class="right">
<div class="r1">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 8,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img width="220" height="220" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="r1">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 9,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img width="220" height="220" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
</div>
<div class="clr"></div>
</div><div class="item ui-switchable-panel selected" style="background-color: rgb(255, 255, 255); position: absolute; z-index: 1; opacity: 1; ">
<div class="left">
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(21);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 1,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(22);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 2,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(23);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 3,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(24);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 4,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(25);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 5,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(26);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 6,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(27);?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 7,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(28);?> </div>
</div>
</div>
</div><div class="right">
<div class="r1">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 8,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img width="220" height="220" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="r1">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 9,1 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['link'];?>"><img width="220" height="220" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
</div>
<div class="clr"></div>
</div>
</div>
</div>
<!-- 特色品类 end -->
</div>
<!--banner----->
<div class="banad">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=21 ORDER BY listorder,id ASC LIMIT 4,1 ');
foreach ($result as $v) { if(!empty($v['picture'])){
?><div style="height:25px; clear:both;"></div><a target="_blank" href="<?php echo $v['link'];?>"><img width="1210" src="<?php echo $v['picture'];?>"></a>
<?php } }
?>
</div>
<!--banner end----->
<!-- 本周精选 -->
<div class="wrap" style="height:600px;">
<div class="m sm-wrap snacks" >
<div class="mc" style="position: relative; ">
<div class="item ui-switchable-panel J_TWidget" data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [1210], 'circular': true, 'activeTriggerCls':'selected','autoplay':'false','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable'}" >
<div class="sub-list switchable-nav">
<a href="javascript:void(0)" class="fore8 sub-tab selected"><strong><em><?php echo position(22) ?></em></strong></a>
<a href="javascript:void(0)" class="fore1 sub-tab"><strong><em><?php echo position(23) ?></em></strong></a>
<a href="javascript:void(0)" class="fore2 sub-tab"><strong><em><?php echo position(24) ?></em></strong></a>
<a href="javascript:void(0)" class="fore3 sub-tab"><strong><em><?php echo position(25) ?></em></strong></a>
<a href="javascript:void(0)" class="fore4 sub-tab"><strong><em><?php echo position(26) ?></em></strong></a>
<a href="javascript:void(0)" class="fore5 sub-tab"><strong><em><?php echo position(27) ?></em></strong></a>
<a href="javascript:void(0)" class="fore6 sub-tab"><strong><em><?php echo position(28) ?></em></strong></a>
<a href="javascript:void(0)" class="fore7 sub-tab"><strong><em><?php echo position(29) ?></em></strong></a>
</div>
<div class="sub-con switchable-content">
<div >
<ul class="clearfix sub-item" >
<?php $result=get_goods(22,15);foreach( $result as $r){ ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="err-product pimg787703" width="170" height="170" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" src="<?php echo $r['pic_url'];?>">
</a>
</div>
<div class="p-price" sku="787703"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</div>
</li>
<?php }?>
</ul></div><div >
<ul class="clearfix sub-item" >
<?php $result=get_goods(23,15);foreach( $result as $r){ ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="err-product pimg787703" width="170" height="170" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" src="<?php echo $r['pic_url'];?>">
</a>
</div>
<div class="p-price" sku="787703"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</div>
</li>
<?php }?>
</ul></div><div >
<ul class="clearfix sub-item" >
<?php $result=get_goods(24,15);foreach( $result as $r){ ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="err-product pimg787703" width="170" height="170" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" src="<?php echo $r['pic_url'];?>">
</a>
</div>
<div class="p-price" sku="787703"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</div>
</li>
<?php }?>
</ul></div><div >
<ul class="clearfix sub-item" >
<?php $result=get_goods(25,15);foreach( $result as $r){ ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="err-product pimg787703" width="170" height="170" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" src="<?php echo $r['pic_url'];?>">
</a>
</div>
<div class="p-price" sku="787703"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</div>
</li>
<?php }?>
</ul></div><div >
<ul class="clearfix sub-item" >
<?php $result=get_goods(26,15);foreach( $result as $r){ ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="err-product pimg787703" width="170" height="170" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" src="<?php echo $r['pic_url'];?>">
</a>
</div>
<div class="p-price" sku="787703"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</div>
</li>
<?php }?>
</ul></div><div >
<ul class="clearfix sub-item" >
<?php $result=get_goods(27,15);foreach( $result as $r){ ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="err-product pimg787703" width="170" height="170" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" src="<?php echo $r['pic_url'];?>">
</a>
</div>
<div class="p-price" sku="787703"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</div>
</li>
<?php }?>
</ul></div><div >
<ul class="clearfix sub-item" >
<?php $result=get_goods(28,15);foreach( $result as $r){ ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="err-product pimg787703" width="170" height="170" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" src="<?php echo $r['pic_url'];?>">
</a>
</div>
<div class="p-price" sku="787703"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</div>
</li>
<?php }?>
</ul></div><div >
<ul class="clearfix sub-item" >
<?php $result=get_goods(29,15);foreach( $result as $r){ ?>
<li class="">
<div class="p-img">
<a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">
<img class="err-product pimg787703" width="170" height="170" data-img="1" data-lazy-img="done" alt="<?php echo $r['title'];?>" src="<?php echo $r['pic_url'];?>">
</a>
</div>
<div class="p-price" sku="787703"><strong>¥<?php echo $r['coupon_price'];?></strong></div>
<div class="p-ext">
<div class="p-name"><a href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-btn">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</div>
</li>
<?php }?>
</ul></div>
</div>
</div>
</div>
</div>
</div>
<!-- 美食地理 -->
<div class="wrap root61">
<!-- 美食地理 -->
<div class=" cookingGeology m sm-wrap" clstag="firsttype|keycount|chaoshi|08">
<div class="mt">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 6,1 ');
foreach ($result as $v) {
?><h2><?php echo $v['title'];?></h2>
<?php }
?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 6,1 ');
foreach ($result as $v) {
?><span class="describe"><?php echo $v['description'];?></span>
<?php }
?>
</div>
</div>
<div class="mc">
<!-- 触发器 -->
<div class="cg-trigger">
</div>
<!-- 触发器 end -->
<div class="cg-hide">
<span class="cg-h-close"></span>
<div class="cg-h-title"></div>
</div>
<!-- 隐藏优惠券 end -->
<!-- 遮罩 -->
<div class="cg-mask left"></div>
<div class="cg-mask right"></div>
<!-- 遮罩 end -->
<!-- 左侧国内 -->
<div class="cookingGeologyLeft cg-wrap left J_TWidget" data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [1210], 'circular': true, 'activeTriggerCls':'curr','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable'}" >
<div class="cg-w-tab">
<div class="cg-w-t-item switchable-nav">
<a class="fore1 ui-switchable-item curr" href="javascript:void(0)">
<div class="cg-w-t-label" style="left:-6px; top: -50px; display:none "></div> <b></b>
<span><?php echo position(30) ?></span>
</a>
<a class="fore2 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left:-6px; top: -50px; display:none "></div> <b></b>
<span><?php echo position(31) ?></span>
</a>
<a class="fore3 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left:-6px; top: -50px; display:none "></div> <b></b>
<span><?php echo position(32) ?></span>
</a>
<a class="fore4 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left:-6px; top: -50px; display:none "></div> <b></b>
<span><?php echo position(33) ?></span>
</a>
<a class="fore5 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left:-6px; top: -50px; display:none "></div> <b></b>
<span><?php echo position(34) ?></span>
</a>
<a class="fore6 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left:-6px; top: -50px; display:none "></div> <b></b>
<span><?php echo position(35) ?></span>
</a>
<a class="fore7 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left:-6px; top: -50px; display:none "></div> <b></b>
<span><?php echo position(36) ?></span>
</a>
<a class="fore8 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left:-6px; top: -50px; display:none "></div> <b></b>
<span><?php echo position(37) ?></span>
</a>
<a class="fore9 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left:-6px; top: -50px; display:none "></div> <b></b>
<span><?php echo position(38) ?></span>
</a>
<a class="fore10 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left:-6px; top: -50px; display:none "></div> <b></b>
<span><?php echo position(39) ?></span>
</a>
</div>
</div>
<div class="cg-w-con switchable-content" style="position: relative; ">
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php $result=get_goods(30,4);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul></div><div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php $result=get_goods(31,4);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul></div><div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php $result=get_goods(32,4);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul></div><div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php $result=get_goods(33,4);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul></div><div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php $result=get_goods(34,4);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul></div><div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php $result=get_goods(35,4);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul></div><div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php $result=get_goods(36,4);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul></div><div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php $result=get_goods(37,4);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul></div><div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php $result=get_goods(38,4);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul></div><div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php $result=get_goods(39,4);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul></div><div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php $result=get_goods(40,4);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul></div>
</div>
</div>
<!-- 左侧国内 end-->
<!-- 右侧国际 -->
<div class="cookingGeologyRight cg-wrap right J_TWidget " data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [1210], 'circular': true, 'activeTriggerCls':'curr','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable'}" >
<div class="cg-w-tab">
<div class="cg-w-t-item switchable-nav">
<a class="fore1 ui-switchable-item curr" href="javascript:void(0)">
<div class="cg-w-t-label" style="left: -13px; top: -50px; display:none; "></div> <b></b>
<span><?php echo position(40) ?></span>
</a>
<a class="fore2 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left: -13px; top: -50px; display:none; "></div> <b></b>
<span><?php echo position(41) ?></span>
</a>
<a class="fore3 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left: -13px; top: -50px; display:none; "></div> <b></b>
<span><?php echo position(42) ?></span>
</a>
<a class="fore4 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left: -13px; top: -50px; display:none; "></div> <b></b>
<span><?php echo position(43) ?></span>
</a>
<a class="fore5 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left: -13px; top: -50px; display:none; "></div> <b></b>
<span><?php echo position(44) ?></span>
</a>
<a class="fore6 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left: -13px; top: -50px; display:none; "></div> <b></b>
<span><?php echo position(45) ?></span>
</a>
<a class="fore7 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left: -13px; top: -50px; display:none; "></div> <b></b>
<span><?php echo position(46) ?></span>
</a>
<a class="fore8 ui-switchable-item" href="javascript:void(0)">
<div class="cg-w-t-label" style="left: -13px; top: -50px; display:none; "></div> <b></b>
<span><?php echo position(47) ?></span>
</a>
</div>
</div>
<div class="cg-w-con switchable-content" style="position: relative; ">
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php $result=get_goods(40,4);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul></div><div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php $result=get_goods(41,4);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul></div><div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php $result=get_goods(42,4);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul></div><div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php $result=get_goods(43,4);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul></div><div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php $result=get_goods(44,4);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul></div><div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php $result=get_goods(45,4);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul></div><div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php $result=get_goods(46,4);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul></div><div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php $result=get_goods(47,4);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul></div>
</div>
</div>
</div>
</div>
<!-- 美食地理 end -->
<div class="clr" style="clear:both;"></div>
</div>
<div class="blank"></div>
<!-- 专题 -->
<div class="wrap">
<div class="special">
<ul><li class="s1">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=22 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?><h1><?php echo $v['title'];?></h1><div class="grace"><?php echo $v['description'];?></div><a href="<?php echo $v['link'];?>" target="_blank"><img height="240" width="240" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</li><li class="s2">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=22 ORDER BY listorder,id ASC LIMIT 1,1 ');
foreach ($result as $v) {
?><h1><?php echo $v['title'];?></h1><div class="grace"><?php echo $v['description'];?></div><a href="<?php echo $v['link'];?>" target="_blank"><img height="240" width="240" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</li><li class="s3">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=22 ORDER BY listorder,id ASC LIMIT 2,1 ');
foreach ($result as $v) {
?><h1><?php echo $v['title'];?></h1><div class="grace"><?php echo $v['description'];?></div><a href="<?php echo $v['link'];?>" target="_blank"><img height="240" width="240" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</li><li class="s4">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=22 ORDER BY listorder,id ASC LIMIT 3,1 ');
foreach ($result as $v) {
?><h1><?php echo $v['title'];?></h1><div class="grace"><?php echo $v['description'];?></div><a href="<?php echo $v['link'];?>" target="_blank"><img height="240" width="240" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</li><li class="s5">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=22 ORDER BY listorder,id ASC LIMIT 4,1 ');
foreach ($result as $v) {
?><h1><?php echo $v['title'];?></h1><div class="grace"><?php echo $v['description'];?></div><a href="<?php echo $v['link'];?>" target="_blank"><img height="240" width="240" src="<?php echo $v['picture'];?>"></a>
<?php }
?>
</li>
</ul> </div>
</div>
<div style="height:15px; clear:both;"></div>
<!--banner----->
<div class="banad">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=21 ORDER BY listorder,id ASC LIMIT 5,1 ');
foreach ($result as $v) { if(!empty($v['picture'])){
?><div style="height:20px; clear:both;"></div><a target="_blank" href="<?php echo $v['link'];?>"><img width="1210" src="<?php echo $v['picture'];?>"></a>
<?php } }
?>
</div>
<!--banner end----->
<div class="wrap root61">
<!-- 第1层-->
<div data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'none',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'selected','autoplay':'true','prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable','duration':'0' }" class=" smFloor1 sm-floor m J_TWidget" >
<!-- tab -->
<div class="sf-tab">
<ul class="clearfix switchable-nav">
<li class="ui-switchable-item selected"><a href="javascript:void(0)"><?php echo position(48) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(49) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(50) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(51) ?></a></li>
</ul>
</div>
<!-- tab end -->
<!-- left -->
<div class="sf-l">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 7,1 ');
foreach ($result as $v) {
?><h2><?php echo $v['title'];?></h2><div class="sf-l-pic"><a href="<?php echo $v['link'];?>" target="_blank"><img data-img="2" width="240" height="415" class="err-product" src="<?php echo $v['picture'];?>" data-lazy-img="done"></a></div>
<?php }
?>
</div>
<!-- left end -->
<!-- right -->
<div class="sf-r switchable-content">
<div class="item ui-switchable-panel" style="display:block;">
<ul class="item-l clearfix">
<?php $result=get_goods(48,10);foreach( $result as $r){ ?>
<li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=12 ORDER BY listorder ASC LIMIT 0,5 ');
foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel">
<ul class="item-l clearfix">
<?php $result=get_goods(49,10);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=12 ORDER BY listorder ASC LIMIT 5,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel">
<ul class="item-l clearfix">
<?php $result=get_goods(50,10);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=12 ORDER BY listorder ASC LIMIT 10,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel selected">
<ul class="item-l clearfix">
<?php $result=get_goods(51,10);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=12 ORDER BY listorder ASC LIMIT 15,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
</div>
<!-- right end -->
</div>
<!-- 第1层 end-->
<div class="blank"></div>
<!-- 第2层-->
<div data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'none',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'selected','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable','duration':'0' }" class=" smFloor2 sm-floor m J_TWidget" >
<!-- tab -->
<div class="sf-tab">
<ul class="clearfix switchable-nav">
<li class="ui-switchable-item selected"><a href="javascript:void(0)"><?php echo position(52) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(53) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(54) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(55) ?></a></li>
</ul>
</div>
<!-- tab end -->
<!-- left -->
<div class="sf-l">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 8,1 ');
foreach ($result as $v) {
?><h2><?php echo $v['title'];?></h2><div class="sf-l-pic"><a href="<?php echo $v['link'];?>" target="_blank"><img data-img="2" width="240" height="415" class="err-product" src="<?php echo $v['picture'];?>" data-lazy-img="done"></a></div>
<?php }
?>
</div>
<!-- left end -->
<!-- right -->
<div class="sf-r switchable-content">
<div class="item ui-switchable-panel" style="display:block;">
<ul class="item-l clearfix">
<?php $result=get_goods(52,10);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=13 ORDER BY listorder ASC LIMIT 0,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel">
<ul class="item-l clearfix">
<?php $result=get_goods(53,10);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=13 ORDER BY listorder ASC LIMIT 5,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel">
<ul class="item-l clearfix">
<?php $result=get_goods(54,10);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=13 ORDER BY listorder ASC LIMIT 10,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel selected">
<ul class="item-l clearfix">
<?php $result=get_goods(55,10);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=13 ORDER BY listorder ASC LIMIT 15,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
</div>
<!-- right end -->
</div>
<!-- 第2层 end-->
<div class="blank"></div>
<!-- 第3层-->
<div data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'none',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'selected','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable','duration':'0' }" class=" smFloor3 sm-floor m J_TWidget" >
<!-- tab -->
<div class="sf-tab">
<ul class="clearfix switchable-nav">
<li class="ui-switchable-item selected"><a href="javascript:void(0)"><?php echo position(56) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(57) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(59) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(60) ?></a></li>
</ul>
</div>
<!-- tab end -->
<!-- left -->
<div class="sf-l">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 9,1 ');
foreach ($result as $v) {
?><h2><?php echo $v['title'];?></h2><div class="sf-l-pic"><a href="<?php echo $v['link'];?>" target="_blank"><img data-img="2" width="240" height="415" class="err-product" src="<?php echo $v['picture'];?>" data-lazy-img="done"></a></div>
<?php }
?>
</div>
<!-- left end -->
<!-- right -->
<div class="sf-r switchable-content">
<div class="item ui-switchable-panel" style="display:block;">
<ul class="item-l clearfix">
<?php $result=get_goods(56,10);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=14 ORDER BY listorder ASC LIMIT 0,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel">
<ul class="item-l clearfix">
<?php $result=get_goods(57,10);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=14 ORDER BY listorder ASC LIMIT 5,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel">
<ul class="item-l clearfix">
<?php $result=get_goods(59,10);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=14 ORDER BY listorder ASC LIMIT 10,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel selected">
<ul class="item-l clearfix">
<?php $result=get_goods(60,10);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=14 ORDER BY listorder ASC LIMIT 15,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
</div>
<!-- right end -->
</div>
<!-- 第3层 end-->
<div class="blank"></div>
<!-- 第4层-->
<div data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'none',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'selected','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable','duration':'0' }" class=" smFloor4 sm-floor m J_TWidget" >
<!-- tab -->
<div class="sf-tab">
<ul class="clearfix switchable-nav">
<li class="ui-switchable-item selected"><a href="javascript:void(0)"><?php echo position(61) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(62) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(63) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(64) ?></a></li>
</ul>
</div>
<!-- tab end -->
<!-- left -->
<div class="sf-l">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 10,1 ');
foreach ($result as $v) {
?><h2><?php echo $v['title'];?></h2><div class="sf-l-pic"><a href="<?php echo $v['link'];?>" target="_blank"><img data-img="2" width="240" height="415" class="err-product" src="<?php echo $v['picture'];?>" data-lazy-img="done"></a></div>
<?php }
?>
</div>
<!-- left end -->
<!-- right -->
<div class="sf-r switchable-content">
<div class="item ui-switchable-panel" style="display:block;">
<ul class="item-l clearfix">
<?php $result=get_goods(61,10);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=15 ORDER BY listorder ASC LIMIT 0,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel">
<ul class="item-l clearfix">
<?php $result=get_goods(62,10);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=15 ORDER BY listorder ASC LIMIT 5,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel">
<ul class="item-l clearfix">
<?php $result=get_goods(63,10);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=15 ORDER BY listorder ASC LIMIT 10,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel selected">
<ul class="item-l clearfix">
<?php $result=get_goods(64,10);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=15 ORDER BY listorder ASC LIMIT 15,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
</div>
<!-- right end -->
</div>
<!-- 第4层 end-->
<div class="blank"></div>
<!-- 第5层-->
<div data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'none',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'selected','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable','duration':'0' }" class=" smFloor2 sm-floor m J_TWidget" >
<!-- tab -->
<div class="sf-tab">
<ul class="clearfix switchable-nav">
<li class="ui-switchable-item selected"><a href="javascript:void(0)"><?php echo position(65) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(66) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(67) ?></a></li>
<li class="ui-switchable-item"><a href="javascript:void(0)"><?php echo position(68) ?></a></li>
</ul>
</div>
<!-- tab end -->
<!-- left -->
<div class="sf-l">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 11,1 ');
foreach ($result as $v) {
?><h2><?php echo $v['title'];?></h2><div class="sf-l-pic"><a href="<?php echo $v['link'];?>" target="_blank"><img data-img="2" width="240" height="415" class="err-product" src="<?php echo $v['picture'];?>" data-lazy-img="done"></a></div>
<?php }
?>
</div>
<!-- left end -->
<!-- right -->
<div class="sf-r switchable-content">
<div class="item ui-switchable-panel" style="display:block;">
<ul class="item-l clearfix">
<?php $result=get_goods(65,10);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=16 ORDER BY listorder ASC LIMIT 0,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel">
<ul class="item-l clearfix">
<?php $result=get_goods(66,10);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=16 ORDER BY listorder ASC LIMIT 5,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel">
<ul class="item-l clearfix">
<?php $result=get_goods(67,10);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=16 ORDER BY listorder ASC LIMIT 10,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
<div class="item ui-switchable-panel selected">
<ul class="item-l clearfix">
<?php $result=get_goods(68,10);foreach( $result as $r){ ?> <li>
<div class="p-img">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="err-product pimg499985" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" src="<?php echo $r['pic_url']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['detail_url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="499985">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['detail_url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php }?>
</ul>
<ul class="item-r">
<?php $result=query('SELECT * FROM jae_brand WHERE typeid=16 ORDER BY listorder ASC LIMIT 15,5 '); foreach ($result as $v) {
?><li><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img class="err-product" width="130" height="70" data-img="2" alt="" src="<?php echo $v['logo'];?>" data-lazy-img="done"></a> </li>
<?php }
?>
</ul>
</div>
</div>
<!-- right end -->
</div>
<!-- 第5层 end-->
<div class="blank"></div>
<!--banner----->
<div class="banad">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=21 ORDER BY listorder,id ASC LIMIT 6,3 ');
foreach ($result as $v) { if(!empty($v['picture'])){
?><div class="blank10"></div><a target="_blank" href="<?php echo $v['link'];?>"><img width="1210" src="<?php echo $v['picture'];?>"></a><div style="height:5px; clear:both;"></div>
<?php } }
?>
</div>
<!--banner end----->
</div>
<!-- 友链 -->
<div class="wrap">
<div class="jh">
<?php $result=query('SELECT * FROM jae_link WHERE typeid=0 ORDER BY listorder ASC LIMIT 0,50 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img src="<?php echo $v['logo'];?>"></a>
<?php }
?>
</div>
</div>
<!-- 友链 end-->
<div style="clear:both;"></div>
<?php include template('content','foot');?>
</div><file_sep>/jae/modules/member/templates/buyer_list.tpl.php
<?php include $this->admin_tpl('head','admin');?>
<div class="pad-lr-10">
<form name="searchform" action="" method="get" accept-charset="UTF-8">
<input type="hidden" value="member" name="m">
<input type="hidden" value="buyer" name="c">
<input type="hidden" value="init" name="a">
<input type="hidden" value="<?php echo $this->menuid;?>" name="menuid">
<table width="100%" cellspacing="0" class="search-form">
<tbody>
<tr>
<td><div class="explain-col"> USERID
<input name="userid" type="text" value="<?php echo $userid?>" class="input-text">
用户姓名
<input name="nickname" type="text" value="<?php echo $nickname?>" class="input-text">
手机号
<input name="mobile" type="text" value="<?php echo $mobile?>" class="input-text">
<input type="submit" name="search" class="button" value="搜索">
</div></td>
</tr>
</tbody>
</table>
<input name="pc_hash" type="hidden" value="4ua2L3">
</form>
<div class="table-list">
<table width="100%" cellspacing="0" class="table_form">
<tbody>
<tr class="thead">
<th width="30"><?php echo L('userid');?></th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=nickname">邀请ID</a></th>
<th width="80">淘宝混肴昵称</th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=nickname">用户姓名</a></th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=wangwang">旺旺</a></th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=mobile">手机</a></th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=address">地址</a></th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=address">EMAIL</a></th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=regdate">入驻时间</a> </th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=lastdate">最后登录时间</a> </th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=loginnum">活跃指数</a> </th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=point">积分</a></th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=vip">vip</a></th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=point">签到次数</a> </th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=point">最后签到天数</a> </th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=point">最后签到时间</a> </th>
<th align="center"><?php echo L('operations_manage');?></th>
</tr>
<?php foreach ($data as $r){ $last_sign=$this->point_db->get_one("userid=".$r['userid'], $data = '*',$order =' date desc');?>
<tr>
<td align="center"><a href="/admin.php?m=member&c=buyer&a=show&userid=<?php echo $r['userid'];?>&menuid=<?php echo $menuid?>"><?php echo $r['userid'];?></a></td>
<td align="center"><a href="/admin.php?m=member&c=buyer&a=show&userid=<?php echo $r['fromuserid'];?>&menuid=<?php echo $menuid?>"><?php echo $r['fromuserid'];?></a></td>
<td align="center" title="<?php echo $r['username'];?>"><a href="/admin.php?m=member&c=buyer&a=show&userid=<?php echo $r['userid'];?>&menuid=<?php echo $menuid?>"><?php echo str_cut($r['username'],5) ;?></a></td>
<td align="center"><?php echo $r['nickname'];?></td>
<td align="center"><?php echo $r['wangwang'];?></td>
<td align="center"><?php echo $r['mobile'];?></td>
<td align="center" title="<?php echo $r['address'];?>"><?php echo str_cut($r['address'],20);?></td>
<td align="center"><?php echo $r['email'];?></td>
<td align="center"><?php echo date('Y-m-d H:i' ,$r['regdate']);?></td>
<td align="center"><?php echo date('Y-m-d H:i' ,$r['lastdate']);?></td>
<td align="center"><?php echo $r['loginnum'];?></td>
<td align="center"><a href="/admin.php?m=member&c=buyer&a=show&userid=<?php echo $r['userid'];?>&menuid=<?php echo $menuid?>"><?php echo $r['point'];?></a></td>
<td align="center"><?php echo $r['vip'];?></td>
<td align="center"><?php echo $sign_num=$this->point_db->count("userid=".$r['userid']." AND typeid=1");?></td>
<td align="center"><?php echo $last_sign['continue'];?></td>
<td align="center"><?php echo date('Y-m-d H:i',$last_sign['date']);?></td>
<td align="center"><?php echo '<a href="/admin.php?m=member&c=buyer&a=edit&userid='.$r['userid'].'&menuid='.$menuid.'">'.L('modify').'</a> ';?></td>
</tr>
<?php }?>
</tbody>
</table>
<div class="btns">
<input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>" />
</div>
</div>
<div class="pages"><?php echo $pages?></div>
</div>
<?php include $this->admin_tpl('foot','admin');?>
<file_sep>/api/focus.php
<?php
header("KissyIoDataType:jsonp");
// exit($_GET['callback'].'('.json_encode(array('data'=>'222')).')');
exit($_GET['callback']."({\"status\":200,\"data\":\"kissy.io ÖÐÎÄ. URLÖÐÎÄ".$_GET["encodeCpt"]." ,".urldecode_utf8($_GET["encode"])."\"})");
?>
<?php
// header("KissyIoDataType:jsonp");
// $focus_db=jae_base::load_model('focus_model');
// $prizes=$prize_db->count("userid=$memberinfo[userid]");
// exit($_GET['callback'].'('.json_encode(array('tips'=>$tips,'point'=>$memberinfo['point'],'login'=>$login,'prizes'=>$prizes,'orders'=>$orders)).')');
?><file_sep>/caches/caches_template/default/content/list_shop.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head');?>
<!-- 商品列表开始 -->
<div class="wrap">
<div class="shop_list">
<ul>
<?php
$db= jae_base::load_model('shop_model');
$where=" status=1 ";
$data=$db->listinfo($where,$order = 'listorder,id DESC',$page, $pages = '10');
$pages=$goods_db->pages;
foreach($data as $shop){ ?>
<li> <a class="img" href="<?php echo $shop['detail_url'] ?>" target="_blank"><img src="<?php echo $shop['pic_url']; ?>" width="290" height="290"></a><a class="title" href="<?php echo $shop['detail_url'] ?>" target="_blank"><?php echo $shop['shop_title']; ?></a> </li>
<?php }; ?>
</ul>
<div class="clear" style="clear:both" ></div>
</div>
</div>
<!-- 列表分页 -->
<div class="pages">
<?php echo $pages; ?>
</div>
<?php include template('content','foot');?><file_sep>/jae/modules/admin/templates/special_css.tpl.php
<?php include $this->admin_tpl('head');?>
<form name="myform" action="/admin.php?m=admin&c=special&a=listorder" method="post">
<div class="pad-lr-10">
<div class="table-list">
<table width="100%" cellspacing="0" class="table_form">
<tbody>
<tr class="thead">
<th width="20" align="left">ID</th>
<th width="200" align="left">标题</th>
<th align="left"><?php echo L('operations_manage');?></th>
</tr>
<?php foreach($data as $v){
$path=special_css($v['id'],$v['css']);
?>
<tr> <td align="left"><?php echo $v['id'];?></td>
<td align="left"><?php echo $v['title'];?></td>
<td align="left"><?php echo '成功生成CSS文件'.$path.''?></td>
</tr>
<?php }?>
</tbody>
</table>
<div class="btns"><input type="submit" class="button" name="dosubmit" value="<?php echo L('listorder')?>" /></div> </div>
</div>
</div>
</form>
<div class="pages"><?php echo $pages;?></div>
<?php include $this->admin_tpl('foot');?><file_sep>/jae/modules/admin/templates/menu.tpl.php
<?php include $this->admin_tpl('head');?>
<form name="myform" action="/admin.php?m=admin&c=menu&a=listorder" method="post">
<div class="pad-lr-10">
<div class="table-list">
<table width="100%" cellspacing="0" class="table_form">
<tr class="thead">
<th width="80"><?php echo L('listorder');?></th>
<th width="100">id</th>
<th><?php echo L('menu_name');?></th>
<th width="200" align="center"><?php echo L('operations_manage');?></th>
</tr>
<?php echo $categorys;?>
</table>
<div class="btns"><input type="submit" class="button" name="dosubmit" value="<?php echo L('listorder')?>" /></div> </div>
</div>
</div>
</form>
<?php include $this->admin_tpl('foot');?><file_sep>/jae/modules/admin/article.php
<?php
defined('IN_JAE') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
class article extends admin {
function __construct() {
parent::__construct();
$this->db =jae_base::load_sys_class('mysql');
$this->table='jae_article';
$this->menuid=25;
}
function init () {
$page=$_GET['page'];
$data=$this->db->listinfo("*",$this->table,"","id DESC",$page,10);
$pages=$this->db->pages;
include $this->admin_tpl('article_list');
}
function add() {
if(isset($_POST['dosubmit'])) {
$data=$_POST['info'];
$this->db->insert($data,$this->table);
include $this->admin_tpl('article_add');
showmessage(L('add_success'));
} else {
include $this->admin_tpl('article_add');
}
}
function delete() {
$_GET['id'] = intval($_GET['id']);
$this->db->delete($this->table,'id='.$_GET['id']);
showmessage(L('operation_success'));
}
function edit() {
if(isset($_POST['dosubmit'])) {
$id = intval($_POST['id']);
$data=$_POST['info'];
$this->db->update($data,$this->table,'id='.$id);
showmessage(L('operation_success'));
include $this->admin_tpl('article_edit');
} else {
$id = intval($_GET['id']);
$r=$this->db->get_one('*',$this->table,'id='.$id);
if($r) extract($r);
include $this->admin_tpl('article_edit');
}
}
function listorder() {
if(isset($_POST['dosubmit'])) {
foreach($_POST['listorders'] as $id => $listorder) {
$listorder = !empty($listorder) ? $listorder : '0';
$this->db->update(array('listorder'=>$listorder),$this->table,'id='.$id);
$status = isset($_POST["status"][$id]) ? $_POST["status"][$id] : '0';
$this->db->update(array('status'=>$status),$this->table,'id='.$id);
}
showmessage(L('operation_success'));
} else {
showmessage(L('operation_failure'));
}
}
}
?><file_sep>/admin.php
<?php
define('JAE_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR);
define('IN_ADMIN',true);
include JAE_PATH.'/jae/base.php';
$_GET['m']? $_GET['m'] : $_GET['m']='admin';
jae_base::creat_app();
?><file_sep>/caches/caches_template/neimeng2/content/index(冲突_2013-1207-1448_2014-09-05 09-32-38).php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head');?>
<link rel="stylesheet" href="/statics/css/lows.css" />
<div class="lows-banner J_TWidget" style="display:none" id="J_LowsBanner" data-widget-type="Carousel" data-widget-config="{'navCls':'ks-switchable-nav','contentCls':'ks-switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'active','autoplay':'true','interval':3,'prevBtnCls': 'prev', 'nextBtnCls': 'next', 'disableBtnCls': 'disable' }">
<div class="trigger-wrap">
<span class="close J_LowsClose"></span>
<span class="prev"></span>
<span class="next"></span>
<ol class="lows-trigger ks-switchable-nav">
<li class="ks-switchable-trigger-internal297 active"></li>
<li class="ks-switchable-trigger-internal297 "></li>
<li class="ks-switchable-trigger-internal297"></li>
</ol>
</div>
<ul class="ks-switchable-content clear-fix">
<li class="pic1 ks-switchable-panel-internal298" style="display: block; opacity: 0; position: absolute; z-index: 1; "><div class="banner-pic" style="background: url(http://img03.taobaocdn.com/imgextra/i3/1863579612/TB2_FMOXVXXXXX7XpXXXXXXXXXX-1863579612.png) no-repeat 0 0;"></div></li>
<li class="pic2 ks-switchable-panel-internal298" style="display: block; opacity: 1; position: absolute; z-index: 9; "><div class="banner-pic" style="background: url(http://img04.taobaocdn.com/imgextra/i4/1863579612/TB2VhgOXVXXXXbaXXXXXXXXXXXX-1863579612.png) no-repeat 0 0;"></div></li>
<li class="pic3 ks-switchable-panel-internal298" style="display: block; opacity: 0; position: absolute; z-index: 1; "><div class="banner-pic" style="background: url(http://img02.taobaocdn.com/imgextra/i2/1863579612/TB2G4ZOXVXXXXXGXXXXXXXXXXXX-1863579612.png) no-repeat 0 0;"></div></li>
</ul>
</div>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=c48e16dbd8278d8301abbc5c84a59774&action=lists&id=185&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=c48e16dbd8278d8301abbc5c84a59774&action=lists&id=185&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'185','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<div class="body_w" style="background-image:url(<?php echo $r['picture'];?>);background-repeat: repeat;">
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<!--首焦-->
<div class="wrap" style="height:420px; position:relative;">
<div class="root61" style="z-index:22">
<div class=" smCategorys">
<div class="sm-c-wrap">
<div class="menu switchable-nav">
<div class="item fore1">
<i class="i1"></i>
<span class="blank"></span>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=fbfd1bf4a40dbeac9ac0541dc24484f6&action=lists&typeid=10&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=fbfd1bf4a40dbeac9ac0541dc24484f6&action=lists&typeid=10&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'10','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<h3><a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a></h3>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<div class="ext">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=659bfc50112d9edffb3f5716f62311d9&action=lists&typeid=10&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=659bfc50112d9edffb3f5716f62311d9&action=lists&typeid=10&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'10','order'=>'listorder ASC','limit'=>'20',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?><?php if($n>1) { ?>
<a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a>
<?php } ?>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
<div class="item fore2">
<i class="i2"></i>
<span class="blank"></span>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=ea0a9866571de93d8ad19c9250246eec&action=lists&typeid=16&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=ea0a9866571de93d8ad19c9250246eec&action=lists&typeid=16&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'16','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<h3><a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a></h3>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<div class="ext">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=10afa1e3dd018f0207be14f349ae285c&action=lists&typeid=16&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=10afa1e3dd018f0207be14f349ae285c&action=lists&typeid=16&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'16','order'=>'listorder ASC','limit'=>'20',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?><?php if($n>1) { ?>
<a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a>
<?php } ?>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
<div class="item fore3">
<i class="i3"></i>
<span class="blank"></span>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=0d04e7787a9a3af53f5c85854f01db9b&action=lists&typeid=17&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=0d04e7787a9a3af53f5c85854f01db9b&action=lists&typeid=17&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'17','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<h3><a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a></h3>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<div class="ext">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=dc6f3f04b7c0bf5f710b33211db949a2&action=lists&typeid=17&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=dc6f3f04b7c0bf5f710b33211db949a2&action=lists&typeid=17&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'17','order'=>'listorder ASC','limit'=>'20',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?><?php if($n>1) { ?>
<a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a>
<?php } ?>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
<div class="item fore4">
<i class="i4"></i>
<span class="blank"></span>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=1ef57e5654162d5aead24c6937597b6c&action=lists&typeid=18&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=1ef57e5654162d5aead24c6937597b6c&action=lists&typeid=18&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'18','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<h3><a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a></h3>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<div class="ext">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=86b75660d3e42ee4e29123012301db19&action=lists&typeid=18&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=86b75660d3e42ee4e29123012301db19&action=lists&typeid=18&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'18','order'=>'listorder ASC','limit'=>'20',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?><?php if($n>1) { ?>
<a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a>
<?php } ?>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
<div class="item fore5">
<i class="i5"></i>
<span class="blank"></span>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=dd282ce42fde959e6a44cda1e470685e&action=lists&typeid=19&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=dd282ce42fde959e6a44cda1e470685e&action=lists&typeid=19&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'19','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<h3><a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a></h3>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<div class="ext">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=158246be5f5778db2fd5132944aca82a&action=lists&typeid=19&order=listorder+ASC+&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=158246be5f5778db2fd5132944aca82a&action=lists&typeid=19&order=listorder+ASC+&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('typeid'=>'19','order'=>'listorder ASC ','limit'=>'20',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?><?php if($n>1) { ?>
<a href="<?php echo $r['link'];?>" target="_blank"><?php echo $r['title'];?></a>
<?php } ?>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!--shoujiao-->
<div class="sjjz" style="position:relative; width:1210px; margin:0 auto;">
<div class="qpsj " style="position:absolute; width:1920px; left:-355px;">
<div class="focus J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'tab-nav','contentCls':'tab-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [1920], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<div class="prev"></div><div class="next"></div>
<div class="tab-content">
<?php $sql="SELECT * FROM jae_focus WHERE status=1 ORDER BY listorder ASC ";
$r_focus=query($sql); foreach ($r_focus as $r) {?>
<div><a href="<?php echo $r["link"]?>" target="_blank"> <img src="<?php echo $r['picture'];?>" height="400"/></a></div>
<?php }?>
</div>
<div class="tab-nav">
<?php $r_focuss=query($sql); foreach ($r_focuss as $k=>$rs) {?>
<div class="v<?php echo $k?>"></div>
<?php }?>
</div>
</div>
</div>
</div>
<!--shoujia end-->
<div class="wrap">
<div class="fl" style="margin-right:5px;">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=c6fd7403822181b7450aa0463594257b&action=lists&id=170&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=c6fd7403822181b7450aa0463594257b&action=lists&id=170&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'170','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a href="<?php echo $r['link'];?>" target="_blank"><img src="<?php echo $r['picture'];?>" /></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="fl">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=a5257e2deba1329b6d9f53dabda02949&action=lists&id=171&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=a5257e2deba1329b6d9f53dabda02949&action=lists&id=171&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'171','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a href="<?php echo $r['link'];?>" target="_blank"><img src="<?php echo $r['picture'];?>" /></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="fr">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=b6b19278882c73e9be2ab6d026b3a3b8&action=lists&id=172&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=b6b19278882c73e9be2ab6d026b3a3b8&action=lists&id=172&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'172','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a href="<?php echo $r['link'];?>" target="_blank"><img src="<?php echo $r['picture'];?>" /></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div>
<div class="blank"></div>
<!--秒杀-->
<div class="wrap">
<div class="sec">
<a href="http://neimenggu.china.taobao.com/index.php?spm=a216r.7173997.1.15.cSK9Dn&m=seckill&c=index&a=init" target="_blank">
<?php $hour=Date('Hs',SYS_TIME); ?>
<div class="time <?php if (800<$hour && $hour<=1000 ){ echo "current";}?> ">
<span><?php if (800<$hour && $hour<=1000 ){ echo "秒杀开始";} elseif($hour>=1000){ echo "秒杀结束";} elseif ($hour<800) {echo "即将开始"} ?></span>
<i>10:00</i>
</div>
<div class="time <?php if (1000<$hour && $hour<=1200 ){ echo "current";}?> ">
<span><?php if (1000<$hour && $hour<=1200 ){ echo "秒杀开始";}elseif ($hour >1200) { echo "秒杀结束";} elseif ($hour<1000){echo "即将开始"} ?></span>
<i>12:00</i>
</div>
<div class="time <?php if (1200<$hour && $hour<=1500 ){ echo "current";}?> ">
<span><?php if (1200<$hour && $hour<=1500 ){ echo "秒杀开始";}elseif($hour > 1500) { echo "秒杀结束";} elseif ($hour <1200) { echo "即将开始"} ?></span>
<i>15:00</i>
</div>
<div class="time <?php if ( 1500 <$hour && $hour <= 1700 ) echo 'current';?>">
<span><?php if (1500<$hour && $hour<=1700 ){ echo "秒杀开始";}elseif( $hour >1700) { echo "秒杀结束";} elseif ($hour <1500) { echo "即将开始";} ?></span>
<i>17:00</i>
</div>
<div class="time <?php if (1700<$hour && $hour<=2000 ){ echo "current";}?> ">
<span><?php if (1700<$hour && $hour<=2000 ){ echo "秒杀开始";}elseif($hour >2000) { echo "秒杀结束"} elseif ($hour <1700){echo "即将开始"} ?></span>
<i>20:00</i>
</div>
<div class="time <?php if (2000<$hour && $hour<=2200 ){ echo "current";}?> ">
<span><?php if (2000<$hour && $hour<=2200 ){ echo "秒杀开始";}elseif($hour >2200) { echo "秒杀结束";} elseif ( $hour<2000){echo "即将开始";} ?></span>
<i>22:00</i>
</div>
</a>
</div>
</div>
<!--秒杀-->
<!--优质推荐-->
<div style="height:10px;"></div>
<div class="wrap">
<div class="youzhi J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'tab-nav','contentCls':'tab-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [620], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<div class="title">
<div class="swap tab-nav"><span>居家美食</span><span>休闲时光</span></div>
</div>
<div class="con tab-content">
<div class="list ">
<ul>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=5bfa118c5016d7da71b62173639c88b9&action=position&posid=74&order=listorder+asc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=5bfa118c5016d7da71b62173639c88b9&action=position&posid=74&order=listorder+asc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'74','order'=>'listorder asc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li> <a href="<?php echo $r['url'];?>" target="_blank"><img height="280" src="<?php echo $r['thumb'];?>" width="280" /><br />
<div class="txt"><?php echo $r['title'];?></div>
<div class="sj"><span class="jg">¥<?php echo round($r['coupon_price']);?></span><span class="yj">原价:¥<?php echo $r['price'];?></span></div><span class="gm"></span></a></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div><div class="list ">
<ul>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=c8d6e59d4cbda79230ea74157bcaaa9d&action=position&posid=75&order=listorder+asc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=c8d6e59d4cbda79230ea74157bcaaa9d&action=position&posid=75&order=listorder+asc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'75','order'=>'listorder asc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li> <a href="<?php echo $r['url'];?>" target="_blank"><img height="280" src="<?php echo $r['thumb'];?>" width="280" /><br />
<div class="txt"><?php echo $r['title'];?></div>
<div class="sj"><span class="jg">¥<?php echo round($r['coupon_price']);?></span><span class="yj">原价:¥<?php echo $r['price'];?></span></div><span class="gm"></span></a></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
</div>
<div class="bt"></div>
</div>
</div>
<div class="blank"></div>
<!--banner-->
<div class="wrap">
<div class="banad">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=93d7d188e57673d4e25f6c7510b0cc1e&action=lists&id=77&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=93d7d188e57673d4e25f6c7510b0cc1e&action=lists&id=77&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'77','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img width="1210" data-ks-lazyload="<?php echo $r['picture'];?>"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
<div style="height:15px; clear:both;"></div>
<!--banner end-->
<!--九九-->
<div class="wrap">
<div class="jiujiu">
<div class="title">
</div>
<div class="con">
<div class="list">
<ul>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=201fac90b05981a5ece67b4edfd41895&action=position&posid=76&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=201fac90b05981a5ece67b4edfd41895&action=position&posid=76&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'76','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li> <a href="<?php echo $r['url'];?>" target="_blank"><img height="280" src="<?php echo $r['thumb'];?>" width="280" /><br />
<div class="txt"><?php echo $r['title'];?></div>
<div class="sj"><span class="jg">¥<?php echo round($r['coupon_price'],1);?></span><span class="yj">原价:¥<?php echo $r['price'];?></span></div><span class="gm"></span></a></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<div class="clear"></div>
</div>
</div>
</div>
</div>
<div class="blank"></div>
<!--探寻内蒙古-->
<div class="wrap">
<div class="tanxun J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'tab-nav','contentCls':'tab-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [620], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<div class=" tab-content">
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=15512654e1b265bc29eef32f6fb41a14&action=position&posid=77&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=15512654e1b265bc29eef32f6fb41a14&action=position&posid=77&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'77','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=c64ae45c3d13ff8bc2c5aeee918ec2b6&action=position&posid=78&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=c64ae45c3d13ff8bc2c5aeee918ec2b6&action=position&posid=78&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'78','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=677e09f450afcd4a953391dcecf1c587&action=position&posid=79&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=677e09f450afcd4a953391dcecf1c587&action=position&posid=79&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'79','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=91837f7b39cf20523ddfe79d8f1576e9&action=position&posid=80&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=91837f7b39cf20523ddfe79d8f1576e9&action=position&posid=80&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'80','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=3432261a70d3edfa08bd4a41ae9acbaa&action=position&posid=81&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=3432261a70d3edfa08bd4a41ae9acbaa&action=position&posid=81&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'81','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=f8a7f70e0fccd07c0b1aef0f0b6e6e95&action=position&posid=82&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=f8a7f70e0fccd07c0b1aef0f0b6e6e95&action=position&posid=82&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'82','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=f1694237a4cfb684682445c42d4bd622&action=position&posid=83&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=f1694237a4cfb684682445c42d4bd622&action=position&posid=83&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'83','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=ef9ee639df8afbbf3f4391d3e4fe5766&action=position&posid=84&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=ef9ee639df8afbbf3f4391d3e4fe5766&action=position&posid=84&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'84','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=369f8dd7edb483fa5a3eb3063e668fbc&action=position&posid=85&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=369f8dd7edb483fa5a3eb3063e668fbc&action=position&posid=85&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'85','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=39baebc060823d8cbce3ffe37b4d857a&action=position&posid=86&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=39baebc060823d8cbce3ffe37b4d857a&action=position&posid=86&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'86','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=609fe764fe828a46f6fac5a312241d55&action=position&posid=87&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=609fe764fe828a46f6fac5a312241d55&action=position&posid=87&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'87','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=7d40b147cc9d1736334c93c31fc71de1&action=position&posid=88&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=7d40b147cc9d1736334c93c31fc71de1&action=position&posid=88&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'88','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a><br>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
<div class="ditu tab-nav">
<div class="qu1">
<span></span>
呼伦贝尔市
</div>
<div class="qu2">
<span></span>
兴安盟
</div>
<div class="qu3"><span></span>
通辽市
</div>
<div class="qu4"><span></span>
赤峰市
</div>
<div class="qu5"><span></span>
锡林郭勒盟
</div>
<div class="qu6"><span></span>
乌兰察布市
</div>
<div class="qu7"><span></span>
包头市
</div>
<div class="qu8"><span></span>
呼和浩特市
</div>
<div class="qu9"><span></span>
巴颜淖尔市
</div>
<div class="qu10"><span></span>
鄂尔多斯市
</div>
<div class="qu11"><span></span>
乌海市
</div>
<div class="qu12"><span></span>
阿拉善盟
</div>
</div>
</div>
</div>
<!--9.9包邮 -->
<div class="blank"></div>
<!-- 特色品类 -->
<div class="wrap">
<div class="pinlei">
<div class="li3">
<div class="li3_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=02d755253663379ad470bf8c8f731227&action=lists&id=106&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=02d755253663379ad470bf8c8f731227&action=lists&id=106&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'106','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $r['picture'];?>"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="li3_t">
<div class="tit"><span class="t">行军粮草</span><span class="des">草原特产 正宗蒙古味道</span></div>
<div><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=e6cadf69a85365878836be62b0fe3fa2&pos=shucai-1\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=e6cadf69a85365878836be62b0fe3fa2&pos=shucai-1\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'shucai-1',));?><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=4fff7339c868e3d264aaf57bcfc407c4&action=lists&id=107&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=4fff7339c868e3d264aaf57bcfc407c4&action=lists&id=107&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'107','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $r['picture'];?>"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="li3_t"><div class="tit"><span class="t">蒙古奶酪</span><span class="des">传统奶食 古法新传</span></div>
<div><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=5c706cc24b16f920897f08c966e739de&pos=shucai-2\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=5c706cc24b16f920897f08c966e739de&pos=shucai-2\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'shucai-2',));?><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=dd0430593b77d68bdcd48675f650c485&action=lists&id=108&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=dd0430593b77d68bdcd48675f650c485&action=lists&id=108&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'108','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $r['picture'];?>"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="li3_t"><div class="tit"><span class="t">草原生鲜</span><span class="des">鲜牛羊肉 从草原直达餐桌</span></div>
<div><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=24bc53b8c348617f4b7dd233df74b6ad&pos=shucai-3\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=24bc53b8c348617f4b7dd233df74b6ad&pos=shucai-3\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'shucai-3',));?><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?> </div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=8f758e9d453fd239fc3e1f9c6b6f8570&action=lists&id=109&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=8f758e9d453fd239fc3e1f9c6b6f8570&action=lists&id=109&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'109','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $r['picture'];?>"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="li3_t"><div class="tit"><span class="t">米面粮油</span><span class="des">草原生态粮油 原产地直供</span></div>
<div><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=dacd98095de743f15040735d10487597&pos=shucai-4\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=dacd98095de743f15040735d10487597&pos=shucai-4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'shucai-4',));?><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?> </div>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<div class="blank"></div>
<!--1楼-->
<div class="wrap">
<div class="louceng J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'tab-nav2','contentCls':'tab-content2','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [620], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<div class="title" style="background:url(http://img02.taobaocdn.com/imgextra/i2/1863579612/TB2_Dg9aXXXXXamXXXXXXXXXXXX_!!1863579612.png) no-repeat"> <div class="swap tab-nav2"><span class="on">美味零食</span><span>传统奶茶</span><span>牧场鲜奶</span></div> </div>
<div class="tab-content2">
<div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=0dfa6ba0b36e35c180b125ff568b4be7&action=lists&id=173&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=0dfa6ba0b36e35c180b125ff568b4be7&action=lists&id=173&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'173','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=71f645d55d154cb2c1e9207bad15e357&action=position&posid=89&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=71f645d55d154cb2c1e9207bad15e357&action=position&posid=89&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'89','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">热销¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div>
<div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=b7248d155311004362a0b3262c6fa108&action=lists&id=174&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=b7248d155311004362a0b3262c6fa108&action=lists&id=174&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'174','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=90eec7f36cc280329a2f6573617cfa2e&action=position&posid=90&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=90eec7f36cc280329a2f6573617cfa2e&action=position&posid=90&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'90','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">热销¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div>
<div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=a5232a251d157ee55fc9b4aff3603316&action=lists&id=175&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=a5232a251d157ee55fc9b4aff3603316&action=lists&id=175&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'175','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=a94c73cbc69e771f941fde786575bed2&action=position&posid=91&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=a94c73cbc69e771f941fde786575bed2&action=position&posid=91&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'91','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">热销¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</div>
<div class="blank"></div>
<!--2楼-->
<div class="wrap">
<div class="louceng J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'tab-nav2','contentCls':'tab-content2','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [620], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<div class="title" style="background:url(http://img04.taobaocdn.com/imgextra/i4/1863579612/TB2I_s5aXXXXXX4XpXXXXXXXXXX_!!1863579612.png) no-repeat"> <div class="swap tab-nav2"><span class="on">风干牛肉</span><span>草原全羊</span><span>经典小食</span></div> </div>
<div class="tab-content2">
<div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=a2d78784c7a4e2df9a6f26bb41ef870c&action=lists&id=176&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=a2d78784c7a4e2df9a6f26bb41ef870c&action=lists&id=176&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'176','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=2c06a3c16422b2064043cec1a3305b80&action=position&posid=92&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=2c06a3c16422b2064043cec1a3305b80&action=position&posid=92&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'92','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">热销¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div><div class="cons ">
<div class="l_img"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=80ecb6c19e3ea8cbd912056a91a02c08&action=lists&id=177&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=80ecb6c19e3ea8cbd912056a91a02c08&action=lists&id=177&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'177','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=35bfcd79bb98971b5bac433ca7a0d38e&action=position&posid=93&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=35bfcd79bb98971b5bac433ca7a0d38e&action=position&posid=93&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'93','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">热销¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div><div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=674bffd22e123c3a7d966da23bd127df&action=lists&id=178&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=674bffd22e123c3a7d966da23bd127df&action=lists&id=178&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'178','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=1ade0a6a58af71bb0ee66e9db628a1c8&action=position&posid=94&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=1ade0a6a58af71bb0ee66e9db628a1c8&action=position&posid=94&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'94','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">热销¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</div>
<div class="blank"></div>
<!--3楼-->
<div class="wrap">
<div class="louceng J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'tab-nav2','contentCls':'tab-content2','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [620], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<div class="title" style="background:url(http://img01.taobaocdn.com/imgextra/i1/1863579612/TB2QH78aXXXXXbJXXXXXXXXXXXX_!!1863579612.png) no-repeat"> <div class="swap tab-nav2"><span class="on">草原鲜米</span><span>精选杂粮</span><span>佐餐调味</span></div> </div>
<div class="tab-content2">
<div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=d4bbc702264b80783ddface97f287db0&action=lists&id=179&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=d4bbc702264b80783ddface97f287db0&action=lists&id=179&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'179','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=cab9615547e18df2e7bacc3b169e7b01&action=position&posid=95&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=cab9615547e18df2e7bacc3b169e7b01&action=position&posid=95&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'95','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">热销¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div><div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=86cbb36c63bcd4454d7d764c13a51c80&action=lists&id=180&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=86cbb36c63bcd4454d7d764c13a51c80&action=lists&id=180&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'180','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=a1a5366cfe6f677a6dfb2e3438d06cc2&action=position&posid=96&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=a1a5366cfe6f677a6dfb2e3438d06cc2&action=position&posid=96&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'96','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">热销¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div><div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=4677c98674c86e3fab25ebe379ad5062&action=lists&id=181&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=4677c98674c86e3fab25ebe379ad5062&action=lists&id=181&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'181','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=5481aafb901907f23ddd98ce78d297bd&action=position&posid=97&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=5481aafb901907f23ddd98ce78d297bd&action=position&posid=97&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'97','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">热销¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</div>
<div class="blank"></div>
<!--4楼-->
<div class="wrap">
<div class="louceng J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'tab-nav2','contentCls':'tab-content2','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [620], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<div class="title" style="background:url(http://img04.taobaocdn.com/imgextra/i4/1863579612/TB2tr.9aXXXXXaEXXXXXXXXXXXX_!!1863579612.png) no-repeat"> <div class="swap tab-nav2"><span class="on">珍味特产</span><span>草原情怀</span><span>特色风味</span></div> </div>
<div class="tab-content2">
<div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=7c9c0a6f07792ee4bad2f9e81fe22ab7&action=lists&id=182&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=7c9c0a6f07792ee4bad2f9e81fe22ab7&action=lists&id=182&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'182','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=f73dee1133a3e6f452701eb2b7e79b61&action=position&posid=98&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=f73dee1133a3e6f452701eb2b7e79b61&action=position&posid=98&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'98','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">热销¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div><div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=7f0aa5922e4d3e4dc48d4380776d6954&action=lists&id=183&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=7f0aa5922e4d3e4dc48d4380776d6954&action=lists&id=183&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'183','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=f344b7e9408e28bd96a9a4f7673f381f&action=position&posid=99&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=f344b7e9408e28bd96a9a4f7673f381f&action=position&posid=99&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'99','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">热销¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div><div class="cons ">
<div class="l_img">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=f99436bc9fb5ca07075c2911bd0cf4c7&action=lists&id=184&num=1&order=listorder+ASC&return=asd\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=f99436bc9fb5ca07075c2911bd0cf4c7&action=lists&id=184&num=1&order=listorder+ASC&return=asd\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$asd = $weblink_tag->lists(array('id'=>'184','order'=>'listorder ASC','limit'=>'1',));}?>
<?php $n=1;if(is_array($asd)) foreach($asd AS $r) { ?>
<a target="_blank" href="<?php echo $r['link'];?>"><img src="<?php echo $r['picture'];?>" width="260" height="470"></a>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="r_list">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=26dc2cd74f5643ed1598e833caeb414f&action=position&posid=100&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=26dc2cd74f5643ed1598e833caeb414f&action=position&posid=100&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'100','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="item"><a href="<?php echo $r['url'];?>" target="_blank">
<div class="img">
<img src="<?php echo $r['thumb'];?>" height="160" width="160"></div>
<div class="tit"><?php echo $r['title'];?></div>
<div class="cxj">热销¥<span><?php echo round($r['coupon_price'],1);?></span></div> <div class="gm">立即抢购</div>
</a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="clear"></div>
</div>
</div>
</div>
</div>
<div class="blank"></div>
<!-- 友链 -->
<div class="wrap">
<div class="jh">
<?php $result=query('SELECT * FROM jae_link WHERE typeid=0 AND listorder!=0 AND passed=1 ORDER BY listorder ASC LIMIT 0,50 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img data-ks-lazyload="<?php echo $v['logo'];?>"></a>
<?php }
?>
</div>
</div>
<!-- 友链 end-->
<div class="blank"></div>
<?php include template('content','foot');?>
</div>
<file_sep>/caches/caches_commons/caches_data/point_setinfo.cache.php
<?php
return array (
'point' => '30',
'title' => '完善基本资料获取积分',
'description' => '完善基本资料获取积分',
'enable' => '1',
'thumb' => 'http://a.tbcdn.cn/apps/membermanager/image/pro-activity.png',
);
?><file_sep>/jae/modules/template/templates/template_bak_list.tpl.php
<?php
defined('IN_ADMIN') or exit('No permission resources.');
include $this->admin_tpl('head', 'admin');
?>
<div class="bk15"></div>
<div class="pad_10">
<div class="table-list">
<table width="100%" cellspacing="0">
<thead>
<tr class="thead">
<th><?php echo L('filename')?></th>
<th><?php echo L('time')?></th>
<th><?php echo L('who')?></th>
<th width="150"><?php echo L('operations_manage')?></th>
</tr>
</thead>
<tbody>
<?php
foreach($list as $v):
?>
<tr>
<td align="center"><?php echo $v['fileid']?></td>
<td align="center"><?php echo date('Y-m-d H:i:s',$v['creat_at'])?></td>
<td align="center"><?php echo $v['username']?></td>
<td align="center"><a href="/admin.php?m=template&c=template_bak&a=restore&id=<?php echo $v['id']?>&style=<?php echo $this->style?>&dir=<?php echo $this->dir?>&filename=<?php echo $this->filename?>" onclick="return confirm('<?php echo L('are_you_sure_you_want_to_restore')?>')"><?php echo L('restore')?></a> | <a href="?m=template&c=template_bak&a=del&id=<?php echo $v['id']?>&style=<?php echo $this->style?>&dir=<?php echo $this->dir?>&filename=<?php echo $this->filename?>" onclick="return confirm('<?php echo L('confirm', array('message'=>date('Y-m-d H:i:s',$v['creat_at'])))?>')"><?php echo L('delete')?></a></td>
</tr>
<?php
endforeach;
?>
</tbody>
</table>
</from>
</div>
</div>
<div id="pages"><?php echo $pages?></div>
<?php include $this->admin_tpl('foot', 'admin');?><file_sep>/caches/caches_template/weifang/content/index.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head');?>
<link rel="stylesheet" href="/statics/css/lows.css" />
<div class="lows-banner J_TWidget" style="display:none" id="J_LowsBanner" data-widget-type="Carousel" data-widget-config="{'navCls':'ks-switchable-nav','contentCls':'ks-switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'active','autoplay':'true','interval':3,'prevBtnCls': 'prev', 'nextBtnCls': 'next', 'disableBtnCls': 'disable' }">
<div class="trigger-wrap">
<span class="close J_LowsClose"></span>
<span class="prev"></span>
<span class="next"></span>
<ol class="lows-trigger ks-switchable-nav">
<li class="ks-switchable-trigger-internal297 active"></li>
<li class="ks-switchable-trigger-internal297 "></li>
<li class="ks-switchable-trigger-internal297"></li>
</ol>
</div>
<ul class="ks-switchable-content clear-fix">
<li class="pic1 ks-switchable-panel-internal298" style="display: block; opacity: 0; position: absolute; z-index: 1; "><div class="banner-pic" style="background: url(http://img02.taobaocdn.com/imgextra/i2/2063414185/TB2vZdVaXXXXXXpXXXXXXXXXXXX-2063414185.png) no-repeat 0 0;"></div></li>
<li class="pic2 ks-switchable-panel-internal298" style="display: block; opacity: 1; position: absolute; z-index: 9; "><div class="banner-pic" style="background: url(http://img01.taobaocdn.com/imgextra/i1/2063414185/TB26QXZaXXXXXXuXXXXXXXXXXXX-2063414185.png) no-repeat 0 0;"></div></li>
<li class="pic3 ks-switchable-panel-internal298" style="display: block; opacity: 0; position: absolute; z-index: 1; "><div class="banner-pic" style="background: url(http://img02.taobaocdn.com/imgextra/i2/2063414185/TB2R10VaXXXXXXNXXXXXXXXXXXX-2063414185.png) no-repeat 0 0;"></div></li>
</ul>
</div>
<div class="body_bg">
<!--首屏-->
<div class="wrap" style="height:400px;position:relative ">
<div class="root61" style="z-index:22">
<div class="smCategorys">
<div class="sm-c-wrap J_TWidget" data-widget-type="Slide"
data-widget-config="{'navCls':'yslider-stick','contentCls':'yslider-stage','activeTriggerCls':'curr',
'delay':0.2,'effect':'fade','easing':'easeBoth','duration':0.8,'autoplay':false}" >
<div class="menu yslider-stick" >
<div class="item fore1 ">
<i class="i1 "></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=10 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=10 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore2">
<i class="i2"></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=16 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=16 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore3">
<i class="i3"></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=17 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=17 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore4">
<i class="i4"></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=18 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=18 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore5">
<i class="i5"></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=19 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=19 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="focus J_TWidget" data-widget-type="Carousel" data-widget-config="{'navCls':'tab-nav','contentCls':'tab-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [770], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'prev', 'nextBtnCls': 'next', 'disableBtnCls': 'disable' }">
<div class="prev"></div><div class="next"></div>
<div class="tab-content">
<?php $sql="SELECT * FROM jae_focus WHERE status=1 ORDER BY listorder ASC ";
$r_focus=query($sql); foreach ($r_focus as $r) {?>
<div><a href="<?php echo $r["link"]?>" target="_blank"> <img src="<?php echo $r["picture"]?>" width="770" height="400"/></a></div>
<?php }?>
</div>
<div class="tab-nav">
<?php $r_focuss=query($sql); foreach ($r_focuss as $k=>$rs) {?>
<div class="v<?php echo $k?>"></div>
<?php }?>
</div>
</div>
<!--个人信息区域开始-->
<div class="vPersonal" >
<div class="info">
<div class="photo " data-test="-1">
<div class="p" id="J_personal_photo" data-garden="-1" data-experience="10007" data-img="http://img.taobaocdn.com/sns_logo/T1xzuvFcRcXXb1upjX.jpg_80x80.jpg"> <?php echo '<img width=76 height=76 src="/_RS/user/picture?mixUserNick='.urlencode($nick,"UTF-8").'" /> ';?></div>
<span class="m"></span> <span class="m mb-hide j_changeInfo"> <b>编辑资料</b> </span> </div>
<div class="per">
<p class="title" >HI!<span class="login_tip"><a href="/member.php" style="color:#fff;">请登录</a></span></p>
<!--<p class="garden">您是湖北馆会员</p>-->
<p class="bt">
<!-- <a class="activied j_activied" href="javascript:void(0);">激活</a>-->
<a class="sign j_sign activied" href="/index.php?m=member&c=index&a=init" target="_blank">签到</a> </p>
</div>
</div>
<!--个人信息区域结束-->
<!--个人资产区域开始-->
<div class="assets unlogin"> <span class="bt1"></span>
<!--已登录开始-->
<div class="row point"> <span class="icon"></span>
<p class="ht"> <a href="/index.php?m=point&c=index&a=sign&trad=all" target="_blank">我的积分:</a> <span class="pots "> <a href="/index.php?m=point&c=index&a=sign&trad=all" target="_blank">0</a> </span> </p>
<p class="bt"> 邀请好友就能赚积分 </p>
</div>
<div class="row coupon"> <span class="icon"></span>
<p class="ht"> <a href="/index.php?m=prize&c=index&a=my_prize" target="_blank">我的奖品:</a> <span class="prizes_num" ><a href="/index.php?m=prize&c=index&a=my_prize" target="_blank">0</a></span> 个 </p>
<p class="bt"> <a href="/index.php?m=prize&c=index&a=my_prize" target="_blank"> 快来参加积分抽奖吧 </a> </p>
</div>
<div class="row message"> <span class="icon"></span>
<p class="ht"> <a href="/index.php?m=order&c=index&a=init" target="_blank">我的订单:</a> <span class="orders_num"><a href="/index.php?m=order&c=index&a=init" target="_blank">0</a></span> 个 </p>
<p class="bt"> <a class="dr" href="/index.php?m=order&c=index&a=init" target="_blank">潍坊馆的积分活动</a> </p>
</div>
<!--已登录结束--> </div>
<!--个人资产区域结束-->
<!--特权区域开始-->
<div class="privilege">
<div class="title"></div>
<div class="list" id="J_privilege_tab">
<div style="position: relative; overflow: hidden; height: 130px;">
<ul class="tab-content" style="width: 190px; overflow: hidden; height: 90px; ">
<div style="position: absolute; overflow: hidden; width: 380px; -webkit-transition: 0s; -webkit-transform: translate3d(0px, 0px, 0px); -webkit-backface-visibility: hidden; ">
<li class="tab-pannel" style="float: left; overflow: hidden; width: 190px; display: block; ">
<ul class="privList">
<li> <a href="/index.php?m=point&c=index&a=sign&trad=all" target="_blank"> <span class="icon "></span> 我的签到 </a> </li>
<li> <a href="/index.php?m=prize&c=index&a=init" target="_blank"> <span class="icon "></span> 积分抽奖 </a> </li>
<li> <a href="/index.php?m=exchange&c=index&a=init" target="_blank"> <span class="icon "></span> 积分换购 </a> </li>
<li> <a href="/index.php?m=seckill&c=index&a=init" target="_blank"> <span class="icon "></span> 积分秒杀 </a> </li>
<li> <a href="/index.php?m=content&c=index&a=lists&catid=1" target="_blank"> <span class="icon "></span> 购物返积分 </a> </li>
<li> <a href="/index.php?m=point&c=index&a=point_invite" target="_blank"> <span class="icon "></span> 邀请好友 </a> </li>
</ul>
</li>
<li class="tab-pannel hidden" style="float: left; overflow: hidden; width: 190px; display: block; ">
<ul class="privList">
<li> </li>
<li> </li>
</ul>
</li>
</div>
</ul>
</div>
</div>
</div>
<!--特权区域结束--> </div>
</div>
<div class="blank"></div>
<div class="wrap">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=21 and id=163 ORDER BY listorder,id ASC LIMIT 1 ');
foreach ($result as $v) { if(!empty($v['picture'])){
?><a target="_blank" href="<?php echo $v['link'];?>"><img width="1210" style="display:block" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php } }
?>
</div>
<div class="blank"></div>
<!--首屏END-->
<!--至尊推荐-->
<div class="wrap">
<div class="sk-con" >
<div class="sk-item">
<ul class="clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=d1873a14efbedecaad41e79e98dffdcb&action=position&posid=7&order=listorder+asc&num=5\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=d1873a14efbedecaad41e79e98dffdcb&action=position&posid=7&order=listorder+asc&num=5\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'7','order'=>'listorder asc','limit'=>'5',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><div class="p-img"><a href="<?php echo $r['url'];?>" target="_blank"><img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img width="240" height="240" data-ks-lazyload="<?php echo $r['thumb'];?>" ></a></div><div class="p-name"><a href="<?php echo $r['url'];?>" target="_blank"><?php echo $r['title'];?></a></div><div class="p-price"><strong>¥<?php echo $r['coupon_price'];?></strong><del><?php echo $r['price'];?></del></div><div class="p-btn"><a class="btn-m seckilling" href="<?php echo $r['url'];?>" target="_blank">立即购买</a></div></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
</div>
<div class="clear"> </div>
</div>
<!--至尊推荐END-->
<!--9.9包邮 74--><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=297cafed24d62adb523e2364dd9e6e6f&action=position&posid=74&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=297cafed24d62adb523e2364dd9e6e6f&action=position&posid=74&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'74','order'=>'listorder asc','limit'=>'10',));}?>
<?php if($data) { ?>
<div class="wrap">
<div class="title" style="height:47px"><img src="http://img04.taobaocdn.com/imgextra/i4/2063414185/T2j3ROXVBXXXXXXXXX_!!2063414185.png"/></div><div class="jinxuan">
<div class="sk-item">
<ul class="clearfix">
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><div class="p-img"><a href="<?php echo $r['url'];?>" target="_blank"><img width="210" height="210" data-ks-lazyload="<?php echo $r['thumb'];?>" ></a></div><div class="p-name"><a href="<?php echo $r['url'];?>" target="_blank"><?php echo $r['title'];?></a></div><div class="p-price"><strong>¥<?php echo $r['coupon_price'];?></strong><del><?php echo $r['price'];?></del></div><div class="p-btn"><a class="btn-m seckilling" href="<?php echo $r['url'];?>" target="_blank">立即购买</a></div></li>
<?php $n++;}unset($n); ?>
</ul></div>
</div>
</div><?php } ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<!--9.9包邮END-->
<!--潍坊精选-->
<div class="wrap">
<div class="title" style="height:97px"><img src="http://img01.taobaocdn.com/imgextra/i1/1089118323/TB2ILtzaXXXXXbAXXXXXXXXXXXX-1089118323.png"/></div><div class="jinxuan">
<div class="sk-item">
<ul class="clearfix"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=c3657b6d21024c499b782f6bc465a4ba&action=position&posid=9&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=c3657b6d21024c499b782f6bc465a4ba&action=position&posid=9&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'9','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><div class="p-img"><a href="<?php echo $r['url'];?>" target="_blank"><img width="210" height="210" data-ks-lazyload="<?php echo $r['thumb'];?>" ></a></div><div class="p-name"><a href="<?php echo $r['url'];?>" target="_blank"><?php echo $r['title'];?></a></div><div class="p-price"><strong>¥<?php echo $r['coupon_price'];?></strong><del><?php echo $r['price'];?></del></div><div class="p-btn"><a class="btn-m seckilling" href="<?php echo $r['url'];?>" target="_blank">立即购买</a></div></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
</div>
</div>
<!--潍坊精选END-->
<!--特色品类-->
<div class="blank"> </div>
<div class="wrap ">
<div class="main tese">
<div class="main_t">
<div class="main_b">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=89c9d31e71e94f24982e6a9bf42cc69a&id=5\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=89c9d31e71e94f24982e6a9bf42cc69a&id=5\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('id'=>'5',));?><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<div class="clear"> </div>
</div>
</div>
</div>
</div>
<!--特色品类END-->
<!--1楼-->
<div class="blank"> </div>
<div class="louceng wrap">
<div class="title"> <img src="http://img02.taobaocdn.com/imgextra/i2/2063414185/T28s4IXW0aXXXXXXXX_!!2063414185.png" style="float:none;margin:0px;" /></div>
<div class="main">
<div class="main_t">
<div class="main_b">
<div class="left"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=ea861e211e996c1889cefb88b8e7e0d6&id=6\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=ea861e211e996c1889cefb88b8e7e0d6&id=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('id'=>'6',));?><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<div class="right">
<div class="list">
<ul>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=dcc651fcbfb304c1bf46f43ab2d24e99&action=position&posid=10&order=listorder+asc&num=8\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=dcc651fcbfb304c1bf46f43ab2d24e99&action=position&posid=10&order=listorder+asc&num=8\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'10','order'=>'listorder asc','limit'=>'8',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li> <a href="<?php echo $r['url']?>" target="_blank"><img height="200" src="<?php echo $r['thumb']?>" style="float:none;margin:0px;" width="200" /><br />
<span class="txt"><?php echo $r['title']?></span>
<span class="jg">¥<?php echo round($r['coupon_price'],1);?></span><span class="yj">¥<?php echo round($r['price'],1);?></span> <span class="gm">立即购买</span></a></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
</div>
<div class="clear"> </div>
</div>
</div>
</div>
</div>
<!--1楼END-->
<!--2楼-->
<div class="blank"> </div>
<div class="louceng wrap">
<div class="title"> <img src="http://img02.taobaocdn.com/imgextra/i2/2063414185/T2hmhJX7FXXXXXXXXX_!!2063414185.png" style="float:none;margin:0px;" /></div>
<div class="main">
<div class="main_t">
<div class="main_b">
<div class="left"> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=be946917f27c9b2559fadfe4e593aae0&id=7\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=be946917f27c9b2559fadfe4e593aae0&id=7\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('id'=>'7',));?><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<div class="right">
<div class="list">
<ul>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=241e8983b17b72d7f52bb29f7f4d2895&action=position&posid=14&order=listorder+asc&num=8\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=241e8983b17b72d7f52bb29f7f4d2895&action=position&posid=14&order=listorder+asc&num=8\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'14','order'=>'listorder asc','limit'=>'8',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li> <a href="<?php echo $r['url']?>" target="_blank"><img data-pinit="registered" height="200" src="<?php echo $r['thumb']?>" style="float:none;margin:0px;" width="200" /><br />
<span class="txt"><?php echo $r['title']?></span>
<span class="jg">¥<?php echo round($r['coupon_price'],1);?></span><span class="yj">¥<?php echo round($r['price'],1);?></span> <span class="gm">立即购买</span></a></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
</div>
<div class="clear"> </div>
</div>
</div>
</div>
</div>
<!--2楼END-->
<!--3楼-->
<div class="blank"> </div>
<div class="louceng wrap">
<div class="title"> <img src="http://img01.taobaocdn.com/imgextra/i1/2063414185/T2jgVMX2BXXXXXXXXX_!!2063414185.png" style="float:none;margin:0px;" /></div>
<div class="main">
<div class="main_t">
<div class="main_b">
<div class="left"> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=bb946944bce804bb0554168e338c62a5&id=8\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=bb946944bce804bb0554168e338c62a5&id=8\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('id'=>'8',));?><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<div class="right">
<div class="list">
<ul>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=7681d386635bebe6c65342d998828a04&action=position&posid=15&order=listorder+asc&num=8\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=7681d386635bebe6c65342d998828a04&action=position&posid=15&order=listorder+asc&num=8\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'15','order'=>'listorder asc','limit'=>'8',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li> <a href="<?php echo $r['url']?>" target="_blank"><img data-pinit="registered" height="200" src="<?php echo $r['thumb']?>" style="float:none;margin:0px;" width="200" /><br />
<span class="txt"><?php echo $r['title']?></span>
<span class="jg">¥<?php echo round($r['coupon_price'],1);?></span><span class="yj">¥<?php echo round($r['price'],1);?></span> <span class="gm">立即购买</span></a></li>
<?php $n++;}unset($n); ?><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
</div>
<div class="clear"> </div>
</div>
</div>
</div>
</div>
<!--3楼END-->
<!--4楼-->
<div class="blank"> </div>
<div class="louceng wrap">
<div class="title"> <img src="http://img01.taobaocdn.com/imgextra/i1/2063414185/T2kU0GX0daXXXXXXXX_!!2063414185.png" style="float:none;margin:0px;" /></div>
<div class="main">
<div class="main_t">
<div class="main_b">
<div class="left"> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=b5b856496b9be73481909fb0e63bf7ca&id=9\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=b5b856496b9be73481909fb0e63bf7ca&id=9\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('id'=>'9',));?><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<div class="right">
<div class="list">
<ul>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=6afc1a25909457b1178ad82d37b05d9e&action=position&posid=16&order=listorder+asc&num=8\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=6afc1a25909457b1178ad82d37b05d9e&action=position&posid=16&order=listorder+asc&num=8\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'16','order'=>'listorder asc','limit'=>'8',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li> <a href="<?php echo $r['url']?>" target="_blank"><img data-pinit="registered" height="200" src="<?php echo $r['thumb']?>" style="float:none;margin:0px;" width="200" /><br />
<span class="txt"><?php echo $r['title']?></span>
<span class="jg">¥<?php echo round($r['coupon_price'],1);?></span><span class="yj">¥<?php echo round($r['price'],1);?></span> <span class="gm">立即购买</span></a></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
</div>
<div class="clear"> </div>
</div>
</div>
</div>
</div>
<!--4楼END-->
<div class="blank"> </div>
<!--特产专辑-->
<div class="wrap">
<div class="title" style="height:127px;"><img src="http://img02.taobaocdn.com/imgextra/i2/1089118323/TB2k4BtaXXXXXaMXpXXXXXXXXXX-1089118323.png"></div>
<div class="zhuanji">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=f68aec78e0763457e213df6a3dd50aff&action=lists&typeid=20&num=8&order=listorder+ASC\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=f68aec78e0763457e213df6a3dd50aff&action=lists&typeid=20&num=8&order=listorder+ASC\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$data = $weblink_tag->lists(array('typeid'=>'20','order'=>'listorder ASC','limit'=>'8',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $v) { ?>
<div class="li4"><a target="_blank" href="<?php echo $v['link'];?>"><img border="0" height="155" style="float:none;margin:0px;" width="280" data-ks-lazyload="<?php echo $v['picture'];?>"></a></div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<div class="clear"></div>
</div>
</div>
<!--特产专辑END-->
<div class="blank"> </div>
<!--友情链接-->
<div class="wrap">
<img src="http://img02.taobaocdn.com/imgextra/i2/2063414185/TB2Ney9aXXXXXXHXpXXXXXXXXXX-2063414185.png">
</div>
<div class="wrap">
<div class="jh">
<?php $result=query('SELECT * FROM jae_link WHERE typeid=0 AND passed=1 ORDER BY listorder ASC LIMIT 0,50 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img data-ks-lazyload="<?php echo $v['logo'];?>"></a>
<?php }?>
<div class="clear"></div>
</div>
</div>
<!--友情链接END-->
<!--版权-->
</div>
<?php include template('content','foot');?>
<!--版权END--><file_sep>/jae/modules/member/templates/buyer_edit.tpl.php
<?php include $this->admin_tpl('head','admin');
?>
<form name="myform" id="myform" action="/admin.php?m=member&c=buyer&a=edit" method="post">
<table width="100%" class="table_form contentWrap">
<tbody>
<tr>
<th> 淘宝混肴昵称:</th>
<td><?php echo $username;?><div id="languageTip" class="onShow"></div></td>
</tr>
<tr>
<th width="100">用户姓名:</th>
<td><input style="width:300px;" type="text" name="info[nickname]" value="<?php echo $nickname?>" id="language" class="input-text"><div id="languageTip" class="onShow"></div></td>
</tr>
<tr>
<th> 旺旺:</th>
<td><input style="width:300px;" type="text" name="info[wangwang]" value="<?php echo $wangwang?>" id="language" class="input-text"><div id="languageTip" class="onShow"></div></td>
</tr>
<tr>
<th>手机:</th>
<td><input style="width:300px;" type="text" name="info[mobile]" value="<?php echo $mobile?>" id="language" class="input-text"><div id="nameTip" class="onShow"></div></td>
</tr>
<tr>
<th>地址:</th>
<td><input style="width:300px;" type="text" name="info[address]" value="<?php echo $address?>" id="language" class="input-text"><div id="nameTip" class="onShow"></div></td>
</tr>
<?php if ($groupid==2) {?>
<tr>
<th>店铺名称:</th>
<td><input style="width:300px;" type="text" name="info[shop_title]" value="<?php echo $shop_title?>" id="language" class="input-text"><div id="nameTip" class="onShow"></div></td>
</tr>
<tr>
<th>店铺简介:</th>
<td><input style="width:300px;" type="text" name="info[shop_profile]" value="<?php echo $shop_profile?>" id="language" class="input-text"><div id="nameTip" class="onShow"></div></td>
</tr>
<tr>
<th>店铺地址:</th>
<td><input style="width:300px;" type="text" name="info[shop_url]" value="<?php echo $shop_url?>" id="language" class="input-text"><div id="nameTip" class="onShow"></div></td>
</tr>
<?php }?>
</tbody></table>
<!--table_form_off-->
<div class="btns">
<input type="hidden" name="userid" value="<?php echo $userid?>"><input type="submit" id="dosubmit" class="button" name="dosubmit" value="提交"></div>
</form>
<?php include $this->admin_tpl('foot','admin');?><file_sep>/upgrade/20140707.sql
ALTER TABLE `jae_prize` ADD `module` VARCHAR(15) NULL DEFAULT NULL AFTER `typeid`;
UPDATE jae_site SET date='20140707' ;
UPDATE jae_site SET version='142';<file_sep>/upgrade/20140626.sql
ALTER TABLE `jae_seckill_person` ADD COLUMN `iswin` TINYINT(1) UNSIGNED default '0' AFTER `goodsid`;
UPDATE jae_point SET module='sign' where typeid=1;
UPDATE jae_point SET module='prize' where typeid=2;
UPDATE jae_site SET date='20140626' ;
UPDATE jae_site SET version='140';<file_sep>/jae/modules/exchange/index.php
<?php
defined('IN_JAE') or exit('No permission resources.');
jae_base::load_app_class('foreground','member');
jae_base::load_app_func('global');
class index extends foreground {
public function __construct() {
$this->exchange_db = jae_base::load_model('exchange_model');
$this->point_db = jae_base::load_model('point_model');
$this->prize_db = jae_base::load_model('prize_model');
$this->member_db = jae_base::load_model('member_model');
parent::__construct();
}
//活动报名首页
public function init() {
$memberinfo = $this->memberinfo;
$page=$_GET['page'];
$where=" status=1 AND end_time > " .SYS_TIME;
$data=$this->exchange_db->listinfo($where,$order = 'listorder ASC',$page, $pages = '24');
$pages=$this->exchange_db->pages;
include template('exchange','index');
}
public function exchange() {
$memberinfo = $this->memberinfo;
$id = intval($_GET['id']);
$data=$this->exchange_db ->get_one('id='.$id);
if($data) extract($data);
include template('exchange','show_ex');
}
}
?><file_sep>/upgrade/20140708.sql
ALTER TABLE `jae_seckill` ADD `question` VARCHAR(255) NULL DEFAULT NULL AFTER `description`;
ALTER TABLE `jae_seckill` ADD `answer` VARCHAR(255) NULL DEFAULT NULL AFTER `question`;
UPDATE jae_site SET date='20140708' ;
UPDATE jae_site SET version='143';<file_sep>/caches/configs/tables.php
<?php
return array (
'article' => '文章',
'block' => '碎片',
'block_history' => '碎片历史',
'block_type' => '碎片类型',
'brand' => '品牌',
'brand_type' => '品牌分类',
'cache' => '缓存',
'channel' => '频道',
'focus' => '首焦',
'goods' => '商品',
'goods_type' => '商品分类',
'link' => '友情链接',
'member' => '会员',
'menu' => '菜单',
'model' => '模型',
'module' => '模块',
'point' => '积分',
'point_set' => '积分设置',
'position' => '推荐位',
'position_data' => '推荐位数据',
'prize' => '奖品',
'prize_set' => '抽奖设置',
'release_point' => '相关发布点',
'seckill' => '秒杀',
'shop' => '店铺',
'site' => '站点配置',
'special' => '专题',
'weblink' => '网页链接',
'weblink_type' => '网页链接分类',
'site_config' => '网站信息',
);
?><file_sep>/jae/modules/seckill/index.php
<?php
defined('IN_JAE') or exit('No permission resources.');
jae_base::load_app_class('foreground','member');
jae_base::load_app_func('global');
class index extends foreground {
public function __construct() {
$this->point_db = jae_base::load_model('point_model');
$this->seckill_db = jae_base::load_model('seckill_model');
$this->member_db = jae_base::load_model('member_model');
parent::__construct();
}
public function init() {
$setting=getcache_sql('seckill','commons');
if($setting['enable']==0) {include template('prize','index_unable'); exit();}
$memberinfo = $this->memberinfo;
$where = SYS_TIME." < end_time AND begin_time +3600 > ".SYS_TIME;
$page=$_GET['page'];
$data=$this->seckill_db->listinfo($where,$order = 'begin_time ASC',$page, $pages = '10');
$pages=$this->seckill_db->pages;
$page_setting=getcache_sql('seckill','commons');
include template('seckill','index');
}
public function rules() {
$memberinfo = $this->memberinfo;
$page_setting=getcache_sql('seckill','commons');
//print_r($setting);
include template('seckill','rules');
}
}
?><file_sep>/jae/modules/point/templates/point_set_edit.tpl.php
<?php include $this->admin_tpl('head','admin');
?>
<form name="myform" id="myform" action="/admin.php?m=point&c=point_set&a=edit" method="post">
<table width="100%" class="table_form contentWrap">
<tbody><tr>
<th width="100">标题:</th>
<td><input style="width:300px;" type="text" name="info[title]" value="<?php echo $title?>" id="language" class="input-text"><div id="languageTip" class="onShow"></div></td>
</tr>
<tr>
<th> 图片:</th>
<td><input style="width:300px;" type="text" name="info[picture]" value="<?php echo $picture?>" id="language" class="input-text"><div id="languageTip" class="onShow"></div></td>
</tr>
<tr>
<th>描述:</th>
<td><input style="width:300px;" type="text" name="info[description]" value="<?php echo $description?>" id="language" class="input-text"><div id="nameTip" class="onShow"></div></td>
</tr>
<tr>
<th>第几天:</th>
<td><input style="width:300px;" type="text" name="info[day]" value="<?php echo $day?>" id="language" class="input-text"><div id="nameTip" class="onShow">数字整数</div></td>
</tr>
<tr>
<th>相应分数:</th>
<td><input style="width:300px;" type="text" name="info[point]" value="<?php echo $point?>" id="language" class="input-text"><div id="nameTip" class="onShow">数字整数</div></td>
</tr>
</tbody></table>
<!--table_form_off-->
<div class="btns">
<input type="hidden" name="id" value="<?php echo $id?>"><input type="submit" id="dosubmit" class="button" name="dosubmit" value="提交"></div>
</form>
<?php include $this->admin_tpl('foot','admin');?><file_sep>/jae/modules/seckill/seckill.php
<?php
defined('IN_JAE') or exit('No permission resources.');defined('IN_ADMIN') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
class seckill extends admin {
function __construct() {
parent::__construct();
$this->db =jae_base::load_sys_class('mysql');
$this->table='jae_seckill';
$this->menuid=31;
}
function init () {
$where =1;
$page=$_GET['page'];
$data=$this->db->listinfo("*",$this->table,$where,"id DESC",$page,10);
$pages=$this->db->pages;
include $this->admin_tpl('seckill_list');
}
function add() {
if(isset($_POST['dopost'])) {
//获取站点配置信息
$siteinfo=siteinfo(SITEID);
$appkey =$siteinfo['appkey'];
$secret =$siteinfo['secretkey'];
jae_base::load_top('topclient');
jae_base::load_top('ItemGetRequest');
$numIid= isset($_POST['numIid']) ? trim($_POST['numIid']) : ''; //提交过来的num_iid
if ($numIid != "" && rRuleNum($numIid)) {
$c = new TopClient;
$c->appkey = $appkey;
$c->secretKey = $secret;
$req = new ItemGetRequest;
$req->setFields("detail_url,num_iid,title,nick,type,cid,seller_cids,props,input_pids,input_str,desc,pic_url,num,valid_thru,list_time,delist_time,stuff_status,location,price,post_fee,express_fee,ems_fee,has_discount,freight_payer,has_invoice,has_warranty,has_showcase,modified,increment,approve_status,postage_id,product_id,auction_point,property_alias,item_img,prop_img,sku,video,outer_id,is_virtual");
$req->setNumIid($numIid);
$resp = $c->execute($req, $sessionKey);
if ($resp->item) {
$detail_url = $resp->item->detail_url; //商品链接
$num_iid = $resp->item->num_iid; //商品ID
$title = $resp->item->title; //商品标题
$nick = $resp->item->nick; //卖家昵称
$pic_url = $resp->item->pic_url; //商品主图
$num = $resp->item->num; //商品数量
$price = $resp->item->price; //商品原价格
$freight_payer = $resp->item->freight_payer; //商品原价格
} else
$message = '不存在这个商品';
//print_r($resp);
} else {
$message = "商品ID【不能为空】并且【必须是数字】。";
}
}
if(isset($_POST['dosubmit'])) {
$data=$_POST['info'];
$data['begin_time'] = strtotime($_POST['info']['begin_time']);
$data['end_time'] = strtotime($_POST['info']['end_time']);
$data['status']=1;
$this->db->insert($data,$this->table);
showmessage(L('add_success'));
} else {
include $this->admin_tpl('seckill_add');
}
}
function delete() {
$_GET['id'] = intval($_GET['id']);
$this->db->delete($this->table,'id='.$_GET['id']);
showmessage(L('operation_success'));
}
function edit() {
if(isset($_POST['dosubmit'])) {
$id = intval($_POST['id']);
$data=$_POST['info'];
$data['begin_time'] = strtotime($_POST['info']['begin_time']);
$data['end_time'] = strtotime($_POST['info']['end_time']);
$this->db->update($data,$this->table,'id='.$id);
showmessage(L('operation_success'));
} else {
$id = intval($_GET['id']);
$r=$this->db->get_one('*',$this->table,'id='.$id);
if($r) extract($r);
include $this->admin_tpl('seckill_edit');
}
}
/**
* 排序
*/
function listorder() {
if(isset($_POST['dosubmit'])) {
foreach($_POST['del'] as $id => $listorder) {
$status = isset($_POST["del"][$id]) ? $_POST["del"][$id] : '0';
$this->db->delete($this->table,'id='.$id);
}
foreach($_POST['listorders'] as $id => $listorder) {
$listorder = !empty($listorder) ? $listorder : '0';
$this->db->update(array('listorder'=>$listorder),$this->table,'id='.$id);
$status = isset($_POST["status"][$id]) ? $_POST["status"][$id] : '0';
$this->db->update(array('status'=>$status),$this->table,'id='.$id);
}
showmessage(L('operation_success'));
} else {
showmessage(L('operation_failure'));
}
}
/**
* 模块配置
*/
public function setting() {
$m_db = jae_base::load_model('module_model');
$data = $m_db->get_one(array('module'=>'seckill'));//array('module'=>'prize')
$setting = string2array($data['setting']);
if(isset($_POST['dosubmit'])) {
$variable = $_POST['setting'];
//更新模型数据库,重设setting 数据.
foreach ($variable as $key => $value) {
$sets[$key]=$value;
}
$sets=new_html_special_chars($sets);
$set = array2string($sets);
setcache('seckill', $sets, 'commons');
$m_db->update(array('setting'=>$set), array('module'=>ROUTE_M));
showmessage(L('setting_updates_successful'), '/admin.php?m=seckill&c=seckill&a=setting&menuid=97');
} else {
@extract($setting);
include $this->admin_tpl('setting');
}
}
}
?><file_sep>/caches/caches_template/liaoning/content/foot.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><!-- 底部 -->
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=41fe3d9e50980b4ea70e5954fe6546b3&action=lists&typeid=23&num=100&order=listorder+ASC&return=data\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=41fe3d9e50980b4ea70e5954fe6546b3&action=lists&typeid=23&num=100&order=listorder+ASC&return=data\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$data = $weblink_tag->lists(array('typeid'=>'23','order'=>'listorder ASC','limit'=>'100',));}?>
<div class="bder">
<div class="wrap">
<div class="dilo">
<img height="70" src="<?php echo $site_setting['foot_logo'] ?>">
</div>
<div class="tle">
<div class="ti">
<a href="<?php echo $data[0]['link'];?>" target="_blank"><?php echo $data[0]['title'];?></a>
</div>
<ul>
<li><a href="<?php echo $data[1]['link'];?>" target="_blank"><?php echo $data[1]['title'];?></a></li>
<li><a href="<?php echo $data[2]['link'];?>" target="_blank"><?php echo $data[2]['title'];?></a></li>
<li><a href="<?php echo $data[3]['link'];?>" target="_blank"><?php echo $data[3]['title'];?></a></li>
</ul>
</div>
<div class="tle">
<div class="ti">
<a href="<?php echo $data[4]['link'];?>" target="_blank"><?php echo $data[4]['title'];?></a>
</div>
<ul>
<li><a href="<?php echo $data[5]['link'];?>" target="_blank"><?php echo $data[5]['title'];?></a></li>
<li><a href="<?php echo $data[6]['link'];?>" target="_blank"><?php echo $data[6]['title'];?></a></li>
<li><a href="<?php echo $data[7]['link'];?>" target="_blank"><?php echo $data[7]['title'];?></a></li>
</ul>
</div>
<div class="tle">
<div class="ti">
<a href="<?php echo $data[8]['link'];?>" target="_blank"><?php echo $data[8]['title'];?></a>
</div>
<ul>
<li><a href="<?php echo $data[9]['link'];?>" target="_blank"><?php echo $data[9]['title'];?></a></li>
<li><a href="<?php echo $data[10]['link'];?>" target="_blank"><?php echo $data[10]['title'];?></a></li>
<li><a href="<?php echo $data[11]['link'];?>" target="_blank"><?php echo $data[11]['title'];?></a></li>
</ul>
</div>
<div class="tle" style="margin:0px;">
<div class="ti">
<a href="<?php echo $data[12]['link'];?>" target="_blank"><?php echo $data[12]['title'];?></a>
</div>
<ul>
<li><a href="<?php echo $data[13]['link'];?>" target="_blank"><?php echo $data[13]['title'];?></a></li>
<li><a href="<?php echo $data[14]['link'];?>" target="_blank"><?php echo $data[14]['title'];?></a></li>
<li><a href="<?php echo $data[15]['link'];?>" target="_blank"><?php echo $data[15]['title'];?></a></li>
</ul>
</div>
<div class="wx" style="display:none;">
<img src="<?php echo $data[16]['picture'];?>" />
</div>
<div class="shux"></div>
<div class="tle jaelx">
<div class="ti">
<a>JAE特色中国系统支持</a>
</div>
<ul>
<li><a>湖北馆提供JAE特色中国系统</a></li>
<li><a>提供免费使用体验</a></li>
<li><a target="_blank" href="http://www.taobao.com/webww/ww.php?ver=3&touid=%E7%86%8A%E6%80%80%E7%AB%B9&siteid=cntaobao&status=1&charset=utf-8">旺旺:熊怀竹<img border="0" src="http://amos.alicdn.com/realonline.aw?v=2&uid=%E7%86%8A%E6%80%80%E7%AB%B9&site=cntaobao&s=1&charset=utf-8" alt="和我联系" /></a></li>
</ul>
</div>
</div>
</div>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<!-- 底部 end -->
<file_sep>/caches/caches_template/weifang2/content/index.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head');?>
<!--首屏-->
<div class="wrap" style="height:400px; position:relative; ">
<div class="root61" style="z-index:22">
<div class="smCategorys">
<div class="sm-c-wrap J_TWidget" data-widget-type="Slide"
data-widget-config="{'navCls':'yslider-stick','contentCls':'yslider-stage','activeTriggerCls':'curr',
'delay':0.2,'effect':'fade','easing':'easeBoth','duration':0.8,'autoplay':false}" >
<div class="menu yslider-stick" >
<div class="item fore1 ">
<i class="i1 "></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=10 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=10 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore2">
<i class="i2"></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=16 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=16 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore3">
<i class="i3"></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=17 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=17 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore4">
<i class="i4"></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=18 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=18 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore5">
<i class="i5"></i>
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=19 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=19 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="focus J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'tab-nav','contentCls':'tab-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [710], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<div class="prev"></div><div class="next"></div>
<div class="tab-content">
<?php $sql="SELECT * FROM jae_focus WHERE status=1 ORDER BY listorder ASC ";
$r_focus=query($sql); foreach ($r_focus as $r) {?>
<div><a href="<?php echo $r["link"]?>" target="_blank"> <img src="<?php echo $r["picture"]?>" width="710" height="400"/></a></div>
<?php }?>
</div>
<div class="tab-nav">
<?php $r_focuss=query($sql); foreach ($r_focuss as $k=>$rs) {?>
<div class="v<?php echo $k?>"></div>
<?php }?>
</div>
</div>
<div class="bn">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=21 ORDER BY listorder,id ASC LIMIT 0,2 ');
foreach ($result as $v) { if(!empty($v['picture'])){
?><a target="_blank" href="<?php echo $v['link'];?>"><img width="290" style="display:block" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php } }
?>
</div>
<div class="clear"></div>
</div>
<div class="blank"></div>
<!--首屏END-->
<!--至尊推荐-->
<div class="wrap">
<div class="sk-con"><div class="title"> <img src="http://img04.taobaocdn.com/imgextra/i4/2063414185/T2ILhJX9lXXXXXXXXX_!!2063414185.png" /></div>
<div class="sk-item">
<ul class="clearfix">
<?php $result=get_goods(7,3);foreach( $result as $r){ ?>
<li><div class="p-img"><a href="<?php echo $r['detail_url'];?>" target="_blank"><img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img width="240" height="240" data-ks-lazyload="<?php echo $r['pic_url'];?>" ></a></div><div class="p-name"><a href="<?php echo $r['detail_url'];?>" target="_blank"><?php echo $r['title'];?></a></div><div class="p-price"><strong>¥<?php echo $r['coupon_price'];?></strong><del><?php echo $r['price'];?></del></div><div class="p-btn"><a class="btn-m seckilling" href="<?php echo $r['detail_url'];?>" target="_blank">立即购买</a></div></li>
<?php } ?>
</ul>
</div>
</div>
<div class="freshSale">
<div class="title"><img src="http://img02.taobaocdn.com/imgextra/i2/2063414185/TB2S1rBXVXXXXcIXXXXXXXXXXXX-2063414185.png"></div>
<div class="mc">
<div class="p-img">
<?php $result=get_goods(8,1);foreach( $result as $r){ ?>
<a href="<?php echo $r['detail_url'];?>" target="_blank"><img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product" width="260" height="260" data-ks-lazyload="<?php echo $r['pic_url'];?>" ></a>
<div class="p-name"><a href="<?php echo $r['detail_url'];?>" target="_blank"><?php echo $r['title'];?></a></div>
<div class="p-ext">
特价优惠,限时抢购!
</div>
<?php } ?>
</div>
</div>
</div>
<div class="clear"> </div>
</div>
<!--至尊推荐END-->
<!--潍坊精选-->
<div class="wrap">
<div class="title"><img src="http://img02.taobaocdn.com/imgextra/i2/2063414185/TB2D2HBXVXXXXaoXXXXXXXXXXXX-2063414185.png"></div>
<div class="jinxuan">
<div class="sk-item">
<ul class="clearfix">
<?php $result=get_goods(9,4);foreach( $result as $r){ ?>
<li><div class="p-img"><a href="<?php echo $r['detail_url'];?>" target="_blank"><img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img width="240" height="240" data-ks-lazyload="<?php echo $r['pic_url'];?>" ></a></div><div class="p-name"><a href="<?php echo $r['detail_url'];?>" target="_blank"><?php echo $r['title'];?></a></div><div class="p-price"><strong>¥<?php echo $r['coupon_price'];?></strong><del><?php echo $r['price'];?></del></div><div class="p-btn"><a class="btn-m seckilling" href="<?php echo $r['detail_url'];?>" target="_blank">立即购买</a></div></li>
<?php } ?>
</ul></div>
</div>
</div>
<!--潍坊精选END-->
<!--特色品类-->
<div class="blank"> </div>
<div class="wrap tese">
<div class="title"> <img src="http://img01.taobaocdn.com/imgextra/i1/2063414185/T2wctJX7hXXXXXXXXX_!!2063414185.png" /></div>
<div class="main">
<div class="main_t">
<div class="main_b">
<?php echo block(5);?>
<div class="clear"> </div>
</div>
</div>
</div>
</div>
<!--特色品类END-->
<!--特产专辑-->
<div class="wrap">
<div class="title"><img src="http://img03.taobaocdn.com/imgextra/i3/2063414185/T2CrRIXYtaXXXXXXXX_!!2063414185.png"></div>
<div class="zhuanji">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 0,4 ');
foreach ($result as $v) { if(!empty($v['picture'])){
?><div class="li4"><a target="_blank" href="<?php echo $v['link'];?>"><img border="0" height="155" style="float:none;margin:0px;" width="290" data-ks-lazyload="<?php echo $v['picture'];?>"></a></div>
<?php } }
?>
<div class="clear"></div>
</div>
</div>
<!--特产专辑END-->
<!--1楼-->
<div class="blank"> </div>
<div class="louceng wrap">
<div class="title"> <img src="http://img02.taobaocdn.com/imgextra/i2/2063414185/T28s4IXW0aXXXXXXXX_!!2063414185.png" style="float:none;margin:0px;" /></div>
<div class="main">
<div class="main_t">
<div class="main_b">
<?php echo block(6);?>
<div class="right">
<div class="list">
<ul>
<?php $result=get_goods(10,10);foreach( $result as $r){ ?>
<li> <a href="<?php echo $r['detail_url']?>" target="_blank"><img height="200" src="<?php echo $r['pic_url']?>" style="float:none;margin:0px;" width="200" /><br />
<span class="txt"><?php echo $r['title']?></span>
<span class="jg">¥<?php echo round($r['coupon_price'],1);?></span><span class="yj">¥<?php echo round($r['price'],1);?></span> <span class="gm">立即购买</span></a></li>
<?php }?>
</ul>
</div>
</div>
<div class="clear"> </div>
</div>
</div>
</div>
</div>
<!--1楼END-->
<!--2楼-->
<div class="blank"> </div>
<div class="louceng wrap">
<div class="title"> <img src="http://img02.taobaocdn.com/imgextra/i2/2063414185/T2hmhJX7FXXXXXXXXX_!!2063414185.png" style="float:none;margin:0px;" /></div>
<div class="main">
<div class="main_t">
<div class="main_b">
<?php echo block(7);?>
<div class="right">
<div class="list">
<ul>
<?php $result=get_goods(14,10);foreach( $result as $r){ ?>
<li> <a href="<?php echo $r['detail_url']?>" target="_blank"><img data-pinit="registered" height="200" src="<?php echo $r['pic_url']?>" style="float:none;margin:0px;" width="200" /><br />
<span class="txt"><?php echo $r['title']?></span>
<span class="jg">¥<?php echo round($r['coupon_price'],1);?></span><span class="yj">¥<?php echo round($r['price'],1);?></span> <span class="gm">立即购买</span></a></li>
<?php }?>
</ul>
</div>
</div>
<div class="clear"> </div>
</div>
</div>
</div>
</div>
<!--2楼END-->
<!--3楼-->
<div class="blank"> </div>
<div class="louceng wrap">
<div class="title"> <img src="http://img01.taobaocdn.com/imgextra/i1/2063414185/T2jgVMX2BXXXXXXXXX_!!2063414185.png" style="float:none;margin:0px;" /></div>
<div class="main">
<div class="main_t">
<div class="main_b">
<?php echo block(8);?>
<div class="right">
<div class="list">
<ul>
<?php $result=get_goods(15,10);foreach( $result as $r){ ?>
<li> <a href="<?php echo $r['detail_url']?>" target="_blank"><img data-pinit="registered" height="200" src="<?php echo $r['pic_url']?>" style="float:none;margin:0px;" width="200" /><br />
<span class="txt"><?php echo $r['title']?></span>
<span class="jg">¥<?php echo round($r['coupon_price'],1);?></span><span class="yj">¥<?php echo round($r['price'],1);?></span> <span class="gm">立即购买</span></a></li>
<?php }?>
</ul>
</div>
</div>
<div class="clear"> </div>
</div>
</div>
</div>
</div>
<!--3楼END-->
<!--4楼-->
<div class="blank"> </div>
<div class="louceng wrap">
<div class="title"> <img src="http://img01.taobaocdn.com/imgextra/i1/2063414185/T2kU0GX0daXXXXXXXX_!!2063414185.png" style="float:none;margin:0px;" /></div>
<div class="main">
<div class="main_t">
<div class="main_b">
<?php echo block(9);?>
<div class="right">
<div class="list">
<ul>
<?php $result=get_goods(16,10);foreach( $result as $r){ ?>
<li> <a href="<?php echo $r['detail_url']?>" target="_blank"><img data-pinit="registered" height="200" src="<?php echo $r['pic_url']?>" style="float:none;margin:0px;" width="200" /><br />
<span class="txt"><?php echo $r['title']?></span>
<span class="jg">¥<?php echo round($r['coupon_price'],1);?></span><span class="yj">¥<?php echo round($r['price'],1);?></span> <span class="gm">立即购买</span></a></li>
<?php }?>
</ul>
</div>
</div>
<div class="clear"> </div>
</div>
</div>
</div>
</div>
<!--4楼END-->
<div class="blank"> </div>
<!--友情链接-->
<div class="wrap">
<div class="jh">
<?php $result=query('SELECT * FROM jae_link WHERE typeid=0 AND passed=1 ORDER BY listorder ASC LIMIT 0,50 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img data-ks-lazyload="<?php echo $v['logo'];?>"></a>
<?php }?>
<div class="clear"></div>
</div>
</div>
<!--友情链接END-->
<!--版权-->
<?php include template('content','foot');?>
<!--版权END--><file_sep>/upgrade/20140614.sql
ALTER TABLE jae_order ADD goodsid INT(11) DEFAULT null AFTER userid;
UPDATE jae_site SET date='20140612' ;
UPDATE jae_site SET version='136';<file_sep>/jae/modules/admin/templates/site_edit.tpl.php
<?php
defined('IN_JAE') or exit('No permission resources.');
include $this->
admin_tpl('head');
?>
<div class="pad-10">
<form action="?m=admin&c=site&a=edit&siteid=<?php echo $siteid?>
" method="post" id="myform">
<fieldset>
<legend>
<?php echo L('basic_configuration')?></legend>
<table width="100%" class="table_form">
<tr>
<th width="80">
<?php echo L('site_name')?></th>
<td class="y-bg">
<input type="text" class="input-text" name="name" id="name" size="40" value="<?php echo $data['name']?>" /></td>
</tr>
<tr>
<th>
<?php echo L('site_domain')?></th>
<td class="y-bg">
<input type="text" class="input-text" name="domain" id="domain" size="40" value="<?php echo $data['domain']?>" /></td>
</tr>
<tr>
<th>
<?php echo L('APPKEY')?></th>
<td class="y-bg">
<input type="text" class="input-text" name="appkey" id="appkey" size="40" value="<?php echo $data['appkey']?>" /></td>
</tr>
<tr>
<th>
<?php echo L('SECRETKEY')?></th>
<td class="y-bg">
<input type="text" class="input-text" name="secretkey" id="secretkey" size="40" value="<?php echo $data['secretkey']?>" /></td>
</tr>
</table>
</fieldset>
<div class="bk10"></div>
<fieldset>
<legend>
<?php echo L('seo_configuration')?></legend>
<table width="100%" class="table_form">
<tr>
<th width="80">
<?php echo L('site_title')?></th>
<td class="y-bg">
<input type="text" class="input-text" name="site_title" id="site_title" size="40" value="<?php echo $data['site_title']?>" /></td>
</tr>
<tr>
<th>
<?php echo L('keyword_name')?></th>
<td class="y-bg">
<input type="text" class="input-text" name="keywords" id="keywords" size="40" value="<?php echo $data['keywords']?>" /></td>
</tr>
<tr>
<th>
<?php echo L('description')?></th>
<td class="y-bg">
<input type="text" class="input-text" name="description" id="description" size="40" value="<?php echo $data['description']?>" /></td>
</tr>
</table>
</fieldset>
<div class="bk10"></div>
<fieldset>
<legend>
<?php echo L('template_style_configuration')?></legend>
<table width="100%" class="table_form">
<tr>
<th width="80" valign="top">
<?php echo L('style_name')?></th>
<td class="y-bg">
<select name="template[]" size="1" style="width:200px;" id="template" multiple title="<?php echo L('ctrl_more_selected')?>
" onchange="default_list()">
<?php
$default_template_list = array();
if (isset($data['template'])) {
$dirname = $data['template'];
} else {
$dirname = array();
}
if(is_array($template_list)):
foreach ($template_list as $key=>
$val):
$default_template_list[$val['dirname']] = $val['name'];
?>
<option value="<?php echo $val['dirname']?>" <?php if($val['dirname']==$dirname){echo 'selected';}?> ><?php echo $val['name'] ;?></option>
<?php endforeach;endif;?></select>
</td>
</tr>
</table>
</fieldset>
<div class="bk10"></div>
<fieldset>
<legend>
<?php echo L('site_att_config')?></legend>
<table width="100%" class="table_form">
<tr>
<th width="130" valign="top">
<?php echo L('Í·˛żLOGO')?></th>
<td class="y-bg">
<input type="text" class="input-text" name="setting[head_logo]" id="head_logo" size="50" value="<?php echo $setting['head_logo'] ? $setting['head_logo'] : '' ?>"/> </td>
</tr>
<tr>
<th width="130" valign="top">
<?php echo L('µ×˛żLOGO')?></th>
<td class="y-bg">
<input type="text" class="input-text" name="setting[foot_logo]" id="foot_logo" size="50" value="<?php echo $setting['foot_logo'] ? $setting['foot_logo'] : '' ?>"/> </td>
</tr>
</table>
</fieldset>
<div class="bk15"></div>
<input type="submit" class="button" id="dosubmit" name="dosubmit" value="<?php echo L('submit')?>" />
</form>
</div>
<?php
include $this->admin_tpl('foot');
?><file_sep>/demo/csv.php
<?php
header( "Cache-Control: public" );
header( "Pragma: public" );
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:attachment;filename=txxx.csv");
header('Content-Type:APPLICATION/OCTET-STREAM');
?>
2,31,32131,23,123,1,23,12,3,123
1,2,3,45,,655,6,76,7,67,68,6,87,<file_sep>/caches/caches_template/liaoning/content/index.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head');?>
<!-- <link rel="stylesheet" href="/statics/css/lows.css" />
<div class="lows-banner J_TWidget" style="display:none" id="J_LowsBanner" data-widget-type="Carousel" data-widget-config="{'navCls':'ks-switchable-nav','contentCls':'ks-switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'active','autoplay':'true','interval':3,'prevBtnCls': 'prev', 'nextBtnCls': 'next', 'disableBtnCls': 'disable' }">
<div class="trigger-wrap">
<span class="close J_LowsClose"></span>
<span class="prev"></span>
<span class="next"></span>
<ol class="lows-trigger ks-switchable-nav">
<li class="ks-switchable-trigger-internal297 active"></li>
<li class="ks-switchable-trigger-internal297 "></li>
<li class="ks-switchable-trigger-internal297"></li>
</ol>
</div>
<ul class="ks-switchable-content clear-fix">
<li class="pic1 ks-switchable-panel-internal298" style="display: block; opacity: 0; position: absolute; z-index: 1; "><div class="banner-pic" style="background: url(http://img02.taobaocdn.com/imgextra/i2/2063414185/TB2vZdVaXXXXXXpXXXXXXXXXXXX-2063414185.png) no-repeat 0 0;"></div></li>
<li class="pic2 ks-switchable-panel-internal298" style="display: block; opacity: 1; position: absolute; z-index: 9; "><div class="banner-pic" style="background: url(http://img01.taobaocdn.com/imgextra/i1/2063414185/TB26QXZaXXXXXXuXXXXXXXXXXXX-2063414185.png) no-repeat 0 0;"></div></li>
<li class="pic3 ks-switchable-panel-internal298" style="display: block; opacity: 0; position: absolute; z-index: 1; "><div class="banner-pic" style="background: url(http://img02.taobaocdn.com/imgextra/i2/2063414185/TB2R10VaXXXXXXNXXXXXXXXXXXX-2063414185.png) no-repeat 0 0;"></div></li>
</ul>
</div> -->
<div class="body_bg">
<!--首屏-->
<div class="wrap" style="height:35 0px; position:relative; ">
<div class="root61" style="z-index:22">
<div class="smCategorys">
<div class="sm-c-wrap J_TWidget" data-widget-type="Slide"
data-widget-config="{'navCls':'yslider-stick','contentCls':'yslider-stage','activeTriggerCls':'curr',
'delay':0.2,'effect':'fade','easing':'easeBoth','duration':0.8,'autoplay':false}" >
<div class="menu yslider-stick" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=eab0d7e8a2cd1da6e61c4b8e7dd085dc&action=lists&typeid=10&num=4&order=listorder+ASC&return=data\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=eab0d7e8a2cd1da6e61c4b8e7dd085dc&action=lists&typeid=10&num=4&order=listorder+ASC&return=data\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$data = $weblink_tag->lists(array('typeid'=>'10','order'=>'listorder ASC','limit'=>'4',));}?>
<div class="item fore1 ">
<i class="i1 "></i><span class="blank"></span>
<h3><a href="<?php echo $data['0']['link'];?>" target="_blank"><?php echo $data['0']['title'];?></a></h3>
<div class="ext"><a href="<?php echo $data['1']['link'];?>" target="_blank"><?php echo $data['1']['title'];?></a><a href="<?php echo $data['2']['link'];?>" target="_blank"><?php echo $data['2']['title'];?></a><a href="<?php echo $data['3']['link'];?>" target="_blank"><?php echo $data['3']['title'];?></a> </div>
</div>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=fdae7c06f08ea5bb6c8545b60578f732&action=lists&typeid=16&num=4&order=listorder+ASC&return=data\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=fdae7c06f08ea5bb6c8545b60578f732&action=lists&typeid=16&num=4&order=listorder+ASC&return=data\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$data = $weblink_tag->lists(array('typeid'=>'16','order'=>'listorder ASC','limit'=>'4',));}?>
<div class="item fore2 ">
<i class="i2 "></i><span class="blank"></span>
<h3><a href="<?php echo $data['0']['link'];?>" target="_blank"><?php echo $data['0']['title'];?></a></h3>
<div class="ext"><a href="<?php echo $data['1']['link'];?>" target="_blank"><?php echo $data['1']['title'];?></a><a href="<?php echo $data['2']['link'];?>" target="_blank"><?php echo $data['2']['title'];?></a><a href="<?php echo $data['3']['link'];?>" target="_blank"><?php echo $data['3']['title'];?></a> </div>
</div>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=1640ed4f9dd20684ef3f6e615b5d7244&action=lists&typeid=17&num=4&order=listorder+ASC&return=data\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=1640ed4f9dd20684ef3f6e615b5d7244&action=lists&typeid=17&num=4&order=listorder+ASC&return=data\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$data = $weblink_tag->lists(array('typeid'=>'17','order'=>'listorder ASC','limit'=>'4',));}?>
<div class="item fore3 ">
<i class="i3 "></i><span class="blank"></span>
<h3><a href="<?php echo $data['0']['link'];?>" target="_blank"><?php echo $data['0']['title'];?></a></h3>
<div class="ext"><a href="<?php echo $data['1']['link'];?>" target="_blank"><?php echo $data['1']['title'];?></a><a href="<?php echo $data['2']['link'];?>" target="_blank"><?php echo $data['2']['title'];?></a><a href="<?php echo $data['3']['link'];?>" target="_blank"><?php echo $data['3']['title'];?></a> </div>
</div>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=142994642bf1c91846857dac96046d2a&action=lists&typeid=18&num=4&order=listorder+ASC&return=data\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=142994642bf1c91846857dac96046d2a&action=lists&typeid=18&num=4&order=listorder+ASC&return=data\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$data = $weblink_tag->lists(array('typeid'=>'18','order'=>'listorder ASC','limit'=>'4',));}?>
<div class="item fore4 ">
<i class="i4"></i><span class="blank"></span>
<h3><a href="<?php echo $data['0']['link'];?>" target="_blank"><?php echo $data['0']['title'];?></a></h3>
<div class="ext"><a href="<?php echo $data['1']['link'];?>" target="_blank"><?php echo $data['1']['title'];?></a><a href="<?php echo $data['2']['link'];?>" target="_blank"><?php echo $data['2']['title'];?></a><a href="<?php echo $data['3']['link'];?>" target="_blank"><?php echo $data['3']['title'];?></a> </div>
</div>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=d5897117a01ab57b058a910c7925769e&action=lists&typeid=19&num=4&order=listorder+ASC&return=data\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=d5897117a01ab57b058a910c7925769e&action=lists&typeid=19&num=4&order=listorder+ASC&return=data\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$data = $weblink_tag->lists(array('typeid'=>'19','order'=>'listorder ASC','limit'=>'4',));}?>
<div class="item fore5 ">
<i class="i5 "></i><span class="blank"></span>
<h3><a href="<?php echo $data['0']['link'];?>" target="_blank"><?php echo $data['0']['title'];?></a></h3>
<div class="ext"><a href="<?php echo $data['1']['link'];?>" target="_blank"><?php echo $data['1']['title'];?></a><a href="<?php echo $data['2']['link'];?>" target="_blank"><?php echo $data['2']['title'];?></a><a href="<?php echo $data['3']['link'];?>" target="_blank"><?php echo $data['3']['title'];?></a> </div>
</div>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div></div></div>
</div>
<div class="focus J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'tab-nav','contentCls':'tab-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [700], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<div class="prev"></div><div class="next"></div>
<div class="tab-content">
<?php $sql="SELECT * FROM jae_focus WHERE status=1 ORDER BY listorder ASC ";
$r_focus=query($sql); foreach ($r_focus as $r) {?>
<div><a href="<?php echo $r["link"]?>" target="_blank"> <img src="<?php echo $r["picture"]?>" width="740" height="340"/></a></div>
<?php }?>
</div>
<div class="tab-nav">
<?php $r_focuss=query($sql); foreach ($r_focuss as $k=>$rs) {?>
<div class="v<?php echo $k?>"></div>
<?php }?>
</div>
</div>
<div class="bn" >
<a target="_blank" href="/index.php?m=point&c=index&a=point_invite"><b>赚积分</b><br>邀请好友入驻</a>
<a target="_blank" href="/index.php?m=prize&c=index&a=init"><b>小积分抽大奖</b><br>每天送积分</a>
<a target="_blank" href="/index.php?m=seckill&c=index&a=init"><b>积分秒杀</b><br>0元天天秒杀</a>
<a target="_blank" href="/index.php?m=exchange&c=index&a=init"><b>积分换购</b><br>换购好礼不限时</a>
</div>
<div class="clear"></div>
</div>
<div class="blank"></div>
<!--首屏END-->
<!--限时秒杀-->
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=8b08b0afeb2669ed06c98a21b553bd67&action=position&posid=75&order=listorder%2Cid+desc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=8b08b0afeb2669ed06c98a21b553bd67&action=position&posid=75&order=listorder%2Cid+desc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'75','order'=>'listorder,id desc','limit'=>'4',));}?>
<?php if($data) { ?>
<div class="wrap">
<div class="sk-con" >
<div class="sk-item">
<ul class="clearfix">
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><div class="p-img"><a href="<?php echo $r['url'];?>" target="_blank"><img width="240" height="240" data-ks-lazyload="<?php echo $r['thumb'];?>" ></a></div><div class="p-name"><a href="<?php echo $r['url'];?>" target="_blank"><?php echo $r['title'];?></a></div><div class="p-price"><strong>¥<?php echo $r['coupon_price'];?></strong><del><?php echo $r['price'];?></del></div><div class="p-btn"><a class="btn-m seckilling" href="<?php echo $r['url'];?>" target="_blank">立即秒杀</a></div>
<div class="remind_time" ><?php if ($r['end_time']>SYS_TIME ) {?> 开始时间:<span><?php echo date( 'm月d日 H时i分s秒', $r['begin_time'] ); } elseif ($r['end_time']<SYS_TIME ) echo "已经结束";?></span></div>
</li>
<?php $n++;}unset($n); ?> </ul>
</div>
</div>
<div class="clear"> </div>
</div><?php } ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<!--限时秒杀END-->
<!--精品推荐-->
<div class="wrap">
<div class="title" ><img src="http://img03.taobaocdn.com/imgextra/i3/2139364924/TB2r00vaVXXXXXvXpXXXXXXXXXX_!!2139364924.png"/></div><div class="jinxuan">
<div class="sk-item">
<ul class="clearfix"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=8d9ccfa19c1319bdb81ddceda3de5f64&action=position&posid=76&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=8d9ccfa19c1319bdb81ddceda3de5f64&action=position&posid=76&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'76','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><div class="p-img"><a href="<?php echo $r['url'];?>" target="_blank"><img width="380" height="380" data-ks-lazyload="<?php echo $r['thumb'];?>" ></a></div><div class="p-name"><a href="<?php echo $r['url'];?>" target="_blank"><?php echo $r['title'];?></a></div><div class="p-price"><strong>¥<?php echo $r['coupon_price'];?></strong><del><?php echo $r['price'];?></del></div><div class="p-btn"><a class="" href="<?php echo $r['url'];?>" target="_blank"><img src="http://img04.taobaocdn.com/imgextra/i4/2139364924/TB2HY8AaVXXXXbHXXXXXXXXXXXX_!!2139364924.png"></a></div></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
</div>
</div>
<!--精品推荐END-->
<!--特色品类-->
<div class="blank"> </div>
<div class="wrap ">
<img src="http://img03.taobaocdn.com/imgextra/i3/2139364924/TB2hoxxaVXXXXczXXXXXXXXXXXX_!!2139364924.png">
<div class="main tese">
<div class="main_t">
<div class="main_b">
<div class="left">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=4a28a4b8b001e7a4a3cbc85c11fa4a55&pos=pinlei\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=4a28a4b8b001e7a4a3cbc85c11fa4a55&pos=pinlei\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'pinlei',));?><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="right"><div class="slide J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'tab-nav','contentCls':'tab-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [300], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<div class="prev"></div><div class="next"></div>
<div class="tab-content">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=fb2918ff2e4177aecd7da51b780c3080&action=lists&id=163&num=1&order=listorder+ASC&return=data\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=fb2918ff2e4177aecd7da51b780c3080&action=lists&id=163&num=1&order=listorder+ASC&return=data\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$data = $weblink_tag->lists(array('id'=>'163','order'=>'listorder ASC','limit'=>'1',));}?>
<div><a href="<?php echo $data['0']['link'];?>" title="<?php echo $data['0']['title'];?>" target="_blank"> <img src="<?php echo $data['0']['picture'];?>" width="300" height="300"/></a></div>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=1c3de7ade978d4dc42150ba3e87718ec&action=lists&id=164&num=1&order=listorder+ASC&return=data\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=1c3de7ade978d4dc42150ba3e87718ec&action=lists&id=164&num=1&order=listorder+ASC&return=data\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$data = $weblink_tag->lists(array('id'=>'164','order'=>'listorder ASC','limit'=>'1',));}?>
<div><a href="<?php echo $data['0']['link'];?>" title="<?php echo $data['0']['title'];?>" target="_blank"> <img src="<?php echo $data['0']['picture'];?>" width="300" height="300"/></a></div>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
<div class="tab-nav">
<div class="v1"></div><div class="v2"></div>
</div>
</div></div>
<div class="clear"> </div>
</div>
</div>
</div>
</div>
<!--特色品类END-->
<!-- 寻味辽宁 -->
<div class="wrap xunwei ">
<div class="title"><img src="http://img02.taobaocdn.com/imgextra/i2/2139364924/TB2BvlwaVXXXXXWXpXXXXXXXXXX_!!2139364924.png"></div>
<div class="main">
<div class="wrap">
<div class="tanxun J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'tab-nav','contentCls':'tab-content','effect': 'fade',
'easing': 'easeIn','triggerType':'click', 'steps':1, 'viewSize': [620], 'circular': true,'activeTriggerCls':'on', 'autoplay':'false','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }">
<div class=" tab-content">
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=15512654e1b265bc29eef32f6fb41a14&action=position&posid=77&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=15512654e1b265bc29eef32f6fb41a14&action=position&posid=77&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'77','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=c64ae45c3d13ff8bc2c5aeee918ec2b6&action=position&posid=78&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=c64ae45c3d13ff8bc2c5aeee918ec2b6&action=position&posid=78&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'78','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=677e09f450afcd4a953391dcecf1c587&action=position&posid=79&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=677e09f450afcd4a953391dcecf1c587&action=position&posid=79&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'79','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=91837f7b39cf20523ddfe79d8f1576e9&action=position&posid=80&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=91837f7b39cf20523ddfe79d8f1576e9&action=position&posid=80&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'80','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=3432261a70d3edfa08bd4a41ae9acbaa&action=position&posid=81&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=3432261a70d3edfa08bd4a41ae9acbaa&action=position&posid=81&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'81','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=f8a7f70e0fccd07c0b1aef0f0b6e6e95&action=position&posid=82&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=f8a7f70e0fccd07c0b1aef0f0b6e6e95&action=position&posid=82&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'82','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=f1694237a4cfb684682445c42d4bd622&action=position&posid=83&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=f1694237a4cfb684682445c42d4bd622&action=position&posid=83&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'83','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=ef9ee639df8afbbf3f4391d3e4fe5766&action=position&posid=84&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=ef9ee639df8afbbf3f4391d3e4fe5766&action=position&posid=84&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'84','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=369f8dd7edb483fa5a3eb3063e668fbc&action=position&posid=85&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=369f8dd7edb483fa5a3eb3063e668fbc&action=position&posid=85&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'85','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=39baebc060823d8cbce3ffe37b4d857a&action=position&posid=86&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=39baebc060823d8cbce3ffe37b4d857a&action=position&posid=86&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'86','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=609fe764fe828a46f6fac5a312241d55&action=position&posid=87&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=609fe764fe828a46f6fac5a312241d55&action=position&posid=87&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'87','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=7d40b147cc9d1736334c93c31fc71de1&action=position&posid=88&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=7d40b147cc9d1736334c93c31fc71de1&action=position&posid=88&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'88','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=e761bb0014389390238bbb74f21fb4cb&action=position&posid=89&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=e761bb0014389390238bbb74f21fb4cb&action=position&posid=89&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'89','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
<ul class="list" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=72ce155160e892ba6b98444f2611d0b0&action=position&posid=90&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=72ce155160e892ba6b98444f2611d0b0&action=position&posid=90&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'90','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><a href="<?php echo $r['url'];?>" target="_blank"><img src="<?php echo $r['thumb'];?>" width="280" height="280" border="0" /></a>
<?php echo $r['title'];?></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
<div class="ditu tab-nav">
<div class="qu1">
<span></span>
朝阳
</div>
<div class="qu2">
<span></span>
阜新
</div>
<div class="qu3"><span></span>
沈阳
</div>
<div class="qu4"><span></span>
铁岭
</div>
<div class="qu5"><span></span>
葫芦岛
</div>
<div class="qu6"><span></span>
锦州
</div>
<div class="qu7"><span></span>
盘锦
</div>
<div class="qu8"><span></span>
辽阳
</div>
<div class="qu9"><span></span>
本溪
</div>
<div class="qu10"><span></span>
抚顺
</div>
<div class="qu11"><span></span>
营口
</div>
<div class="qu12"><span></span>
鞍山
</div>
<div class="qu13"><span></span>
丹东
</div>
<div class="qu14"><span></span>
大连
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 寻味辽宁END -->
<div class="blank"> </div>
<!-- 必买推荐 -->
<div class="wrap bimai">
<div class="title"><img src="http://img03.taobaocdn.com/imgextra/i3/2139364924/TB2Az4FaVXXXXXMXpXXXXXXXXXX_!!2139364924.png"></div>
<div class="main">
<div class="l_img"> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=ac0cdf5cc22841a52604b9b9be2d33b8&action=lists&id=165&num=1&order=listorder+ASC&return=data\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=ac0cdf5cc22841a52604b9b9be2d33b8&action=lists&id=165&num=1&order=listorder+ASC&return=data\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$data = $weblink_tag->lists(array('id'=>'165','order'=>'listorder ASC','limit'=>'1',));}?>
<a href="<?php echo $data['0']['link'];?>" title="<?php echo $data['0']['title'];?>" target="_blank"> <img src="<?php echo $data['0']['picture'];?>" width="320" height="590"/></a>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<div class="r_list"> <div class="list">
<ul>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=c78041c4be1c9ccb16f18bfad3d74b32&action=position&posid=91&order=listorder+asc&num=6\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=c78041c4be1c9ccb16f18bfad3d74b32&action=position&posid=91&order=listorder+asc&num=6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'91','order'=>'listorder asc','limit'=>'6',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li> <a href="<?php echo $r['url']?>" target="_blank"><img height="200" src="<?php echo $r['thumb']?>" style="float:none;margin:0px;" width="200" />
<span class="txt"><?php echo $r['title']?></span>
<span class="jg">¥<?php echo round($r['coupon_price'],1);?></span><span class="yj">¥<?php echo round($r['price'],1);?></span> <span class="gm">立即购买</span></a></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div></div>
</div>
</div>
<!-- 必买推荐END -->
<!--1楼-->
<div class="blank"> </div>
<div class="louceng wrap clearfix">
<div class="title"> <img src="http://img02.taobaocdn.com/imgextra/i2/2139364924/TB2YNdLaVXXXXbdXXXXXXXXXXXX_!!2139364924.png" /></div>
<div class="main">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=59b710c5fabac45bd87fbec0b8af322c&action=lists&typeid=30&num=5&order=listorder+ASC&return=data\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=59b710c5fabac45bd87fbec0b8af322c&action=lists&typeid=30&num=5&order=listorder+ASC&return=data\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$data = $weblink_tag->lists(array('typeid'=>'30','order'=>'listorder ASC','limit'=>'5',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="img<?php echo $n;?>"><a href="<?php echo $r['link'];?>" title="<?php echo $r['title'];?>" target="_blank"><img src="<?php echo $r['picture'];?>"></a></div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
<!--1楼END-->
<!--2楼-->
<div class="blank"> </div>
<div class="louceng wrap clearfix">
<div class="title"> <img src="http://img01.taobaocdn.com/imgextra/i1/2139364924/TB24aNLaVXXXXaZXXXXXXXXXXXX_!!2139364924.png" /></div>
<div class="main">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=db7f5605dd1ed934a9fffa4f167a78af&action=lists&typeid=31&num=5&order=listorder+ASC&return=data\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=db7f5605dd1ed934a9fffa4f167a78af&action=lists&typeid=31&num=5&order=listorder+ASC&return=data\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$data = $weblink_tag->lists(array('typeid'=>'31','order'=>'listorder ASC','limit'=>'5',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="img<?php echo $n;?>"><a href="<?php echo $r['link'];?>" title="<?php echo $r['title'];?>" target="_blank"><img src="<?php echo $r['picture'];?>"></a></div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
<!--2楼END-->
<!--3楼-->
<div class="blank"> </div>
<div class="louceng wrap clearfix">
<div class="title"> <img src="http://img04.taobaocdn.com/imgextra/i4/2139364924/TB24SXIaVXXXXbQXXXXXXXXXXXX_!!2139364924.png" /></div>
<div class="main">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=124cb65aa55906ed9a90f3e02ccd503c&action=lists&typeid=32&num=5&order=listorder+ASC&return=data\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=124cb65aa55906ed9a90f3e02ccd503c&action=lists&typeid=32&num=5&order=listorder+ASC&return=data\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$data = $weblink_tag->lists(array('typeid'=>'32','order'=>'listorder ASC','limit'=>'5',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="img<?php echo $n;?>"><a href="<?php echo $r['link'];?>" title="<?php echo $r['title'];?>" target="_blank"><img src="<?php echo $r['picture'];?>"></a></div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
<!--3楼END-->
<!--4楼-->
<div class="blank"> </div>
<div class="louceng wrap clearfix">
<div class="title"> <img src="http://img04.taobaocdn.com/imgextra/i4/2139364924/TB2_z8EaVXXXXawXpXXXXXXXXXX_!!2139364924.png" /></div>
<div class="main">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=1ff0a913f0ef06c76269bce3799478dc&action=lists&typeid=33&num=5&order=listorder+ASC&return=data\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=1ff0a913f0ef06c76269bce3799478dc&action=lists&typeid=33&num=5&order=listorder+ASC&return=data\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$data = $weblink_tag->lists(array('typeid'=>'33','order'=>'listorder ASC','limit'=>'5',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="img<?php echo $n;?>"><a href="<?php echo $r['link'];?>" title="<?php echo $r['title'];?>" target="_blank"><img src="<?php echo $r['picture'];?>"></a></div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
<!--4楼END-->
<!--5楼-->
<div class="blank"> </div>
<div class="louceng wrap clearfix">
<div class="title"> <img src="http://img02.taobaocdn.com/imgextra/i2/2139364924/TB2zchGaVXXXXXlXpXXXXXXXXXX_!!2139364924.png" /></div>
<div class="main">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"weblink\" data-datas=\"op=weblink&tag_md5=1fc29ae06b94fede0bdcd8af20abdfe5&action=lists&typeid=34&num=5&order=listorder+ASC&return=data\"><a href=\"/admin.php?m=visualization&c=weblink&a=lists&op=weblink&tag_md5=1fc29ae06b94fede0bdcd8af20abdfe5&action=lists&typeid=34&num=5&order=listorder+ASC&return=data\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$weblink_tag = jae_base::load_app_class("weblink_tag", "weblink");if (method_exists($weblink_tag, 'lists')) {$data = $weblink_tag->lists(array('typeid'=>'34','order'=>'listorder ASC','limit'=>'5',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="img<?php echo $n;?>"><a href="<?php echo $r['link'];?>" title="<?php echo $r['title'];?>" target="_blank"><img src="<?php echo $r['picture'];?>"></a></div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
<!--5楼END-->
<div class="blank"> </div>
<!--友情链接-->
<div class="wrap">
<div class="jh">
<?php $result=query('SELECT * FROM jae_link WHERE typeid=0 AND passed=1 ORDER BY listorder ASC LIMIT 0,50 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img data-ks-lazyload="<?php echo $v['logo'];?>"></a>
<?php }?>
<div class="clear"></div>
</div>
</div>
<!--友情链接END-->
<!--版权-->
</div>
<?php include template('content','foot');?>
<!--版权END--><file_sep>/statics/js/datalazyload.js
// JavaScript Document
new KISSY.DataLazyload({diff: 500,});
<file_sep>/caches/caches_template/weifang/content/foot.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><!-- 底部 -->
<div class="bder">
<div class="wrap">
<div class="dilo">
<img height="70" src="<?php echo $site_setting['foot_logo'] ?>">
</div>
<div class="tle">
<div class="ti">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=23 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
<ul>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=23 ORDER BY listorder,id ASC LIMIT 1,3 ');
foreach ($result as $v) {
?><li><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></li>
<?php }
?>
</ul>
</div>
<div class="tle">
<div class="ti">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=23 ORDER BY listorder,id ASC LIMIT 4,1 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
<ul>
<li>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=23 ORDER BY listorder,id ASC LIMIT 5,3 ');
foreach ($result as $v) {
?><li><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></li>
<?php }
?>
</ul>
</div>
<div class="tle">
<div class="ti">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=23 ORDER BY listorder,id ASC LIMIT 8,1 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
<ul>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=23 ORDER BY listorder,id ASC LIMIT 9,3 ');
foreach ($result as $v) {
?><li><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></li>
<?php }
?>
</ul>
</div>
<div class="tle" style="margin:0px;">
<div class="ti">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=23 ORDER BY listorder,id ASC LIMIT 12,1 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
<ul>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=23 ORDER BY listorder,id ASC LIMIT 13,3 ');
foreach ($result as $v) {
?><li><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></li>
<?php }
?>
</ul>
</div>
<div class="wx" style="display:none;">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=23 ORDER BY listorder,id ASC LIMIT 16,1 ');
foreach ($result as $v) {
?><img src="<?php echo $v['picture'];?>" />
<?php }
?>
</div>
<div class="shux"></div>
<div class="tle jaelx">
<div class="ti">
<a>JAE特色中国系统支持</a>
</div>
<ul>
<li><a>湖北馆提供JAE特色中国系统</a></li>
<li><a>提供免费使用体验</a></li>
<li><a>旺旺:熊怀竹</a><a target="_blank" href="http://www.taobao.com/webww/ww.php?ver=3&touid=%E7%86%8A%E6%80%80%E7%AB%B9&siteid=cntaobao&status=1&charset=utf-8"><img border="0" src="http://amos.alicdn.com/realonline.aw?v=2&uid=%E7%86%8A%E6%80%80%E7%AB%B9&site=cntaobao&s=1&charset=utf-8" alt="和我联系" /></a></li>
</ul>
</div>
</div>
</div>
<!-- 底部 end -->
<!-- 右侧悬浮 -->
<!-- 右侧悬浮结束 -->
<file_sep>/statics/js/jquery.sgallery.js
var $ = jQuery;
//$Event,$each
// 首页焦点图
function Carousel (slid) {
var data=$(slid).attr("data-widget-config");
var config=$parseJSON(data)
var sWidth = $(slid).width(); // $(slid).width(); //获取焦点图的宽度(显示面积)
var sHeight = $(slid).height(); // $(slid).width(); //获取焦点图的宽度(显示面积)
var len = $(slid + " ."+config.contentCls).children().length(); //获取焦点图个数
$(slid + " ."+config.contentCls).css({"position":"relective","width":sWidth,"height":sHeight});
$(slid + " ."+config.contentCls).children().css("position", "absolute");
var index = 0;
var picTimer;
//以下代码添加数字按钮和按钮后的半透明条,还有上一页、下一页两个按钮
//为小按钮添加鼠标滑入事件,以显示相应的内容
if(config.triggerType=="click") {
$(slid + " ."+config.navCls).children().css("opacity", 1).click(function() {
index = $(slid + " ."+config.navCls).children().index(this);
showPics(index);
}).eq(0).trigger("click");}
if(config.triggerType=="mouseenter") {
$(slid + " ."+config.navCls).children().css("opacity", 1).mouseenter(function() {
index = $(slid + " ."+config.navCls).children().index(this);
showPics(index);
}).eq(0).trigger("mouseenter");}
//上一页、下一页按钮透明度处理
$(slid).hover(
function(){$(this).find(" ." +config.prevBtnCls).fadeIn(200);$(this).find(" ." +config.nextBtnCls).fadeIn(200)},
function(){$(this).find(" ." +config.prevBtnCls).fadeOut(200);$(this).find(" ." +config.nextBtnCls).fadeOut(200)})
$(slid + " ." +config.prevBtnCls).css("opacity", 0.5).hover(function() {
$(this).stop(true, false).animate({ "opacity": "0.8" }, 300);
}, function() {
$(this).stop(true, false).animate({ "opacity": "0.5" }, 300);
});
$(slid + " ." +config.nextBtnCls).css("opacity", 0.5).hover(function() {
$(this).stop(true, false).animate({ "opacity": "0.8" }, 300);
}, function() {
$(this).stop(true, false).animate({ "opacity": "0.5" }, 300);
});
//上一页按钮
$(slid + " ." +config.prevBtnCls).click(function() {
index -= 1;
if (index == -1) { index = len - 1; }
showPics(index);
});
//下一页按钮
$(slid + " ." +config.nextBtnCls).click(function() {
index += 1;
if (index == len) { index = 0; }
showPics(index);
});
//鼠标滑上焦点图时停止自动播放,滑出时开始自动播放
if(config.autoplay=="true"){
$(slid).hover(function() {
clearInterval(picTimer);
}, function() {
picTimer = setInterval(function() {
showPics(index);
index++;
if (index == len) { index = 0; }
}, config.interval); //此4000代表自动播放的间隔,单位:毫秒
}).trigger("mouseleave");}
//显示图片函数,根据接收的index值显示相应的内容
function showPics(index) { //普通切换
var nowLeft = -index * sWidth; //根据index值计算ul元素的left值
$(slid + " ."+config.contentCls).children().eq(index).stop(true, false).animate({ "z-index": "2","opacity":1 }, 300).siblings().animate({ "z-index": "1","opacity":0 }, 300); //通过animate()调整ul元素滚动到计算出的position
$(slid + " ."+config.navCls).children().removeClass("on").eq(index).addClass("on"); //为当前的按钮切换到选中的效果
$(slid + " ."+config.navCls).children().stop(true, false).animate({ "opacity": "0.9","z-index":"10" }, 300).eq(index).stop(true, false).animate({ "opacity": "1","z-index":"10" }, 300); //为当前的按钮切换到选中的效果
}
};
//向上滚动代码
function startmarquee(elementID,h,n,speed,delay){
var t = null;
var box = '#' + elementID;
$(box).hover(function(){
clearInterval(t);
}, function(){
t = setInterval(start,delay);
}).trigger('mouseout');
function start(){
$(box).children('ul:first').animate({marginTop: '-='+h},speed,function(){
$(this).css({marginTop:'0'}).find('li').slice(0,n).appendTo(this);
})
}
}
//TAB切换
function SwapTab(name,title,content,Sub,cur){
$(name+' '+title).mouseover(function(){
$(this).addClass(cur).siblings().removeClass(cur);
$(content+" > "+Sub).eq($(name+' '+title).index(this)).show().siblings().hide();
});
}
/**
* @author xing
*/
new SwapTab('.tab','div','.cnt','div','on');
new Carousel('.fc');
<file_sep>/caches/caches_template/default/member/setinfo.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php
include template('content','head');
?>
<link href="/statics/css/table_form.css" rel="stylesheet" type="text/css" />
<div class="blank"></div>
<div class="wrap">
<dl class="ui-tab clearfix" id="">
<dt>我的资料</dt>
</dl>
<div class="border">
<div class="pd20">
<div class="content">
<!-- point .summary END -->
<?php echo $msg?>
<form method="post" >
<table class="table_form" cellpadding="0" cellspacing="0" border="0">
<tbody>
<tr>
<th>旺旺:</th>
<td>
<input class="input-text" style="width:95%;" type="text" name="info[wangwang]" value="<?php echo $wangwang?>" size="80"></td>
</tr>
<tr>
<th>收货人姓名:</th>
<td>
<input class="input-text" style="width:95%;" type="text" name="info[nickname]" value="<?php echo $nickname?>" size="80"></td>
</tr>
<tr>
<th>收货地址:</th>
<td>
<input class="input-text" style="width:95%;" type="text" name="info[address]" value="<?php echo $address?>" size="80"></td>
</tr>
<tr>
<th>手机:</th>
<td>
<input class="input-text" style="width:95%;" type="text" name="info[mobile]" value="<?php echo $mobile?>" size="80"></td>
</tr>
<tr>
<th>E-mail:</th>
<td>
<input class="input-text" style="width:95%;" type="text" name="info[email]" value="<?php echo $email?>" size="80"></td>
</tr>
<?php if($memberinfo['groupid']==2) {?> <tr>
<th>店铺名称:</th>
<td>
<input class="input-text" style="width:95%;" type="text" name="info[shop_title]" value="<?php echo $shop_title?>" size="80">
</td>
</tr>
<tr>
<th>店铺简介:</th>
<td> <input class="input-text" style="width:95%;" type="text" name="info[shop_profile]" value="<?php echo $shop_profile?>" size="80">
</td>
</tr>
<tr>
<th>店铺地址:</th>
<td><input class="input-text" style="width:95%;" type="text" name="info[shop_url]" value="<?php echo $shop_url?>" size="80">
</td>
</tr><?php }?>
<tr>
<th colspan="2" style="text-align:center;vertical-align:middle;">
<input class="button" name="dopost" type="submit" value="提交"></th>
</tr>
</tbody>
</table>
</form>
<!-- point .detail END --> </div>
<div class="blank"></div>
<div class="m_main"></div>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<div class="blank"></div><file_sep>/jae/modules/trade/trade.php
<?php
defined('IN_JAE') or exit('No permission resources.');
defined('IN_ADMIN') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
jae_base::load_app_func('global','admin');
class trade extends admin {
public function __construct() {
parent::__construct();
$this->db = jae_base::load_model('trade_model');
$this->menuid=90;
}
public function init () {
$page=$_GET['page'];
$data=$this->db->listinfo($where,$order = 'pub_time DESC',$page, $pages = '10');
$pages=$this->db->pages;
include $this->admin_tpl('trade_list');
}
public function request() {
$siteinfo=siteinfo(SITEID);
$appkey =$siteinfo['appkey'];
$secret =$siteinfo['secretkey'];
jae_base::load_top('topclient');
jae_base::load_top('RequestCheckUtil');
jae_base::load_top('TmcMessagesConsumeRequest');
jae_base::load_top('TmcMessagesConfirmRequest');
$c = new TopClient;
$c->appkey = $appkey;
$c->secretKey =$secret;
// $c->gatewayUrl = "http://gw.api.tbsandbox.com/router/rest";
$req = new TmcMessagesConsumeRequest;
$req->setQuantity(100);
$resp = $c->execute($req);
// print_r($resp);
for ($i=0; $i<count($resp->messages->tmc_message); $i++)
{
$messages_ids.=$resp->messages->tmc_message[$i]->id.",";
$data['id']=$resp->messages->tmc_message[$i]->id;
$data['user_id']=$resp->messages->tmc_message[$i]->user_id;
$data['content']=htmlspecialchars($resp->messages->tmc_message[$i]->content);
$contents=json_decode(htmlspecialchars_decode($resp->messages->tmc_message[$i]->content),true);
$data['buyer_nick']=$contents['buyer_nick'];
$data['auction_id']=$contents['auction_id'];
$data['paid_fee']=$contents['paid_fee'];
$data['auction_count']=$contents['auction_count'];
$data['auction_title']=$contents['auction_title'];
$data['pub_time']=strtotime($resp->messages->tmc_message[$i]->pub_time);
$data['pub_app_key']=$resp->messages->tmc_message[$i]->pub_app_key;
$data['topic']=$resp->messages->tmc_message[$i]->topic;
// print_r($data);
$this->db->insert($data);
}
//确认消息
$req2 = new TmcMessagesConfirmRequest;
$req2->setSMessageIds($messages_ids);
$resp2 = $c->execute($req2);
//stdClass Object ( [messages] => stdClass Object ( [tmc_message] => Array ( [0] => stdClass Object ( [user_id] => 0 [content] => {"buyer_nick":"<KEY>","auction_id":36261151986,"paid_fee":990,"auction_count":1,"auction_title":"韩国风味 水果茶 蜜炼蜂蜜柚子茶248g 玻璃瓶子 买2瓶送勺子包邮"} [id] => 7112500108330773705 [pub_time] => 2014-04-11 23:38:23 [pub_app_key] => 12497914 [topic] => jae_trade_PaidSuccessed ) ) ) )
showmessage(L('add_success').count($resp->messages->tmc_message).'条');
//include $this->admin_tpl('trade_list');
}
public function add() {
$data['id']='7112500108330773705';
$data['user_id']='0';
$data['content']= htmlspecialchars('{"buyer_nick":"<KEY>","auction_id":36261151986,"paid_fee":990,"auction_count":1,"auction_title":"韩国风味 水果茶 蜜炼蜂蜜柚子茶248g 玻璃瓶子 买2瓶送勺子包邮"}') ;
$data['buyer_nick']='<KEY>';
$data['auction_id']='36261151986';
$data['paid_fee']='990';
$data['auction_count']='1';
$data['auction_title']='韩国风味 水果茶 蜜炼蜂蜜柚子茶248g 玻璃瓶子 买2瓶送勺子包邮';
$data['pub_time']=strtotime('2014-04-11 23:38:23');
$data['pub_app_key']='12497914';
$data['topic']="jae_trade_PaidSuccessed";
$this->db->insert($data);
if(isset($_POST['dosubmit'])) {
$data=$_POST['info'];
$this->db->insert($data);
showmessage(L('add_success'));
} else {
$prize_type=jae_base::load_config('prize_type');
include $this->admin_tpl('trade_list');
}
}
public function delete() {
$_GET['id'] = intval($_GET['id']);
$this->db->delete('id='.$_GET['id']);
showmessage(L('operation_success'));
}
public function edit() {
if(isset($_POST['dosubmit'])) {
$id = intval($_POST['id']);
$data=$_POST['info'];
$data['status']=1;
$this->db->update($data,'id='.$id);
showmessage(L('operation_success'));
} else {
$prize_type=jae_base::load_config('prize_type');
$id = intval($_GET['id']);
$r=$this->db->get_one('id='.$id ,'*');
if($r) extract($r);
include $this->admin_tpl('prize_edit');
}
}
/**
* 排序
*/
public function listorder() {
if(isset($_POST['dosubmit'])) {
foreach($_POST['listorders'] as $id => $listorder) {
$listorder = !empty($listorder) ? $listorder : '0';
$this->db->update(array('listorder'=>$listorder),'id='.$id);
$status = isset($_POST["status"][$id]) ? $_POST["status"][$id] : '0';
$this->db->update(array('status'=>$status),'id='.$id);
}
showmessage(L('operation_success'));
} else {
showmessage(L('operation_failure'));
}
}
/**
* 抽奖模块配置
*/
public function setting() {
$m_db = jae_base::load_model('module_model');
$data = $m_db->get_one(array('module'=>'prize'));//array('module'=>'prize')
$setting = string2array($data['setting']);
if(isset($_POST['dosubmit'])) {
$variable = $_POST['setting'];
//更新模型数据库,重设setting 数据.
foreach ($variable as $key => $value) {
$sets[$key]=$value;
}
$sets=new_html_special_chars($sets);
$set = array2string($sets);
setcache('prize', $sets, 'commons');
$m_db->update(array('setting'=>$set), array('module'=>ROUTE_M));
showmessage(L('setting_updates_successful'), '/admin.php?m=prize&c=prize&a=setting&menuid=76');
} else {
@extract($setting);
include $this->admin_tpl('setting');
}
}
}<file_sep>/jae/modules/brand/templates/brand_add.tpl.php
<?php include $this->admin_tpl('head','admin');
?>
<form name="myform" id="myform" action="/admin.php?m=brand&c=brand&a=add" method="post">
<table width="100%" class="table_form contentWrap">
<tbody><tr>
<th width="100">品牌分类:</th>
<td> <select name="info[typeid]">
<option value="0">无分类</option>
<?php
foreach($type as $r){; ?>
<option value="<?php echo $r['typeid']; ?>" <?php if ($r['typeid']==$typeid) echo "selected";?>><?php echo $r['name']; ?></option>
<?php }; ?>
</select></td>
</tr>
<tr>
<th width="100">链接名称:</th>
<td><input style="width:300px;" type="text" name="info[name]" id="language" class="input-text"></td>
</tr>
<tr>
<th> 缩略图地址:</th>
<td><input style="width:300px;" type="text" name="info[logo]" id="language" class="input-text"><div id="languageTip" class="onShow"></div></td>
</tr>
<tr>
<th>链接地址:</th>
<td><input style="width:300px;" type="text" name="info[url]" id="name" class="input-text"><div id="nameTip" class="onShow"></div></td>
</tr>
<tr>
<th>品牌所属单位:</th>
<td><input style="width:300px;" type="text" name="info[username]" id="m" class="input-text"><div id="mTip" class="onShow"></div></td>
</tr>
</tbody></table>
<!--table_form_off-->
<div class="btns"><input type="submit" id="dosubmit" class="button" name="dosubmit" value="提交"></div>
</form>
<?php include $this->admin_tpl('foot','admin');?><file_sep>/jae/modules/brand/templates/brand_list.tpl.php
<?php include $this->admin_tpl('head','admin');?>
<form name="searchform" action="" method="get" accept-charset="UTF-8">
<input type="hidden" value="brand" name="m">
<input type="hidden" value="brand" name="c">
<input type="hidden" value="init" name="a">
<input type="hidden" value="<?php echo $this->menuid;?>" name="menuid">
<table width="100%" cellspacing="0" class="search-form">
<tbody>
<tr>
<td><div class="explain-col"> 品牌分类
<select name="typeid">
<option value="0">无分类</option>
<?php
foreach($type as $r){; ?>
<option value="<?php echo $r['typeid']; ?>" <?php if ($r['typeid']==$typeid) echo "selected";?>><?php echo $r['name']; ?></option>
<?php }; ?>
</select>
<input type="submit" name="search" class="button" value="搜索">
</div></td>
</tr>
</tbody>
</table>
<input name="pc_hash" type="hidden" value="4ua2L3">
</form>
<form name="myform" action="/admin.php?m=brand&c=brand&a=listorder" method="post">
<div class="pad-lr-10">
<div class="table-list">
<table width="100%" cellspacing="0" class="table_form">
<tbody>
<tr class="thead">
<th width="80"><?php echo L('listorder');?></th>
<th width="30"><?php echo L('id');?></th>
<th width="30">状态</th>
<th width="80">缩略图地址</th>
<th>链接名称</th>
<th width="100">品牌所属单位</th>
<th width="200" align="center"><?php echo L('operations_manage');?></th>
</tr>
<?php foreach ($data as $r){?>
<tr>
<td align="center"><input name='listorders[<?php echo $r['brandid'];?>]' type='text' size='3' value='<?php echo $r['listorder'];?>' class='input-text-c input-text'></td>
<td align="center"><?php echo $r['brandid'];?></td>
<td align="center"> <input type="checkbox" name="passed[<?php echo $r['brandid']; ?>]" value="1" <?php if( $r['passed']==1){echo "checked='checked'";}?> ></td>
<td align="center"><img src="<?php echo $r['logo'];?>" height="40"></td>
<td><?php echo $r['name'];?></td>
<td align="center"><?php echo $r['username'];?></td>
<td align="center"><?php echo '<a href="/admin.php?m=brand&c=brand&a=edit&brandid='.$r['brandid'].'&menuid='.$menuid.'">'.L('modify').'</a> | <a href="/admin.php?m=brand&c=brand&a=delete&brandid='.$r['brandid'].'&menuid='.$menuid.'">'.L('delete').'</a> ';?></td>
</tr>
<?php }?>
</tbody>
</table>
<div class="btns"><input type="submit" class="button" name="dosubmit" value="<?php echo L('listorder')?>" /></div> </div>
</div>
</div>
</form>
<div class="pages"><?php echo $pages;?></div>
<?php include $this->admin_tpl('foot','admin');?><file_sep>/caches/caches_template/weifang/content/head.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><cajamodules include="kissy/1.3.0/core,kissy/gallery/layer-anim/1.1/index,kissy/gallery/datalazyload/1.0/index,jquery/1.9/index" />
<script src="http://a.tbcdn.cn/apps/taesite/libs/jquery-ui/jquery1.9.min.js"></script>
<script src="/statics/js/common.js"></script>
<?php $siteinfo=siteinfo(SITEID); $site_setting=string2array($siteinfo['setting']); ?>
<link rel="stylesheet" href="/jae/templates/weifang/css/index.css" />
<div class="top wrap">
<div class="head">
<div class="logo">
<a href="/index.php">
<img height="80" src="<?php echo $site_setting['head_logo'] ?>" />
</a>
</div>
<div class="chandi">
<img src="http://img01.taobaocdn.com/imgextra/i1/2063414185/TB2PN_BXVXXXXcwXXXXXXXXXXXX-2063414185.png">
</div>
<div class="top_right">
<div class="member_btn">
<div class="member_arrow" ><a href="/" target="_blank">会员中心</a></div>
<div class="member_mini_nav" ><div class="prompt"> <span class="fl">您好,<span class="tips">请登录</span></span> <span class="fr"></span> </div><div class="uclist">
<ul class="fore1 fl">
<?php $nav_arr=query('SELECT * FROM jae_member_menu WHERE display=1 AND project1=1 ORDER BY listorder,id ASC'); foreach ($nav_arr as $key =>
$r) { ?>
<li>
<a href="/index.php?m=<?php echo $r['m']?>&c=<?php echo $r['c']?>&a=<?php echo $r['a']?><?php if($r['data']) echo '&'.$r['data'];?>"><?php echo $r['name'] ?></a>
</li>
<?php } ?>
</ul>
<ul class="fore2 fl">
<?php $nav_arr=query('SELECT * FROM jae_member_menu WHERE display=1 AND project1=0 ORDER BY listorder,id ASC'); foreach ($nav_arr as $key =>
$r) { ?>
<li>
<a href="/index.php?m=<?php echo $r['m']?>&c=<?php echo $r['c']?>&a=<?php echo $r['a']?><?php if($r['data']) echo '&'.$r['data'];?>"><?php echo $r['name'] ?> ></a>
</li>
<?php } ?>
</ul>
</div></div>
</div>
<div class="top_point">
<div class="member_point">
<a href="/index.php?m=point&c=index&a=sign&trad=all" target="_blank">0</a>
</div>
<div class="member_sign">
<a href="/index.php?m=member&c=index&a=init" target="_blank">请登录</a>
</div>
</div>
</div>
</div>
</div>
<div class="nav">
<div class="wrap">
<div class="nav_left">
<div class="nav_cat">
热门商品分类
<img src="/assets/images/xxjianta.png" />
</div>
</div>
<div class="nav_li">
<ul>
<li>
<a href="/">首页</a>
</li>
<?php $nav_arr=query('SELECT * FROM jae_category WHERE ismenu=1 ORDER BY listorder,catid ASC'); foreach ($nav_arr as $key =>
$v) { ?>
<li><a target="_blank" href="<?php echo $v['url'] ?>"><?php echo $v['catname'] ?></a></li>
<?php } ?></ul>
</div>
</div>
</div>
<file_sep>/jae/modules/admin/goods.php
<?php
defined('IN_JAE') or exit('No permission resources.');
jae_base::load_app_class('admin', 'admin', 0);
class goods extends admin
{
function __construct()
{
parent::__construct();
$this->db= jae_base::load_model('goods_model');
$this->position_db= jae_base::load_model('position_model');
$this->position_data_db= jae_base::load_model('position_data_model');
$this->menuid = 20;
}
function init()
{ $where= "status=1";
$searchCategoryId=-1;
$searchPindaoId=-1;
$searchPromoteId=-1;
$dopost = isset($_POST["dopost"]) ? $_POST["dopost"] : '';
$page = $_GET['page'];
$data = $this->db->listinfo($where, "id DESC", $page, 10);
$categoryArr = rGetCategoryArr();
$promotePositionArr = rGetPromotePositionArr();
$pindaoArr = rGetPindaoArr();
$pages = $this->db->pages;
include $this->admin_tpl('goods_list');
}
function search()
{
$categoryArr = rGetCategoryArr();
$promotePositionArr = rGetPromotePositionArr();
$pindaoArr = rGetPindaoArr();
$where= "status = 1 ";
//搜索
$searchWord=isset($_GET['searchWord'])?$_GET['searchWord']:'';
$searchCategoryId=isset($_GET['searchCategoryId'])?$_GET['searchCategoryId']:'';
$searchPindaoId=isset($_GET['searchPindaoId'])?$_GET['searchPindaoId']:'';
$searchPromoteId=isset($_GET['searchPromoteId'])?$_GET['searchPromoteId']:'';
if (!empty( $searchWord))$where .= " AND `title` LIKE '%$searchWord%' OR `num_iid` = '$searchWord' OR `nick` = '$searchWord'";
if ($searchPromoteId>=0) $where .=" AND promote_id = '$searchPromoteId' ";
if($searchCategoryId>=0)$where .=" AND category_id = $searchCategoryId";
if($searchPindaoId>=0)$where .=" AND pindao_id = $searchPindaoId";
//if($searchPromoteId>=0)$where .=" AND promote_id = $searchPromoteId";
//搜索结束
$page=$_GET['page'];
$data=$this->db->listinfo($where,"id DESC",$page,10);
$pages=$this->db->pages;
include $this->admin_tpl('goods_list');
}
function goods_collect (){
$position=$this->position_db->select(array('modelid'=>1),'posid,name','',"posid ASC");
foreach ($position as $v){$position_array[$v['posid']]=$v['name'] ;}
$categoryArr = rGetCategoryArr();
$numiid = isset($_POST['numiid']) ? trim($_POST['numiid']) : ''; //提交过来的num_iid
if (isset($_POST['dopost'])) {
if ($numiid != "" && rRuleNum($numiid)) {
$array=goods_collect($numiid);
extract($array);
} else {
showmessage(L('商品ID不能为空并且必须是数字'));
}
}
include $this->admin_tpl('goods_add');
}
function add()
{
$position=$this->position_db->select(array('modelid'=>1),'posid,name','',"posid ASC");
foreach ($position as $v){$position_array[$v['posid']]=$v['name'] ;}
$categoryArr = rGetCategoryArr();
if (isset($_POST['dosubmit'])) {
$data=$_POST['info'];
$data['begin_time']=strtotime($_POST['info']['begin_time']);
$data['end_time']=strtotime($_POST['info']['end_time']);
$data['status']=1;
$data['create_time']=SYS_TIME;
$insert_id=$this->db->insert($data,$return_insert_id =true);
$posids=$_POST['posids'];
$arr['title']=$data['title'];
$arr['isicon']=$data['isicon'];
$arr['icon_url']=$data['icon_url'];
$arr['thumb']=$data['pic_url'];
$arr['url']=$data['detail_url'];
$arr['inputtime']=$data['begin_time'];
$arr['price']=$data['price'];
$arr['coupon_price']=$data['coupon_price'];
$arr['begin_time']=$data['begin_time'];
$arr['end_time']=$data['end_time'];
$string=array2string($arr);
foreach ($posids as $posid){
$this->position_data_db->insert(array('posid'=>$posid,'id'=>$insert_id,'modelid'=>1,'module'=>'goods','data'=>$string,'expiration'=>$data['begin_time'],'siteid'=>SITEID));
}
showmessage(L('operation_success'));
}
include $this->admin_tpl('goods_add');
}
function delete()
{
if(is_array($_POST['ids'])){
foreach($_POST['ids'] as $id) {
print_r($linkid_arr);
//批量删除友情链接
$this->db->delete('id=' . $id);
}
showmessage(L('operation_success'),'?m=link&c=link');
}
$_GET['id'] = intval($_GET['id']);
$this->db->delete('id=' . $_GET['id']);
showmessage(L('operation_success'));
}
function edit()
{
$categoryArr= rGetCategoryArr();
$position=$this->position_db->select(array('modelid'=>1),'posid,name','',"posid ASC");
foreach ($position as $v){$position_array[$v['posid']]=$v['name'] ;}
if (isset($_POST['dosubmit'])) {
$id = intval($_POST['id']); $data = $_POST['info'];
$data["begin_time"] = strtotime($_POST['info']["begin_time"]);
$data["end_time"] = strtotime($_POST['info']["end_time"]);
$this->db->update($data, 'id=' . $id);
$this->position_data_db->delete(array('id'=>$id,'module'=>'goods'));
$posids=$_POST['posids'];
$arr['title']=$data['title'];
$arr['isicon']=$data['isicon'];
$arr['icon_url']=$data['icon_url'];
$arr['thumb']=$data['pic_url'];
$arr['url']=$data['detail_url'];
$arr['inputtime']=$data['begin_time'];
$arr['price']=$data['price'];
$arr['coupon_price']=$data['coupon_price'];
$arr['begin_time']=$data['begin_time'];
$arr['end_time']=$data['end_time'];
$string=array2string($arr);
foreach ($posids as $posid){
$this->position_data_db->insert(array('posid'=>$posid,'id'=>$id,'module'=>'goods','modelid'=>1,'data'=>$string,'expiration'=>$data['begin_time'],'siteid'=>SITEID));
}
showmessage(L('operation_success'));
} else {
$id = intval($_GET['id']);
$posids=$this->position_data_db->select(array('id'=>$id,'module'=>"goods"),"*","1000","id ASC ");
foreach ($posids as $c){ $posids_array[]=$c['posid'];}
$r = $this->db->get_one( 'id=' . $id);
extract($r);
include $this->admin_tpl('goods_edit');
}
}
/**
* 排序
*/
function listorder()
{
if (isset($_POST['dosubmit'])) {
foreach ($_POST['listorders'] as $id => $listorder) {
$listorder = !empty($listorder) ? $listorder : '0';
$this->db->update(array('listorder' => $listorder), 'id=' . $id);
$status = isset($_POST["status"][$id]) ? $_POST["status"][$id] : '0';
$this->db->update(array('status' => $status), 'id=' . $id);
}
showmessage(L('operation_success'));
} else {
showmessage(L('operation_failure'));
}
}
}
?><file_sep>/caches/caches_template/gansu/content/index.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head');?>
<link rel="stylesheet" href="/statics/css/lows.css" />
<div class="lows-banner J_TWidget" style="display:none" id="J_LowsBanner" data-widget-type="Carousel" data-widget-config="{'navCls':'ks-switchable-nav','contentCls':'ks-switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'active','autoplay':'true','interval':3,'prevBtnCls': 'prev', 'nextBtnCls': 'next', 'disableBtnCls': 'disable' }">
<div class="trigger-wrap">
<span class="close J_LowsClose"></span>
<span class="prev"></span>
<span class="next"></span>
<ol class="lows-trigger ks-switchable-nav">
<li class="ks-switchable-trigger-internal297 active"></li>
<li class="ks-switchable-trigger-internal297 "></li>
<li class="ks-switchable-trigger-internal297"></li>
</ol>
</div>
<ul class="ks-switchable-content clear-fix">
<li class="pic1 ks-switchable-panel-internal298" style="display: block; opacity: 0; position: absolute; z-index: 1; "><div class="banner-pic" style="background: url(http://img01.taobaocdn.com/imgextra/i1/2063404741/TB2jVoFXVXXXXauXpXXXXXXXXXX-2063404741.png) no-repeat 0 0;"></div></li>
<li class="pic2 ks-switchable-panel-internal298" style="display: block; opacity: 1; position: absolute; z-index: 9; "><div class="banner-pic" style="background: url(http://img03.taobaocdn.com/imgextra/i3/2063404741/TB2nF.HXVXXXXctXXXXXXXXXXXX-2063404741.png) no-repeat 0 0;"></div></li>
<li class="pic3 ks-switchable-panel-internal298" style="display: block; opacity: 0; position: absolute; z-index: 1; "><div class="banner-pic" style="background: url(http://img03.taobaocdn.com/imgextra/i3/2063404741/TB2hu.GXVXXXXcBXXXXXXXXXXXX-2063404741.png) no-repeat 0 0;"></div></li>
</ul>
</div>
<div class="body_bg">
<!--首屏-->
<div class="wrap" style="height:400px; position:relative; ">
<div class="root61" style="z-index:22">
<div class="smCategorys">
<div class="sm-c-wrap J_TWidget" data-widget-type="Slide"
data-widget-config="{'navCls':'yslider-stick','contentCls':'yslider-stage','activeTriggerCls':'curr',
'delay':0.2,'effect':'fade','easing':'easeBoth','duration':0.8,'autoplay':false}" >
<div class="menu yslider-stick" >
<div class="item fore1 ">
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=10 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=10 ORDER BY listorder,id ASC LIMIT 1,10 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore2">
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=16 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=16 ORDER BY listorder,id ASC LIMIT 1,10 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore3">
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=17 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=17 ORDER BY listorder,id ASC LIMIT 1,10 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore4">
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=18 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=18 ORDER BY listorder,id ASC LIMIT 1,10 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore5">
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=19 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=19 ORDER BY listorder,id ASC LIMIT 1,10 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
<div class="item fore6">
<span class="blank"></span>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=32 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<h3><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a></h3><?php }?>
<div class="ext">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=32 ORDER BY listorder,id ASC LIMIT 1,10 ');
foreach ($result as $v) {
?><a href="<?php echo $v['link'];?>" target="_blank"><?php echo $v['title'];?></a>
<?php }
?>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="focus J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [710], 'circular': true, 'activeTriggerCls':'on','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable'}" >
<div class="prev"></div><div class="next"></div>
<div class="tabs-content switchable-content">
<?php $sql="SELECT * FROM jae_focus WHERE status=1 ORDER BY listorder ASC ";
$r_focus=query($sql); foreach ($r_focus as $r) {?>
<div><a href="<?php echo $r["link"]?>" target="_blank"> <img src="<?php echo $r["picture"]?>" width="710" height="400"/></a></div>
<?php }?>
</div>
<div class="tabs-nav switchable-nav">
<?php $r_focuss=query($sql); foreach ($r_focuss as $k=>$rs) {?>
<div class="v<?php echo $k?>"></div>
<?php }?>
</div>
</div>
<div class="bn">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=21 ORDER BY listorder,id ASC LIMIT 0,2 ');
foreach ($result as $v) { if(!empty($v['picture'])){
?><a target="_blank" href="<?php echo $v['link'];?>"><img width="290" style="display:block" src="<?php echo $v['picture'];?>"></a>
<?php } }
?>
</div>
<div class="clear"></div>
</div>
<div class="blank"></div>
<!--首屏END-->
<div class="wrap">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=21 ORDER BY listorder,id ASC LIMIT 2,1 ');
foreach ($result as $v) { if(!empty($v['picture'])){
?><a target="_blank" href="<?php echo $v['link'];?>"><img width="1210" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php } }
?>
</div>
<!--积分换购 -->
<!--
<div style=" height:25px; clear:both;"></div>
<div class="wrap root61">
<h2 class="jfhgzt">积分换购</h2>
<div class="jfhgsm">积分换购为全额换购 无需付邮费</div>
<div style="clear:both;"></div>
<div class="jfhg">
<?php $result=query('SELECT * FROM jae_exchange ORDER BY ID desc LIMIT 0,4 ');
foreach ($result as $v) {
?><div class="jfhgkj"><a target="_blank" href="/index.php?m=exchange&c=index&a=exchange&id=<?php echo $v['id']?>" title="<?php echo $v['title'];?>"><div class="jfhgsp"><img data-ks-lazyload="<?php echo $v['pic_url'];?>"></div>
<div class="jfhgbt"><?php echo $v['title'];?></div>
<div class="jfhgjf">换购所需积分:<span><?php echo $v['point'];?></span>甘肃馆积分</div>
<div class="jfhgyj">原价:¥<?php echo $v['price'];?></div></a>
<a target="_blank" href="/index.php?spm=a216r.7118237.1.21.oVIVsm&m=point&c=index&a=point_invite"><div class="jfhghq">点我获取积分</div></a>
<a target="_blank" href="<?php echo $v['detail_url'];?>"><div class="jfhghq jfhgck">查看宝贝详情</div></a></div>
<?php }
?>
</div>
</div>
-->
<!-- 积分换购end -->
<!-- 火爆热销 -->
<div style=" height:25px; clear:both;"></div>
<div class="wrap root61">
<h2 class="jfhgzt">火爆热销</h2>
<div class="jfhgsm"></div>
<div style="clear:both;"></div>
<div class="jdjby">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=ce4bb761bc4038a998578bc28f046966&action=position&posid=74&order=id+desc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=ce4bb761bc4038a998578bc28f046966&action=position&posid=74&order=id+desc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'74','order'=>'id desc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <div class="jfhgkj"><a target="_blank" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>"><div class="jfhgsp"><img data-ks-lazyload="<?php echo $r['thumb'];?>"></div>
<div class="jdjgbt"><?php echo $r['title'];?></div>
<div class="jdjljgm">立即购买</div></a></div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
<!-- 火爆热销 end-->
<!--9.9包邮 -->
<div style=" height:25px; clear:both;"></div>
<div class="wrap">
<div class="sk-con">
<div class="sk-item">
<ul class="clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=3ab29c546ebf3da3e8328275730cf193&action=position&posid=78&order=listorder+asc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=3ab29c546ebf3da3e8328275730cf193&action=position&posid=78&order=listorder+asc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'78','order'=>'listorder asc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li><div class="p-img"><a href="<?php echo $r['url'];?>" target="_blank"><img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img width="240" height="240" data-ks-lazyload="<?php echo $r['thumb'];?>" ></a></div><div class="p-name"><a href="<?php echo $r['url'];?>" target="_blank"><?php echo $r['title'];?></a></div><div class="p-price"><strong>¥<?php echo $r['coupon_price'];?></strong><del><?php echo $r['price'];?></del></div><div class="p-btn"><a class="btn-m seckilling" href="<?php echo $r['url'];?>" target="_blank">立即购买</a></div></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
</div>
<div class="clear"> </div>
</div>
<!-- 9.9包邮end -->
<!--抽奖 -->
<div style="height:30px; clear:both;"></div>
<div class="wrap root61">
<h2>会员抽奖</h2>
<div class="abenti">
<div class="chojdkm">
<div class="bejsl">
<?php $result=query('SELECT * FROM jae_prize_set WHERE status=1 ORDER BY listorder,id ASC LIMIT 0,6 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['url'];?>"><img data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="zjsl">
<a target="_blank" href="/index.php?spm=a216r.7118237.1.17.dF0fJJ&m=prize&c=index&a=init"><img data-ks-lazyload="http://img02.taobaocdn.com/imgextra/i2/2063404741/TB2c7fQXVXXXXbqXXXXXXXXXXXX-2063404741.jpg"></a>
</div>
<div class="bejsl">
<?php $result=query('SELECT * FROM jae_prize_set WHERE status=1 ORDER BY listorder,id ASC LIMIT 6,6 ');
foreach ($result as $v) {
?><a target="_blank" href="<?php echo $v['url'];?>"><img data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="clr"></div>
</div>
</div>
</div>
<!-- 抽奖end -->
<!-- 美食地理 -->
<div style="height:10px; clear:both;"></div>
<div class="wrap root61">
<!-- 美食地理 -->
<div class=" cookingGeology m sm-wrap" clstag="firsttype|keycount|chaoshi|08">
<div class="mt">
<h2>美食地图</h2>
<div class="ext">
<span class="describe">带您吃遍甘肃大地</span>
</div>
</div>
<div class="mc">
<!-- 触发器 -->
<div class="cg-trigger">
</div>
<!-- 触发器 end -->
<div class="cg-hide">
<span class="cg-h-close"></span>
<div class="cg-h-title"></div>
</div>
<!-- 隐藏优惠券 end -->
<!-- 遮罩 -->
<div class="cg-mask left"></div>
<div class="cg-mask right"></div>
<!-- 遮罩 end -->
<!-- 左侧国内 -->
<div class="cookingGeologyLeft cg-wrap left J_TWidget" data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [1210], 'circular': true, 'activeTriggerCls':'curr','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable'}" >
<div class="cg-w-tab">
<div class="cg-w-t-item switchable-nav">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=31 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?><a class="fore1 ui-switchable-item curr" href="<?php echo $v['link'];?>" target="_blank" style="cursor:pointer;">
<div class="cg-w-t-label" style="left:-6px; top: -50px; "></div> <b></b>
<span><?php echo position(30) ?></span>
</a>
<?php }
?>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=31 ORDER BY listorder,id ASC LIMIT 1,1 ');
foreach ($result as $v) {
?>
<a class="fore3 ui-switchable-item" href="<?php echo $v['link'];?>" target="_blank" style="cursor:pointer;">
<div class="cg-w-t-label" style="left:-6px; top: -50px; "></div> <b></b>
<span><?php echo position(31) ?></span>
</a>
<?php }
?>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=31 ORDER BY listorder,id ASC LIMIT 2,1 ');
foreach ($result as $v) {
?>
<a class="fore5 ui-switchable-item" href="<?php echo $v['link'];?>" target="_blank" style="cursor:pointer;">
<div class="cg-w-t-label" style="left:-6px; top: -50px; "></div> <b></b>
<span><?php echo position(32) ?></span>
</a>
<?php }
?>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=31 ORDER BY listorder,id ASC LIMIT 3,1 ');
foreach ($result as $v) {
?>
<a class="fore6 ui-switchable-item" href="<?php echo $v['link'];?>" target="_blank" style="cursor:pointer;">
<div class="cg-w-t-label" style="left:-6px; top: -50px; "></div> <b></b>
<span><?php echo position(33) ?></span>
</a>
<?php }
?>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=31 ORDER BY listorder,id ASC LIMIT 4,1 ');
foreach ($result as $v) {
?>
<a class="fore7 ui-switchable-item" href="<?php echo $v['link'];?>" target="_blank" style="cursor:pointer;">
<div class="cg-w-t-label" style="left:-6px; top: -50px; "></div> <b></b>
<span><?php echo position(76) ?></span>
</a>
<?php }
?>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=31 ORDER BY listorder,id ASC LIMIT 5,1 ');
foreach ($result as $v) {
?>
<a class="fore8 ui-switchable-item" href="<?php echo $v['link'];?>" target="_blank" style="cursor:pointer;">
<div class="cg-w-t-label" style="left:-6px; top: -50px; "></div> <b></b>
<span><?php echo position(34) ?></span>
</a>
<?php }
?>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=31 ORDER BY listorder,id ASC LIMIT 6,1 ');
foreach ($result as $v) {
?>
<a class="fore10 ui-switchable-item" href="<?php echo $v['link'];?>" target="_blank" style="cursor:pointer;">
<div class="cg-w-t-label" style="left:-6px; top: -50px; "></div> <b></b>
<span><?php echo position(35) ?></span>
</a> <?php }
?>
</div>
</div>
<div class="cg-w-con switchable-content" style="position: relative; ">
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=f9920f4550630ee01a1cb673ad80d2a4&action=position&posid=30&order=id+desc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=f9920f4550630ee01a1cb673ad80d2a4&action=position&posid=30&order=id+desc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'30','order'=>'id desc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=81cf9e6f450c426012c76d181bf27b10&action=position&posid=31&order=id+desc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=81cf9e6f450c426012c76d181bf27b10&action=position&posid=31&order=id+desc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'31','order'=>'id desc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=b1403b0ee810ff9be1f4ab1d81888e9a&action=position&posid=32&order=id+desc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=b1403b0ee810ff9be1f4ab1d81888e9a&action=position&posid=32&order=id+desc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'32','order'=>'id desc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=8f2d4240bc8bb12df3afb4ef1ce92e68&action=position&posid=33&order=id+desc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=8f2d4240bc8bb12df3afb4ef1ce92e68&action=position&posid=33&order=id+desc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'33','order'=>'id desc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=03c2121a21146189d5899ee31b7bc995&action=position&posid=76&order=id+desc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=03c2121a21146189d5899ee31b7bc995&action=position&posid=76&order=id+desc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'76','order'=>'id desc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=a7c8f84531e7603ae77c70347938704d&action=position&posid=34&order=id+desc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=a7c8f84531e7603ae77c70347938704d&action=position&posid=34&order=id+desc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'34','order'=>'id desc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=fb9696f4ee4bafc55cf59ba283efee74&action=position&posid=35&order=id+desc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=fb9696f4ee4bafc55cf59ba283efee74&action=position&posid=35&order=id+desc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'35','order'=>'id desc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
</div>
</div>
<!-- 左侧国内 end-->
<!-- 右侧国际 -->
<div class="cookingGeologyRight cg-wrap right J_TWidget " data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [1210], 'circular': true, 'activeTriggerCls':'curr','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable'}" >
<div class="cg-w-tab">
<div class="cg-w-t-item switchable-nav"> <?php $result=query('SELECT * FROM jae_weblink WHERE typeid=31 ORDER BY listorder,id ASC LIMIT 7,1 ');
foreach ($result as $v) {
?>
<a class="fore1 ui-switchable-item curr" href="<?php echo $v['link'];?>" target="_blank" style="cursor:pointer;">
<div class="cg-w-t-label" style="left: -13px; top: -50px; "></div> <b></b>
<span><?php echo position(29) ?></span>
</a>
<?php }
?>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=31 ORDER BY listorder,id ASC LIMIT 8,1 ');
foreach ($result as $v) {
?>
<a class="fore2 ui-switchable-item" href="<?php echo $v['link'];?>" target="_blank" style="cursor:pointer;">
<div class="cg-w-t-label" style="left: -13px; top: -50px; "></div> <b></b>
<span><?php echo position(77) ?></span>
</a>
<?php }
?>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=31 ORDER BY listorder,id ASC LIMIT 9,1 ');
foreach ($result as $v) {
?>
<a class="fore3 ui-switchable-item" href="<?php echo $v['link'];?>" target="_blank" style="cursor:pointer;">
<div class="cg-w-t-label" style="left: -13px; top: -50px; "></div> <b></b>
<span><?php echo position(41) ?></span>
</a>
<?php }
?>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=31 ORDER BY listorder,id ASC LIMIT 10,1 ');
foreach ($result as $v) {
?>
<a class="fore4 ui-switchable-item" href="<?php echo $v['link'];?>" target="_blank" style="cursor:pointer;">
<div class="cg-w-t-label" style="left: -13px; top: -50px; "></div> <b></b>
<span ><?php echo position(36) ?></span>
</a>
<?php }
?>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=31 ORDER BY listorder,id ASC LIMIT 11,1 ');
foreach ($result as $v) {
?>
<a class="fore5 ui-switchable-item" href="<?php echo $v['link'];?>" target="_blank" style="cursor:pointer;">
<div class="cg-w-t-label" style="left: -13px; top: -50px; "></div> <b></b>
<span><?php echo position(37) ?></span>
</a>
<?php }
?>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=31 ORDER BY listorder,id ASC LIMIT 12,1 ');
foreach ($result as $v) {
?>
<a class="fore6 ui-switchable-item" href="<?php echo $v['link'];?>" target="_blank" style="cursor:pointer;">
<div class="cg-w-t-label" style="left: -13px; top: -50px; "></div> <b></b>
<span><?php echo position(38) ?></span>
</a>
<?php }
?>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=31 ORDER BY listorder,id ASC LIMIT 13,1 ');
foreach ($result as $v) {
?>
<a class="fore8 ui-switchable-item" href="<?php echo $v['link'];?>" target="_blank" style="cursor:pointer;">
<div class="cg-w-t-label" style="left: -13px; top: -50px; "></div> <b></b>
<span><?php echo position(39) ?></span>
</a>
<?php }
?> </div>
</div>
<div class="cg-w-con switchable-content" style="position: relative; ">
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=e1ef4f3c7963694c6c0a69c1787c8e74&action=position&posid=29&order=id+desc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=e1ef4f3c7963694c6c0a69c1787c8e74&action=position&posid=29&order=id+desc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'29','order'=>'id desc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=8989e9cba0694c8c849f63d3d2ca1a0b&action=position&posid=77&order=id+desc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=8989e9cba0694c8c849f63d3d2ca1a0b&action=position&posid=77&order=id+desc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'77','order'=>'id desc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=e4746bfb14b03e8e3eb01af66c6d1660&action=position&posid=41&order=id+desc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=e4746bfb14b03e8e3eb01af66c6d1660&action=position&posid=41&order=id+desc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'41','order'=>'id desc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=d4ce5607a4b02a6f3b415178f82a596e&action=position&posid=36&order=id+desc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=d4ce5607a4b02a6f3b415178f82a596e&action=position&posid=36&order=id+desc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'36','order'=>'id desc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=572ca3beee90054255803e3354bb100f&action=position&posid=37&order=id+desc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=572ca3beee90054255803e3354bb100f&action=position&posid=37&order=id+desc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'37','order'=>'id desc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=34ef9c26ce90e32925a5d75dad5eb17c&action=position&posid=38&order=id+desc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=34ef9c26ce90e32925a5d75dad5eb17c&action=position&posid=38&order=id+desc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'38','order'=>'id desc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
<div> <ul class="clearfix item ui-switchable-panel selected" style="position: absolute; z-index: 1; opacity: 1; ">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=2cf366bdfb88100c973907a180978483&action=position&posid=39&order=id+desc&num=4\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=2cf366bdfb88100c973907a180978483&action=position&posid=39&order=id+desc&num=4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'39','order'=>'id desc','limit'=>'4',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?> <li>
<div class="p-img">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank">
<img class="isicon" src="<?php if($r['isicon']==1) {echo $r['icon_url']} ?>" ><img class="err-product pimg816303" width="100" height="100" data-img="1" data-lazy-img="done" alt="<?php echo $r['title']?>" data-ks-lazyload="<?php echo $r['thumb']?>">
</a>
</div>
<div class="p-name">
<a href="<?php echo $r['url']?>" title="<?php echo $r['title']?>" target="_blank"><?php echo $r['title']?></a>
</div>
<div class="p-price" sku="816303">
<strong>¥<?php echo $r['coupon_price']?></strong>
</div>
<div class="p-ext">
<a class="btn-s addCart" href="<?php echo $r['url'];?>" title="<?php echo $r['title'];?>" target="_blank">立即购买</a>
</div>
</li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul></div>
</div>
</div>
</div>
</div>
<!-- 美食地理 end -->
<div class="clr" style="clear:both;"></div>
</div>
<!--美食地理END-->
<!--特色品类-->
<div class="blank"> </div>
<div class="wrap tese">
<div class="title"> <img src="http://img01.taobaocdn.com/imgextra/i1/2063404741/TB2EpnRXVXXXXbOXXXXXXXXXXXX-2063404741.png" /></div>
<div class="main">
<div class="main_t">
<div class="main_b">
<?php echo block(5);?>
<?php echo block(6);?>
<div class="clear"> </div>
</div>
</div>
</div>
</div>
<!--特色品类END-->
<!--1楼-->
<div class="blank"> </div>
<div class="louceng wrap">
<div class="title"> <img src="http://img03.taobaocdn.com/imgextra/i3/2063404741/TB2EufHXVXXXXbxXXXXXXXXXXXX-2063404741.png" style="float:none;margin:0px;" /></div>
<div class="main">
<div class="main_t">
<div class="main_b">
<?php echo block(7);?>
<div class="right">
<div class="list">
<ul>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=1af57eb5914ad61ad4b375ab2b4dc191&action=position&posid=7&order=id+desc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=1af57eb5914ad61ad4b375ab2b4dc191&action=position&posid=7&order=id+desc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'7','order'=>'id desc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li> <a href="<?php echo $r['url']?>" target="_blank"><img height="200" src="<?php echo $r['thumb']?>" style="float:none;margin:0px;" width="200" /><br />
<span class="txt"><?php echo $r['title']?></span>
<span class="jg">¥<?php echo round($r['coupon_price'],1);?></span><span class="yj">¥<?php echo round($r['price'],1);?></span> <span class="gm">立即购买</span></a></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
</div>
<div class="clear"> </div>
</div>
</div>
</div>
</div>
<!--1楼END-->
<!--2楼-->
<div class="blank"> </div>
<div class="louceng wrap">
<div class="title"> <img src="http://img04.taobaocdn.com/imgextra/i4/2063404741/TB2SdfIXVXXXXbwXXXXXXXXXXXX-2063404741.png" style="float:none;margin:0px;" /></div>
<div class="main">
<div class="main_t">
<div class="main_b">
<?php echo block(8);?>
<div class="right">
<div class="list">
<ul>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=017d8297d818fa426e675258d3f8fdba&action=position&posid=8&order=id+desc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=017d8297d818fa426e675258d3f8fdba&action=position&posid=8&order=id+desc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'8','order'=>'id desc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li> <a href="<?php echo $r['url']?>" target="_blank"><img height="200" src="<?php echo $r['thumb']?>" style="float:none;margin:0px;" width="200" /><br />
<span class="txt"><?php echo $r['title']?></span>
<span class="jg">¥<?php echo round($r['coupon_price'],1);?></span><span class="yj">¥<?php echo round($r['price'],1);?></span> <span class="gm">立即购买</span></a></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
</div>
<div class="clear"> </div>
</div>
</div>
</div>
</div>
<!--2楼END-->
<!--3楼-->
<div class="blank"> </div>
<div class="louceng wrap">
<div class="title"> <img src="http://img02.taobaocdn.com/imgextra/i2/2063404741/TB2JA.bXVXXXXbvXXXXXXXXXXXX-2063404741.jpg" style="float:none;margin:0px;" /></div>
<div class="main">
<div class="main_t">
<div class="main_b">
<?php echo block(34);?>
<div class="right">
<div class="list">
<ul>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=7223efa3848c7d8b42f703e32e94d4e3&action=position&posid=75&order=id+desc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=7223efa3848c7d8b42f703e32e94d4e3&action=position&posid=75&order=id+desc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'75','order'=>'id desc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li> <a href="<?php echo $r['url']?>" target="_blank"><img height="200" src="<?php echo $r['thumb']?>" style="float:none;margin:0px;" width="200" /><br />
<span class="txt"><?php echo $r['title']?></span>
<span class="jg">¥<?php echo round($r['coupon_price'],1);?></span><span class="yj">¥<?php echo round($r['price'],1);?></span> <span class="gm">立即购买</span></a></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
</div>
<div class="clear"> </div>
</div>
</div>
</div>
</div>
<!--3楼END-->
<!--4楼-->
<div class="blank"> </div>
<div class="louceng wrap">
<div class="title"> <img src="http://img04.taobaocdn.com/imgextra/i4/2063404741/TB2AkHJXVXXXXXbXXXXXXXXXXXX-2063404741.png" style="float:none;margin:0px;" /></div>
<div class="main">
<div class="main_t">
<div class="main_b">
<?php echo block(9);?>
<div class="right">
<div class="list">
<ul>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=30b250eed86511d078a3ab7e816d14cd&action=position&posid=9&order=id+desc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=30b250eed86511d078a3ab7e816d14cd&action=position&posid=9&order=id+desc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'9','order'=>'id desc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li> <a href="<?php echo $r['url']?>" target="_blank"><img height="200" src="<?php echo $r['thumb']?>" style="float:none;margin:0px;" width="200" /><br />
<span class="txt"><?php echo $r['title']?></span>
<span class="jg">¥<?php echo round($r['coupon_price'],1);?></span><span class="yj">¥<?php echo round($r['price'],1);?></span> <span class="gm">立即购买</span></a></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
</div>
<div class="clear"> </div>
</div>
</div>
</div>
</div>
<!--4楼END-->
<!--5楼-->
<div class="blank"> </div>
<div class="louceng wrap">
<div class="title"> <img src="http://img04.taobaocdn.com/imgextra/i4/2063404741/TB2zkPHXVXXXXbvXXXXXXXXXXXX-2063404741.png" style="float:none;margin:0px;" /></div>
<div class="main">
<div class="main_t">
<div class="main_b">
<?php echo block(10);?>
<div class="right">
<div class="list">
<ul>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=b11cb678f337c0d2954966dcc86969b5&action=position&posid=10&order=id+desc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=b11cb678f337c0d2954966dcc86969b5&action=position&posid=10&order=id+desc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'10','order'=>'id desc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li> <a href="<?php echo $r['url']?>" target="_blank"><img height="200" src="<?php echo $r['thumb']?>" style="float:none;margin:0px;" width="200" /><br />
<span class="txt"><?php echo $r['title']?></span>
<span class="jg">¥<?php echo round($r['coupon_price'],1);?></span><span class="yj">¥<?php echo round($r['price'],1);?></span> <span class="gm">立即购买</span></a></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
</div>
<div class="clear"> </div>
</div>
</div>
</div>
</div>
<!--5楼END-->
<!--6楼-->
<div class="blank"> </div>
<div class="louceng wrap">
<div class="title"> <img src="http://img03.taobaocdn.com/imgextra/i3/2063404741/TB28VjHXVXXXXbDXXXXXXXXXXXX-2063404741.png" style="float:none;margin:0px;" /></div>
<div class="main">
<div class="main_t">
<div class="main_b">
<?php echo block(11);?>
<div class="right">
<div class="list">
<ul>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=5c8ecc8b8f301907759f9d671efb901b&action=position&posid=14&order=id+desc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=5c8ecc8b8f301907759f9d671efb901b&action=position&posid=14&order=id+desc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'14','order'=>'id desc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<li> <a href="<?php echo $r['url']?>" target="_blank"><img height="200" src="<?php echo $r['thumb']?>" style="float:none;margin:0px;" width="200" /><br />
<span class="txt"><?php echo $r['title']?></span>
<span class="jg">¥<?php echo round($r['coupon_price'],1);?></span><span class="yj">¥<?php echo round($r['price'],1);?></span> <span class="gm">立即购买</span></a></li>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
</div>
<div class="clear"> </div>
</div>
</div>
</div>
</div>
<!--6楼END-->
<!--特色旅游-->
<div class="blank"> </div>
<div class="louceng wrap">
<div class="title"> <img src="http://img03.taobaocdn.com/imgextra/i3/2063404741/TB2oorEXVXXXXcUXXXXXXXXXXXX-2063404741.png" style="float:none;margin:0px;" /></div>
<div class="main">
<div class="main_t">
<div class="main_b">
<div class="lvyou">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=22 ORDER BY listorder,id ASC LIMIT 0,2 ');
foreach ($result as $v) { if(!empty($v['picture'])){
?><div class="ly1 ly2 item"><a target="_blank" href="<?php echo $v['link'];?>"><img data-ks-lazyload="<?php echo $v['picture'];?>"></a></div>
<?php } }
?>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=22 ORDER BY listorder,id ASC LIMIT 2,3 ');
foreach ($result as $v) { if(!empty($v['picture'])){
?><div class="ly3 ly4 ly5 item"><a target="_blank" href="<?php echo $v['link'];?>"><img data-ks-lazyload="<?php echo $v['picture'];?>"></a></div>
<?php } }
?>
<div class="clear"></div></div>
</div>
</div>
</div>
</div>
<div class="blank10"></div>
<!--特色旅游END-->
<!--banner----->
<div class="wrap">
<div class="banad2">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=21 ORDER BY listorder,id ASC LIMIT 3,3 ');
foreach ($result as $v) { if(!empty($v['picture'])){
?><div class="blank10"></div><a target="_blank" href="<?php echo $v['link'];?>"><img width="1210" src="<?php echo $v['picture'];?>"></a><div style="height:5px; clear:both;"></div>
<?php } }
?>
</div>
</div>
<!--banner end----->
<!--友情链接-->
<div class="blank"></div>
<div class="wrap">
<div class="jh">
<?php $result=query('SELECT * FROM jae_link WHERE typeid=0 AND passed=1 ORDER BY listorder ASC LIMIT 0,50 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img data-ks-lazyload="<?php echo $v['logo'];?>"></a>
<?php }?>
<div class="clear"></div>
</div>
</div>
<!--友情链接END-->
</div>
<!--版权-->
<?php include template('content','foot');?>
<!--版权END--><file_sep>/jae/modules/admin/templates/setting.tpl.php
<?php include $this->admin_tpl('head');
?>
<form name="myform" id="myform" action="/admin.php?m=admin&c=setting&a=init" method="post">
<table width="100%" class="table_form contentWrap">
<tbody><tr>
<th width="200">站点地址</th>
<td><input style="width: 300px;" type="text" name="info[siteUrl]" id="language" value="<?PHP echo($siteUrl)?>" class="input-text"><div id="languageTip" class="onShow"></div> </td>
</tr>
<tr>
<th> 客服旺旺</th>
<td><input value="<?PHP echo($wangwang)?>" style="width: 300px;" type="text" name="info[wangwang]" id="language" class="input-text"><div id="languageTip" class="onShow"></div></td>
</tr>
<tr>
<th>帮派地址</th>
<td><input value="<?PHP echo($bangpai)?>" style="width: 300px;" type="text" name="info[bangpai]" id="name" class="input-text"><div id="nameTip" class="onShow"></div></td>
</tr>
<tr>
<th>APPKEY</th>
<td><input value="<?PHP echo($appkey)?>" style="width: 300px;" type="text" name="info[appkey]" id="m" class="input-text"><div id="mTip" class="onShow"></div></td>
</tr>
<tr>
<th>SECRETKEY</th>
<td><input value="<?PHP echo($secretKey)?>" style="width: 300px;" type="text" name="info[secretKey]" id="c" class="input-text"><div id="cTip" class="onShow"></div></td>
</tr>
<tr>
<th>完整pid</th>
<td><input value="<?PHP echo($pid)?>" style="width: 300px;" type="text" name="info[pid]" id="a" class="input-text"> </td>
</tr>
<tr>
<th>logo地址</th>
<td><input value="<?PHP echo($logo)?>" style="width: 300px;" type="text" name="info[logo]" class="input-text"></td>
</tr>
<tr>
<th>sessionkey</th>
<td><input value="<?PHP echo($sessionkey)?>" style="width: 300px;" type="text" name="info[sessionkey]" class="input-text"></td>
</tr>
</tbody></table>
<!--table_form_off-->
<div class="btns"><input type="submit" id="dosubmit" class="button" name="dosubmit" value="提交"></div>
</form>
<div class="pages"><?php echo $pages;?></div>
<?php include $this->admin_tpl('foot');?><file_sep>/jae/modules/upgrade/templates/upgrade_index.tpl.php
<?php include $this->admin_tpl('head','admin');
?>
<div class="pad-lr-10">
<div class="table-list">
<div class="explain-col">
<?php echo L('upgrade_notice');?>
</div>
<div class="bk15"></div>
<form name="myform" action="" method="post" id="myform">
<input type="hidden" name="s" value="1" />
<input type="hidden" name="cover" value="<?php echo $_GET['cover']?>" />
<input name="m" value="upgrade" type="hidden" />
<input name="c" value="index" type="hidden" />
<input name="a" value="init" type="hidden" />
<table width="100%" cellspacing="0">
<thead>
<tr class="thead">
<th align="left" width="300"><?php echo L('currentversion')?><?php if(empty($pathlist)) {?><?php echo L('lastversion')?><?php }?></th>
<th align="left"><?php echo L('updatetime')?></th>
</tr>
</thead>
<tbody>
<tr>
<td align="left"><?php echo $siteinfo['version'];?></td>
<td align="left"><?php echo $siteinfo['date'];?></td>
</tr>
</tbody>
</table>
<?php if(!empty($pathlist)) {?>
<div class="bk15"></div>
<table width="100%" cellspacing="0" class="table-list" >
<thead>
<tr class="thead">
<th align="left" width="300"><?php echo L('updatelist')?></th>
<th align="left"><?php echo L('updatetime')?></th>
</tr>
</thead>
<tbody>
<?php foreach($pathlist as $v) { ?>
<tr>
<td><?php echo $v;?></td>
<td><?php echo substr($v, 0, 8);?></td>
</tr>
<?php }?>
</tbody>
</table>
<div class="bk15"></div>
<div class="btns"> <input name="dosubmit" type="submit" id="dosubmit" value="<?php echo L('begin_upgrade')?>" class="button"></div>
<?php }?>
</form>
</div>
</div>
<?php include $this->admin_tpl('foot','admin');?><file_sep>/caches/caches_commons/caches_data/sitelist.cache.php
<?php
return array (
1 =>
array (
'siteid' => '1',
0 => '1',
'name' => '特色中国湖北馆',
1 => '特色中国湖北馆',
'dirname' => '',
2 => '',
'domain' => 'http://hubei.china.taobao.com/',
3 => 'http://hubei.china.taobao.com/',
'site_title' => '特色中国湖北馆',
4 => '特色中国湖北馆',
'appkey' => '21689808',
5 => '21689808',
'secretkey' => '40e7b98fce138a560854d453bc4a1544',
6 => '40e7b98fce138a560854d453bc4a1544',
'keywords' => '湖北馆',
7 => '湖北馆',
'description' => '特色中国湖北馆',
8 => '特色中国湖北馆',
'release_point' => '',
9 => '',
'default_style' => 'hubei',
10 => 'hubei',
'template' => 'hubei',
11 => 'hubei',
'setting' => 'array (
\'head_logo\' => \'http://img04.taobaocdn.com/imgextra/i4/1089118323/TB2xquxapXXXXXFXXXXXXXXXXXX-1089118323.png\',
\'foot_logo\' => \'http://img04.taobaocdn.com/imgextra/i4/1089118323/TB2xquxapXXXXXFXXXXXXXXXXXX-1089118323.png\',
)',
12 => 'array (
\'head_logo\' => \'http://img04.taobaocdn.com/imgextra/i4/1089118323/TB2xquxapXXXXXFXXXXXXXXXXXX-1089118323.png\',
\'foot_logo\' => \'http://img04.taobaocdn.com/imgextra/i4/1089118323/TB2xquxapXXXXXFXXXXXXXXXXXX-1089118323.png\',
)',
'version' => '144',
13 => '144',
'date' => '20140718',
14 => '20140718',
'uuid' => '0',
15 => '0',
'url' => 'http://hubei.china.taobao.com/',
),
2 =>
array (
'siteid' => '2',
0 => '2',
'name' => '特色中国内蒙古馆',
1 => '特色中国内蒙古馆',
'dirname' => '',
2 => '',
'domain' => 'http://neimenggu.china.taobao.com/',
3 => 'http://neimenggu.china.taobao.com/',
'site_title' => '特色中国内蒙古馆',
4 => '特色中国内蒙古馆',
'appkey' => '21733132',
5 => '21733132',
'secretkey' => '<KEY>',
6 => '<KEY>',
'keywords' => '内蒙古馆',
7 => '内蒙古馆',
'description' => '特色中国内蒙古馆',
8 => '特色中国内蒙古馆',
'release_point' => '',
9 => '',
'default_style' => 'neimeng2',
10 => 'neimeng2',
'template' => 'neimeng2',
11 => 'neimeng2',
'setting' => 'array (
\'head_logo\' => \'http://img04.taobaocdn.com/imgextra/i4/1863579612/TB24lM2aXXXXXXKXXXXXXXXXXXX-1863579612.png\',
\'foot_logo\' => \'http://img04.taobaocdn.com/imgextra/i4/1863579612/TB24lM2aXXXXXXKXXXXXXXXXXXX-1863579612.png\',
)',
12 => 'array (
\'head_logo\' => \'http://img04.taobaocdn.com/imgextra/i4/1863579612/TB24lM2aXXXXXXKXXXXXXXXXXXX-1863579612.png\',
\'foot_logo\' => \'http://img04.taobaocdn.com/imgextra/i4/1863579612/TB24lM2aXXXXXXKXXXXXXXXXXXX-1863579612.png\',
)',
'version' => '144',
13 => '144',
'date' => '20140718',
14 => '20140718',
'uuid' => '0',
15 => '0',
'url' => 'http://neimenggu.china.taobao.com/',
),
3 =>
array (
'siteid' => '3',
0 => '3',
'name' => '特色中国武夷山馆',
1 => '特色中国武夷山馆',
'dirname' => '',
2 => '',
'domain' => 'http://wuyishan.china.taobao.com/',
3 => 'http://wuyishan.china.taobao.com/',
'site_title' => '特色中国武夷山馆',
4 => '特色中国武夷山馆',
'appkey' => '21772477',
5 => '21772477',
'secretkey' => '22f5677315e0f9f3a1e773d6b853fefb',
6 => '22f5677315e0f9f3a1e773d6b853fefb',
'keywords' => '特色中国武夷山馆',
7 => '特色中国武夷山馆',
'description' => '特色中国武夷山馆',
8 => '特色中国武夷山馆',
'release_point' => '',
9 => '',
'default_style' => 'wuyishan',
10 => 'wuyishan',
'template' => 'wuyishan',
11 => 'wuyishan',
'setting' => 'array ( head_logo => http://img03.taobaocdn.com/imgextra/i3/12004038721590667/T2Nf9.XMpXXXXXXXXX_!!1658162004-2-cs-!CS.png, foot_logo => http://img03.taobaocdn.com/imgextra/i3/12004038721590667/T2Nf9.XMpXXXXXXXXX_!!1658162004-2-cs-!CS.png,)',
12 => 'array ( head_logo => http://img03.taobaocdn.com/imgextra/i3/12004038721590667/T2Nf9.XMpXXXXXXXXX_!!1658162004-2-cs-!CS.png, foot_logo => http://img03.taobaocdn.com/imgextra/i3/12004038721590667/T2Nf9.XMpXXXXXXXXX_!!1658162004-2-cs-!CS.png,)',
'version' => '144',
13 => '144',
'date' => '20140718',
14 => '20140718',
'uuid' => '0',
15 => '0',
'url' => 'http://wuyishan.china.taobao.com/',
),
4 =>
array (
'siteid' => '4',
0 => '4',
'name' => '特色中国甘肃馆',
1 => '特色中国甘肃馆',
'dirname' => '',
2 => '',
'domain' => 'http://gansu.china.taobao.com/',
3 => 'http://gansu.china.taobao.com/',
'site_title' => '特色中国甘肃馆',
4 => '特色中国甘肃馆',
'appkey' => '21805589',
5 => '21805589',
'secretkey' => '<KEY>',
6 => '<KEY>',
'keywords' => '特色中国甘肃馆',
7 => '特色中国甘肃馆',
'description' => '特色中国甘肃馆',
8 => '特色中国甘肃馆',
'release_point' => '',
9 => '',
'default_style' => 'gansu',
10 => 'gansu',
'template' => 'gansu',
11 => 'gansu',
'setting' => 'array (
\'head_logo\' => \'/statics/images/logo.png\',
\'foot_logo\' => \'/statics/images/logo.png\',
)',
12 => 'array (
\'head_logo\' => \'/statics/images/logo.png\',
\'foot_logo\' => \'/statics/images/logo.png\',
)',
'version' => '144',
13 => '144',
'date' => '20140718',
14 => '20140718',
'uuid' => '0',
15 => '0',
'url' => 'http://gansu.china.taobao.com/',
),
6 =>
array (
'siteid' => '6',
0 => '6',
'name' => '特色中国辽宁馆',
1 => '特色中国辽宁馆',
'dirname' => '',
2 => '',
'domain' => 'http://liaoning.china.taobao.com/',
3 => 'http://liaoning.china.taobao.com/',
'site_title' => '特色中国辽宁馆',
4 => '特色中国辽宁馆',
'appkey' => '23014028',
5 => '23014028',
'secretkey' => '287c303b58a10446c29eab67d3a4679d',
6 => '287c303b58a10446c29eab67d3a4679d',
'keywords' => '特色中国辽宁馆',
7 => '特色中国辽宁馆',
'description' => '特色中国辽宁馆',
8 => '特色中国辽宁馆',
'release_point' => '',
9 => '',
'default_style' => 'liaoning2',
10 => 'liaoning2',
'template' => 'liaoning2',
11 => 'liaoning2',
'setting' => 'array (
\'head_logo\' => \'http://img01.taobaocdn.com/imgextra/i1/2139364924/TB2WXXJaVXXXXX4XXXXXXXXXXXX_!!2139364924.png\',
\'foot_logo\' => \'http://img01.taobaocdn.com/imgextra/i1/2139364924/TB2WXXJaVXXXXX4XXXXXXXXXXXX_!!2139364924.png\',
)',
12 => 'array (
\'head_logo\' => \'http://img01.taobaocdn.com/imgextra/i1/2139364924/TB2WXXJaVXXXXX4XXXXXXXXXXXX_!!2139364924.png\',
\'foot_logo\' => \'http://img01.taobaocdn.com/imgextra/i1/2139364924/TB2WXXJaVXXXXX4XXXXXXXXXXXX_!!2139364924.png\',
)',
'version' => '',
13 => '',
'date' => '',
14 => '',
'uuid' => '1',
15 => '1',
'url' => 'http://liaoning.china.taobao.com/',
),
5 =>
array (
'siteid' => '5',
0 => '5',
'name' => '特色中国潍坊馆',
1 => '特色中国潍坊馆',
'dirname' => '',
2 => '',
'domain' => 'http://weifang.china.taobao.com/',
3 => 'http://weifang.china.taobao.com/',
'site_title' => '特色中国潍坊馆',
4 => '特色中国潍坊馆',
'appkey' => '21799848',
5 => '21799848',
'secretkey' => '435eebee3e0518397dff05b43daa4aba',
6 => '435eebee3e0518397dff05b43daa4aba',
'keywords' => '特色中国潍坊馆',
7 => '特色中国潍坊馆',
'description' => '特色中国潍坊馆',
8 => '特色中国潍坊馆',
'release_point' => '',
9 => '',
'default_style' => 'weifang',
10 => 'weifang',
'template' => 'weifang',
11 => 'weifang',
'setting' => 'array (
\'head_logo\' => \'http://img04.taobaocdn.com/imgextra/i4/2063414185/T2ZFXJX_FXXXXXXXXX_!!2063414185.png\',
\'foot_logo\' => \'http://img04.taobaocdn.com/imgextra/i4/2063414185/T2ZFXJX_FXXXXXXXXX_!!2063414185.png\',
)',
12 => 'array (
\'head_logo\' => \'http://img04.taobaocdn.com/imgextra/i4/2063414185/T2ZFXJX_FXXXXXXXXX_!!2063414185.png\',
\'foot_logo\' => \'http://img04.taobaocdn.com/imgextra/i4/2063414185/T2ZFXJX_FXXXXXXXXX_!!2063414185.png\',
)',
'version' => '144',
13 => '144',
'date' => '20140718',
14 => '20140718',
'uuid' => '0',
15 => '0',
'url' => 'http://weifang.china.taobao.com/',
),
);
?><file_sep>/caches/caches_template/default/member/goods_manage.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head');?>
<link href="/statics/css/apply.css" rel="stylesheet" type="text/css" />
<div class="blank"></div>
<div class="wrap">
<dl class="ui-tab clearfix" id="">
<dt>商品管理</dt>
<dd data-type="all" class="j_nativeHistory all <?php if(ROUTE_A=='goods_apply') echo "select"?> "><a href="/index.php?m=member&c=index&a=goods_apply&manage=all">活动报名</a></dd>
<dd data-type="all" class="j_nativeHistory all <?php if($manage=='pass') echo "select"?> " ><a href="/index.php?m=member&c=index&a=goods_manage&manage=pass">已通过</a></dd>
<dd data-type="income" class="j_nativeHistory income <?php if($manage=='check') echo "select"?>" ><a href="/index.php?m=member&c=index&a=goods_manage&manage=check ">审核中</a></dd>
<dd data-type="used" class="j_nativeHistory used <?php if($manage=='refuse') echo "select"?>" ><a href="/index.php?m=member&c=index&a=goods_manage&manage=refuse">被拒绝</a></dd>
<!-- <dd data-type="expired" class="j_nativeHistory expired <?php if(ROUTE_A=='apply_task') echo "select"?>" ><a href="/index.php?m=member&c=index&a=apply_task">报名条件</a></dd> -->
<!-- <dd data-type="freezed" class="j_nativeHistory freezed" data-template="/point/detail/freezed">冻结积分</dd>-->
</dl>
<div class="border">
<div class="pd20">
<div class="content">
<div class="product-list clearfix" data-spm="9">
<!-- pc begin -->
<?php foreach($data as $v){?>
<div class="product ">
<a class="title clearfix" href="<?php echo $v['detail_url']?>" target="_blank" title="<?php echo $v['title']?>" data-spm="d1">
<img alt="<?php echo $v['title']?>" src="<?php echo $v['pic_url']?>">
<?php if ($v['freight_payer']=='seller') {?><span class="benefit">包邮</span><?php }?>
<?php echo $v['title']?>
</a>
<div class="layer clearfix">
<a class="info clearfix" href="//detail.tmall.com/item.htm?id=25891328996" target="_blank" title="<?php echo $v['title']?>" data-spm="d1">
<div class="point">
<div class="num"><?php echo $v['coupon_price']?></div>
</div>
<div class="limit"><?php echo $v['num']?>件</div>
<div class="old-price">
原价 ¥ <s><?php echo $v['price']?></s>
</div>
<div class="j-sell-status status sold-out" data-id="25891328996">立即购买</div>
</a>
<a class="shop-link" href="<?php echo $v['shop_url']?>" target="_blank" data-spm="d1">进入店铺</a>
</div>
<div class="edit"><a href="/index.php?m=member&c=index&a=edit&id=<?php echo $v['id']?>">编辑</a><a href="/index.php?m=member&c=index&a=delete&id=<?php echo $v['id']?>">删除</a><br><?php if($manage=='refuse') { ?> <font color="#f00">拒绝理由:
<?php echo $v['refuse']?></font><?php }?>
</div>
</div>
<?php }?>
<!-- pc end -->
</div>
</div>
</div>
</div>
<div class="clear"></div>
</div>
<file_sep>/jae/modules/exchange/templates/exchange_edit.tpl.php
<?php include $this->admin_tpl('head','admin'); ?>
<font color="red"><?php echo $message;?></font>
<form name="form2" method="post" action="/admin.php?m=exchange&c=exchange&a=edit">
<table class="table_form" cellpadding="0" cellspacing="0" border="0">
<tr>
<th width="140">*商品链接:</th>
<td><input class="input-text" type="text" name="info[detail_url]" size="50" value="<?php echo $detail_url; ?>"></td>
</tr>
<tr>
<th width="140">*店铺链接:</th>
<td><input class="input-text" type="text" name="info[shop_url]" size="50" value="<?php echo $shop_url; ?>"></td>
</tr>
<tr>
<th>*商品标题:</th>
<td><input class="input-text" type="text" name="info[title]" size="50" value="<?php echo $title; ?>"></td> <td rowspan="12" valign="top"> <a target="_blank" href="<?php echo $detail_url; ?>"><img border="0" src="<?php echo $pic_url; ?>" width="200" height="200" /><br>商品图片预览(点击跳到详情页面)</a> </td>
</tr>
<tr>
<th>*商品图片:</th>
<td><input class="input-text" type="text" name="info[pic_url]" size="50" value="<?php echo $pic_url; ?>"></td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<th>*上线时间段:</th>
<td>
<ul>
<li>
<label class="tit" for="J_DepDate">开始时间:</label>
<input name="info[begin_time]" class="kg_datePicker input-text" type="text" value="<?php echo date('Y-m-d H:i:s', $begin_time); ?>"/>
</li>
<li>
<label class="tit" for="J_RetDate">结束时间:</label>
<input name="info[end_time]" class="kg_datePicker input-text" type="text"
value="<?php echo date('Y-m-d H:i:s', $end_time); ?>"/>
</li>
</ul>
</td>
</tr>
<tr>
<th>*包邮:</th>
<td>
<select name="info[freight_payer]">
<option<?php if($freight_payer=='seller'){?> selected="selected"<?php }; ?> value="seller">是</option>
<option<?php if($freight_payer=='buyer'){?> selected="selected"<?php }; ?> value="buyer">否</option>
</select>
</tr>
<tr>
<th>*商家昵称:</th>
<td><input class="input-text" type="text" name="info[nick]" size="50" value="<?php echo $nick; ?>"></td>
</tr>
<tr>
<th>*商品原价:</th>
<td><input class="input-text" type="text" name="info[price]" size="50" value="<?php echo $price; ?>"></td>
</tr>
<tr>
<th>*商品现价:</th>
<td><input class="input-text" type="text" name="info[coupon_price]" value="<?php echo $coupon_price; ?>" /></td>
</tr>
<tr>
<th>*兑换积分:</th>
<td><input class="input-text" type="text" name="info[point]" value="<?php echo $point; ?>" /></td>
</tr>
<tr>
<th>*商品数量:</th>
<td><input class="input-text" type="text" name="info[num]" size="50" value="<?php echo $num; ?>"></td>
</tr>
<tr>
<th>卖点描述:</th>
<td>
<textarea style="width:350px;height:100px" name="info[description]"><?php echo $description; ?></textarea>
</td>
</tr>
</table>
<div class="btns"><input name="id" type="hidden" value="<?php echo $id?>"><input type="submit" id="dosubmit" class="button" name="dosubmit" value="提交"></div>
</form>
<?php include $this->admin_tpl('foot','admin');?><file_sep>/jae/modules/apply/goods.php
<?php
defined('IN_JAE') or exit('No permission resources.');defined('IN_ADMIN') or exit('No permission resources.');
jae_base::load_app_class('admin', 'admin', 0);
class goods extends admin
{
function __construct()
{
parent::__construct();
$this->db = jae_base::load_sys_class('mysql');
$this->table = 'jae_goods';
$this->menuid = 19;
}
function init()
{
$where= "status=0";
$searchCategoryId=-1;
$searchPindaoId=-1;
$searchPromoteId=-1;
$dopost = isset($_POST["dopost"]) ? $_POST["dopost"] : '';
$page = $_GET['page'];
$data = $this->db->listinfo("*", $this->table, $where, "id DESC", $page, 10);
$categoryArr = rGetCategoryArr();
$promotePositionArr = rGetPromotePositionArr('goods');
$pindaoArr = rGetPindaoArr();
$pages = $this->db->pages;
include $this->admin_tpl('goods_list','apply');
}
function search()
{
$where= " status = 0 ";
$searchCategoryId=-1;
$searchPindaoId=-1;
$searchPromoteId=-1;
$dopost = isset($_GET["dopost"]) ? $_GET["dopost"] : '';
if ($dopost=="search")
{
$searchWord=$_GET['searchWord'];
$searchCategoryId=$_GET['searchCategoryId'];
$searchPindaoId=$_GET['searchPindaoId'][0];
$searchPromoteId=$_GET['searchPromoteId'][0];
if(!empty($searchWord))$where .= " AND `title` LIKE '%$searchWord%' OR `num_iid` = '$searchWord' OR `nick` = '$searchWord'";
if($searchCategoryId>=0)$where .=" AND category_id =".$searchCategoryId;
if($searchPindaoId>=0)$where .=" AND pindao_id =".$searchPindaoId;
if($searchPromoteId>=0)$where .=" AND promote_id =".$searchPromoteId;
}
$data = $this->db->listinfo("*", $this->table, $where, "id DESC", $page, 110);
$categoryArr = rGetCategoryArr();
$promotePositionArr = rGetPromotePositionArr('goods');
$pindaoArr = rGetPindaoArr();
$pages = $this->db->pages;
include $this->admin_tpl('goods_list','apply');
}
function add()
{
//获取站点配置信息
$siteinfo=siteinfo(SITEID);
$appkey =$siteinfo['appkey'];
$secret =$siteinfo['secretkey'];
jae_base::load_top('topclient');
jae_base::load_top('ItemGetRequest');
$promotePositionArr = rGetPromotePositionArr('goods');
$categoryArr = rGetCategoryArr();
$pindaoArr = rGetPindaoArr();
$dopost = isset($_POST['dopost']) ? $_POST['dopost'] : '';
$numIid = isset($_POST['numIid']) ? trim($_POST['numIid']) : ''; //提交过来的num_iid
$createMessage = '';
if ($dopost == 'caiji') {
if ($numIid != "" && rRuleNum($numIid)) {
$c = new TopClient;
$c->appkey = $appkey;
$c->secretKey = $secret;
$req = new ItemGetRequest;
$req->setFields("detail_url,num_iid,title,nick,type,cid,seller_cids,props,input_pids,input_str,desc,pic_url,num,valid_thru,list_time,delist_time,stuff_status,location,price,post_fee,express_fee,ems_fee,has_discount,freight_payer,has_invoice,has_warranty,has_showcase,modified,increment,approve_status,postage_id,product_id,auction_point,property_alias,item_img,prop_img,sku,video,outer_id,is_virtual");
$req->setNumIid($numIid);
$resp = $c->execute($req, $sessionKey);
if ($resp->item) {
$detail_url = $resp->item->detail_url; //商品链接
$num_iid = $resp->item->num_iid; //商品ID
$title = $resp->item->title; //商品标题
$nick = $resp->item->nick; //卖家昵称
$pic_url = $resp->item->pic_url; //商品主图
$num = $resp->item->num; //商品数量
$price = $resp->item->price; //商品原价格
$freight_payer = $resp->item->freight_payer; //商品原价格
} else
$message = '不存在这个商品';
//print_r($resp);
} else {
$message = "商品ID【不能为空】并且【必须是数字】。";
}
}
if ($dopost == 'create') {
$categoryId = intval($_POST["categoryId"]);
$num_iid = $_POST["num_iid"];
$num = intval($_POST["num"]);
$detail_url = $_POST["detail_url"];
$title = $_POST["title"];
$pic_url = $_POST["pic_url"];
$create_time = time();
$begin_time = strtotime($_POST["begin_time"]);
$end_time = strtotime($_POST["end_time"]);
$price = $_POST["price"];
$coupon_price = $_POST["coupon_price"];
$freight_payer = $_POST['freight_payer'];
$promote_id = intval($_POST['promote_id']);
$pindao_id = intval($_POST['pindao_id']);
$description = $_POST['description']; //过滤内容
$nick = $_POST['nick'];
if ($num_iid == "" || $detail_url == "" || $title == "" || $pic_url == "" || $price == "" || $coupon_price == "") {
$message = "请把商品信息填写完整,星号为必填项!!";
} else {
$sql = 'SELECT * FROM `jae_goods` WHERE `num_iid`="' . $num_iid . '"';
$pdo=new PDO();
$rs = $pdo->query($sql);
$row = $rs->fetchAll(); //取得所有记录
if (count($row) == 0) {
if (rRuleUrl($detail_url) && rRuleNum($num_iid) && rRulePrice($price) && rRulePrice($coupon_price)) {
$datetime = date("Y-m-d H:i:s");
$sql = 'INSERT INTO `jae_goods` SET `num_iid`="' . $num_iid . '", `title`="' . $title . '", `pic_url`="' . $pic_url . '", `detail_url`="' . $detail_url . '", `price`="' . $price . '", `coupon_price`="' . $coupon_price . '", `num`="' . $num . '", `create_time`="' . $create_time . '", `description`="' . $description . '", `category_id`="' . $categoryId . '", `end_time`="' . $end_time . '", `promote_id`="' . $promote_id . '", `freight_payer`="' . $freight_payer . '", `nick`="' . $nick . '", `begin_time`="' . $begin_time . '", `pindao_id`="' . $pindao_id . '"';
$count = $pdo->exec($sql);
if ($count > 0) {
$message = "新增成功";
} else {
echo $sql;
$message = "添加失败";
}
} else {
if (!rRuleUrl($detail_url))
$message .= '商品链接url填写不规范,带http://模式<br>';
elseif (!rRuleNum($num_iid))
$message .= '商品id填写不规范,数字模式<br>';
elseif (!rRulePrice($price))
$message .= '商品价格填写不规范,小数模式:10.00<br>';
elseif (!rRulePrice($coupon_price))
$message .= '促销价格填写不规范,小数模式:10.00<br>';
}
} else {
$message = "【商品id】或者【标题】重复!!";
}
}
}
include $this->admin_tpl('goods_add','apply');
}
function delete()
{
if(is_array($_POST['ids'])){
foreach($_POST['ids'] as $id) {
print_r($linkid_arr);
//批量删除友情链接
$this->db->delete($this->table, 'id=' . $id);
}
showmessage(L('operation_success'),'?m=link&c=link');
}
$_GET['id'] = intval($_GET['id']);
$this->db->delete($this->table, 'id=' . $_GET['id']);
showmessage(L('operation_success'));
}
function edit()
{
$promotePositionArr = rGetPromotePositionArr('goods');
$categoryArr = rGetCategoryArr();
$pindaoArr = rGetPindaoArr();
if (isset($_POST['dosubmit'])) {
$id = intval($_POST['id']);
$_POST['info']["begin_time"] = strtotime($_POST['info']["begin_time"]);
$_POST['info']["end_time"] = strtotime($_POST['info']["end_time"]);
$_POST['info']["status"] =-1;
$data = $_POST['info'];
$this->db->update($data, $this->table, 'id=' . $id);
showmessage(L('operation_success'));
include $this->admin_tpl('goods_edit','apply');
} else {
$id = intval($_GET['id']);
$r = $this->db->get_one('*', $this->table, 'id=' . $id);
extract($r);
include $this->admin_tpl('goods_edit','apply');
}
}
/*审核通过*/
function pass(){
$id = $_GET["id"];
$data=array('status'=>1);
$this->db->update($data, $this->table, 'id=' . $id);
showmessage(L('operation_success'));
}
/**
* 排序
*/
function listorder()
{
if (isset($_POST['dosubmit'])) {
foreach ($_POST['listorders'] as $id => $listorder) {
$listorder = !empty($listorder) ? $listorder : '0';
$this->db->update(array(
'listorder' => $listorder
), $this->table, 'id=' . $id);
$status = isset($_POST["status"][$id]) ? $_POST["status"][$id] : '0';
$this->db->update(array(
'status' => $status
), $this->table, 'id=' . $id);
}
showmessage(L('operation_success'));
} else {
showmessage(L('operation_failure'));
}
}
}
?><file_sep>/caches/caches_template/default/content/show_special.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head_mini');
//if ($islink==1) header("Location:".$url);
?>
<link rel="stylesheet" href="/statics/special_css/special_<?php echo $id?>.css" />
<div class="sperai">
<?php echo htmlspecialchars_decode($html);?>
</div>
<file_sep>/jae/modules/order/templates/order_list.tpl.php
<?php include $this->admin_tpl('head','admin');?>
<div class="pages"><?php echo $pages;?></div>
<form name="searchform" action="" method="get" accept-charset="UTF-8">
<input type="hidden" value="order" name="m">
<input type="hidden" value="order" name="c">
<input type="hidden" value="init" name="a">
<input type="hidden" value="<?php echo $this->menuid;?>" name="menuid">
<table width="100%" cellspacing="0" class="search-form">
<tbody>
<tr>
<td><div class="explain-col"> 标题
<input name="title" type="text" value="<?php echo $title?>" class="input-text">userid
<input name="userid" type="text" value="<?php echo $userid?>" class="input-text">
<input type="submit" name="search" class="button" value="搜索">
</div></td>
</tr>
</tbody>
</table>
</form>
<form name="myform" action="/admin.php?m=order&c=order&a=listorder" method="post">
<div class="pad-lr-10">
<div class="table-list">
<table width="100%" cellspacing="0" class="table_form">
<tbody>
<tr class="thead">
<th width="20">ID</th>
<th width="20">USERID</th>
<th width="20">GOODSID</th>
<th width="20">描述</th>
<th width="100">标题</th>
<th width="60">图片</th>
<th width="60">中奖人姓名</th>
<th width="100">中奖人旺旺</th>
<th width="80">中奖人电话</th>
<th width="100">中奖人地址</th>
<th width="100">状态</th>
<th width="100">快递名称 </th>
<th width="100">快递单号 </th>
<th width="100">时间 </th>
<th width="100">类型 </th>
<th align="center"><?php echo L('operations_manage');?></th>
</tr>
<?php foreach ($data as $v){?>
<tr>
<td align="center"><?php echo $v['id'];?></td>
<td align="center"><?php echo $v['userid'];?></td>
<td align="center"><?php echo $v['goodsid'];?></td>
<td align="center"><?php echo $v['description'];?></td>
<td ><a href="<?php echo $v['url']?>" target="_blank"><?php echo $v['title']?></a></td>
<td align="center"><a href="<?php echo $v['url']?>" target="_blank"><img src="<?php echo $v['picture']?>" height="60"></a></td>
<td align="center" ><a href="/admin.php?m=member&c=buyer&a=show&userid=<?php echo $r['userid'];?>&menuid=<?php echo $menuid?>"><?php echo get_memberinfo($v['userid'],'nickname')?></a></td>
<td align="center" ><?php echo get_memberinfo($v['userid'],'wangwang')?></td>
<td align="center" ><?php echo get_memberinfo($v['userid'],'mobile')?></td>
<td align="center" ><?php echo get_memberinfo($v['userid'],'address')?></td>
<td align="center" ><?php echo $order_follow[$v['status']+1] ?></td>
<td align="center" ><?php echo $v['express_name']?></td>
<td align="center" ><?php echo $v['express_num']?></td>
<td><?php echo date("m-d H:i:s",$v['date'])?></td>
<td><?php echo $v['module'];?></td>
<td align="center"><?php echo '<a target="_blank" href="/admin.php?m=order&c=order&a=edit&id='.$v['id'].'&menuid='.$menuid.'">'.L('发货').'</a> | <a href="/admin.php?m=order&c=order&a=delete&id='.$v['id'].'&menuid='.$menuid.'">'.L('delete').'</a> ';?></td>
</tr>
<?php }?>
</tbody>
</table>
<div class="btns">
<input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>" />
</div>
</div>
</div>
</div>
</form>
<div class="pages"><?php echo $pages;?></div>
<?php include $this->admin_tpl('foot','admin');?>
<file_sep>/jae/modules/point/templates/point_set.tpl.php
<?php include $this->admin_tpl('head','admin');?>
<form name="myform" action="/admin.php?m=weblink&c=weblink&a=listorder" method="post">
<div class="pad-lr-10">
<div class="table-list">
<table width="100%" cellspacing="0" class="table_form">
<tbody>
<tr class="thead">
<th width="20">id</th>
<th width="140">标题</th>
<th width="80">图片</th>
<th align="center">描述</th>
<th width="40">天数</th>
<th width="40">分数</th>
<th width="200" align="center"><?php echo L('operations_manage');?></th>
</tr>
<?php foreach ($data as $v){?>
<tr>
<td align="center"><?php echo $v['id'];?></td>
<td ><?php echo $v['title']?></td>
<td align="center"><img src="<?php echo $v['picture']?>" height="60"></td>
<td ><?php echo $v['description']?></td>
<td align="center"><?php echo $v['day']?></td>
<td align="center"><?php echo $v['point']?></td>
<td align="center"><?php echo '<a href="/admin.php?m=point&c=point_set&a=edit&id='.$v['id'].'&menuid='.$menuid.'">'.L('modify').'</a> | <a href="/admin.php?m=point&c=point_set&a=delete&id='.$v['id'].'&menuid='.$menuid.'">'.L('delete').'</a> ';?></td>
</tr>
<?php }?>
</tbody>
</table>
<div class="btns">
<input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>" />
(每项必填)</div>
</div>
</div>
</div>
</form>
<div class="pages"><?php echo $pages;?></div>
<?php include $this->admin_tpl('foot','admin');?>
<file_sep>/jae/modules/content/special.php
<?php
defined('IN_JAE') or exit('No permission resources.');
class special {
private $db;
function __construct() {
$this->db =jae_base::load_sys_class('mysql');
$this->table='jae_special';
}
public function list_special() {
$where='status=1';
$page=$_GET['page'];
$special=$this->db->listinfo("*",$this->table,$where,"listorder ASC",$page,10);
$pages=$this->db->pages;
include template('content','list_special');
}
public function show_special() {
$id = intval($_GET['id']);
$v=$this->db->get_one('*',$this->table,'id='.$id);
if($v) extract($v);
include template('content','show_special');
}
}
?><file_sep>/caches/caches_template/default/prize/index_unable.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php
include template('content','head');
?>
<div class="i_step i_step1" style="height: 740px;
background: url(/statics/images/thanks_bg.png) no-repeat center 0 #F2445D;" >
<div class="i_w990" style="width: 990px;
margin: 0 auto;
position: relative;"> <img style="display:block" src="/statics/images/thanks.png">
<div class="step_info" style="color: white;
display: block;
font-family: 'Microsoft Yahei', 微软雅黑, 黑体, 宋体;
font-size: 12px;
font-style: normal;
font-variant: normal;
font-weight: normal;
height: 96px;
left: 0px;
line-height: 18px;
margin-bottom: 0px;
margin-left: 0px;
margin-right: 0px;
margin-top: 0px;
padding-bottom: 0px;
padding-left: 0px;
padding-right: 0px;
padding-top: 0px;
position: absolute;
text-align: center;
top: 69px;
width: 990px;">
<p class="h1" style="font-size: 58px;
font-weight: bold;
line-height: 60px;">活动紧急筹备中</p>
<p class="h3" style="font-size: 24px;
line-height: 36px;" >感谢有你,请随时关注,请耐心等待</p>
</div>
</div>
</div>
<file_sep>/jae/modules/member/buyer.php
<?php
defined('IN_JAE') or exit('No permission resources.');
defined('IN_ADMIN') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
jae_base::load_app_func('global','admin');
class buyer extends admin {
public function __construct() {
//$this->menu_db = jae_base::load_model('menu_model');
parent::__construct();
$this->db =jae_base::load_model('member_model');
$this->point_db =jae_base::load_model('point_model');
$this->menuid=8;
}
public function init () {
$where='1 ';
$userid = isset($_GET['userid']) ? $_GET['userid'] : '';
$nickname = isset($_GET['nickname']) ? $_GET['nickname'] : '';
$mobile = isset($_GET['mobile']) ? $_GET['mobile'] : '';
if (!empty($userid))$where .= " AND `userid` = '$userid'";
if (!empty($nickname))$where .= " AND `nickname` = '$nickname'";
if (!empty($mobile))$where .= " AND `mobile` = '$mobile'";
$order = $_GET['order']?$_GET['order']:'userid';
$page=$_GET['page'];
$data=$this->db->listinfo($where,"$order DESC",$page,20);
$pages=$this->db->pages;
include $this->admin_tpl('buyer_list');
}
public function delete() {
$_GET['userid'] = intval($_GET['userid']);
$this->db->delete('userid='.$_GET['userid']);
showmessage(L('operation_success'));
}
public function edit() {
if(isset($_POST['dosubmit'])) {
$userid = intval($_POST['userid']);
$data=$_POST['info'];
$this->db->update($data,'userid='.$userid);
showmessage(L('operation_success'));
} else {
$userid = intval($_GET['userid']);
$r=$this->db->get_one('userid='.$userid);
if($r) extract($r);
include $this->admin_tpl('buyer_edit');
}
}
public function export(){
if(isset($_POST['dosubmit'])) {
$limit_start =$_POST['limit_start'];
$limit_end =$_POST['limit_end'];
header( "Cache-Control: public" );
header( "Pragma: public" );
header("Content-type:application/vnd.ms-excel");
header("Content-Disposition:attachment;filename=member".date('Y-m-d',SYS_TIME).".csv");
header('Content-Type:APPLICATION/OCTET-STREAM');
$data=$this->db->select($where = "userid >=$limit_start AND userid <= $limit_end", );
echo "userid,fromuserid,username,nickname,regdate,lastdate,login_num,point,vip,sign_num,last_continue,last_sign,wangwang,mobile,address,email\r\n";
foreach ($data as $key => $value) {
//$sign_num=$this->point_db->count("userid=".$value['userid']." AND typeid=1");
//$last_sign=$this->point_db->get_one("userid=".$value['userid'], $data = '*',$order =' date desc');
echo $value['userid'].','.$value['fromuserid'].','.$value['username'].','.$value['nickname'].','.date('Y-m-d H:i',$value['regdate']).','.date('Y-m-d H:i',$value['lastdate']).','.$value['loginnum'].','.$value['point'].','.$value['vip'].','.$sign_num.','.$last_sign['continue'].','.date('Y-m-d H:i',$last_sign['date']).','.$value['wangwang'].','.$value['mobile'].','.$value['address'].','.$value['email']."\r\n";
}
}else{
include $this->admin_tpl('buyer_export');
}
}
public function exports(){
//header( "Cache-Control: public" );
//header( "Pragma: public" );
//header("Content-type:application/vnd.ms-excel");
//header("Content-Disposition:attachment;filename=member".date('Y-m-d',SYS_TIME).".csv");
//header('Content-Type:APPLICATION/OCTET-STREAM');
$data=$this->db->select();
$str="userid,fromuserid,username,nickname,regdate,lastdate,login_num,point,vip,sign_num,last_continue,last_sign,wangwang,mobile,address\r\n";
foreach ($data as $key => $value) {
//$sign_num=$this->point_db->count("userid=".$value['userid']." AND typeid=1");
//$last_sign=$this->point_db->get_one("userid=".$value['userid'], $data = '*',$order =' date desc');
$str.= $value['userid'].','.$value['fromuserid'].','.$value['username'].','.$value['nickname'].','.date('Y-m-d H:i',$value['regdate']).','.date('Y-m-d H:i',$value['lastdate']).','.$value['loginnum'].','.$value['point'].','.$value['vip'].','.$sign_num.','.$last_sign['continue'].','.date('Y-m-d H:i',$last_sign['date']).','.$value['wangwang'].','.$value['mobile'].','.$value['address']."\r\n";
}
file_put_contents("member".date('Y-m-d',SYS_TIME).".csv", $str);
$file_name="member".date('Y-m-d',SYS_TIME).".csv";
//$file_sub_path=$_SERVER['DOCUMENT_ROOT']."marcofly/phpstudy/down/down/";
$file_path=$file_sub_path.$file_name;
//首先要判断给定的文件存在与否
if(!file_exists($file_path)){
echo "没有该文件文件";
return ;
}
$fp=fopen($file_path,"r");
$file_size=filesize($file_path);
//下载文件需要用到的头
Header("Content-type: application/octet-stream");
Header("Accept-Ranges: bytes");
Header("Accept-Length:".$file_size);
Header("Content-Disposition: attachment; filename=".$file_name);
$buffer=1024;
$file_count=0;
//向浏览器返回数据
while(!feof($fp) && $file_count<$file_size){
$file_con=fread($fp,$buffer);
$file_count+=$buffer;
echo $file_con;
}
fclose($fp);
}
public function show () {
$page=$_GET['page'];
$userid = intval($_GET['userid']);
$where =" userid=$userid ";
$userinfo=$this->db->get_one("userid = $userid");
$data=$this->point_db ->listinfo($where,"id DESC",$page,50);
$data=$data->fetchAll();
$pages=$this->point_db->pages;
include $this->admin_tpl('show_point');
}
public function edit_point() {
if(isset($_POST['dosubmit'])) {
$id = intval($_POST['id']);
$userid = intval($_POST['userid']);
$data=$_POST['info'];
$this->point_db->update($data,'id='.$id);
$this->point =jae_base::load_app_class('point','point');
$this->point->update_point($userid);//更新积分明细
showmessage(L('operation_success'),"/admin.php?m=member&c=buyer&a=show&userid=$userid&menuid=8");
}else {
$id = intval($_GET['id']);
$userid = intval($_GET['userid']);
$r=$this->point_db->get_one('id='.$id);
if($r) extract($r);
include $this->admin_tpl('edit_point');
}
}
public function delete_point() {
$_GET['id'] = intval($_GET['id']);
$_GET['userid'] = intval($_GET['userid']);
$this->point_db->delete('id='.$_GET['id']);
$this->point =jae_base::load_app_class('point','point');
$this->point->update_point($_GET['userid']);//更新积分明细
showmessage(L('operation_success'));
}
public function check_invite () {
$where='1 ';
$page=$_GET['page'];
$where .= " AND `fromuserid` != 0 AND `islock`= 0 ";
$order = $_GET['order']?$_GET['order']:'userid';
$data=$this->db->listinfo($where,"$order DESC",$page,50);
$pages=$this->db->pages;
include $this->admin_tpl('check_invite');
}
public function pass_point () {
$setting=getcache_sql('point_invite', 'commons');
$fromuserid=intval($_GET['fromuserid']);
$userid=intval($_GET['userid']);
$this->db->update(array('islock'=>1),"userid=$userid");
if($setting['enable']==1 && $fromuserid!=0) {
$array_point=array('userid'=>$fromuserid,'point'=>intval($setting['point']),'title'=>$setting['title']."ID".$userid,'date'=>SYS_TIME,'picture'=>$setting['thumb'],'description'=>$setting['description'],'status'=>'2','module'=>'invite');
$this->point =jae_base::load_app_class('point','point');
$this->point->change_point($array_point);//更新积分明细
}
showmessage(L('operation_success'));
}
public function pass_list () {
$setting=getcache_sql('point_invite', 'commons');
if ($_POST['dosubmit']==1) {
foreach ($_POST['listorders'] as $userid => $fromuserid) {
$this->db->update(array('islock'=>1),"userid=$userid");
$array_point=array('userid'=>$fromuserid,'point'=>intval($setting['point']),'title'=>$setting['title']."ID".$userid,'date'=>SYS_TIME,'picture'=>$setting['thumb'],'description'=>$setting['description'],'status'=>'2','module'=>'invite');
$this->point =jae_base::load_app_class('point','point');
$this->point->change_point($array_point);//更新积分明细
}
showmessage(L('operation_success'));
} elseif ($_POST['dosubmit']==0) {
foreach ($_POST['listorders'] as $userid => $fromuserid) {
$this->db->update(array('islock'=>1),"userid=$userid");
}
showmessage(L('operation_success'));
}
}
}<file_sep>/caches/caches_commons/caches_data/point_invite.cache.php
<?php
return array (
'point' => '',
'title' => '邀请好友赚积分',
'description' => '邀请好友赚积分',
'enable' => '1',
'thumb' => 'http://a.tbcdn.cn/apps/membermanager/image/pro-activity.png',
'content_url' => '到淘宝网特色中国馆参与积分秒杀、抽奖、积分换购超多惊喜奖品等你来拿!',
);
?><file_sep>/jae/modules/admin/shop.php
<?php
defined('IN_JAE') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
class shop extends admin {
function __construct() {
parent::__construct();
$this->db =jae_base::load_sys_class('mysql');
$this->table='jae_shop';
$this->menuid=23;
}
function init () {
$page=$_GET['page'];
$data=$this->db->listinfo("*",$this->table,"","id DESC",$page,10);
$pages=$this->db->pages;
include $this->admin_tpl('shop_list');
}
function add() {
//获取站点配置信息
$siteinfo=siteinfo(SITEID);
$appkey =$siteinfo['appkey'];
$secret =$siteinfo['secretkey'];
jae_base::load_top('topclient');
jae_base::load_top('ShopGetRequest');
//初始化条件
$categoryArr = rGetCategoryArr();
$promoteArr = rGetPromotePositionArr('shop');
$dopost = isset($_POST['dopost'])?$_POST['dopost']:'';
$nick = isset($_POST['nick'])?$_POST['nick']:'';
$category_id= isset($_POST['category_id'])?$_POST['category_id']:0;
$detail_url= isset($_POST['detail_url'])?$_POST['detail_url']:'';
$pic_url= isset($_POST['pic_url'])?'http://logo.taobao.com/shop-logo'.$_POST['pic_url']:'';
$shop_title= isset($_POST['shop_title'])?$_POST['shop_title']:'';
$description= isset($_POST['description'])?$_POST['description']:'';
$promote_id= isset($_POST['promote_id'])?$_POST['promote_id']:0;
$sid= isset($_POST['sid'])?$_POST['sid']:0;
$create_time= time();
$createMessage='';
if ($dopost == 'caiji')
{
if ($nick != "")
{
$c = new TopClient;
$c->appkey = $appkey; //top appkey
$c->secretKey = $secret; //top secretkey
//实例化具体API对应的Request类
$req = new ShopGetRequest(); //top 封装的php文件
$req->setFields("sid,cid,title,nick,desc,pic_path,created,modified");
$req->setNick($nick);
$resp = $c->execute($req);
if ($resp->shop)
{
$sid = $resp->shop->sid;
$shop_title = $resp->shop->title;
$detail_url = 'http://shop'.$resp->shop->sid.'.taobao.com';
$description = $resp->shop->desc;
$pic_url = $resp->shop->pic_path;
}else
$createMessage= '不存在这个店铺';
}
else
{
$createMessage= "商家昵称不能为空。";
}
}
if ($dopost == 'create')
{
if ($nick == "" || $detail_url == "" || $shop_title == "" || $pic_url == "")
{
$createMessage= "请把商品信息填写完整!!";
}
else
{
$sql = 'select * from jae_shop where nick="'.$nick.'"';
$pdo =new PDO();
$rs = $pdo->query($sql);
$row = $rs->fetchAll(); //取得所有记录
if (count($row) == 0)
{
// $detail_url.='?nick_uz='.$nick;
$datetime = date("Y-m-d H:i:s");
$sql = "INSERT INTO `jae_shop` (`nick`,`category_id`,`detail_url`,`pic_url`,`shop_title`,`description`,`sid`,`create_time`,`promote_id`)
VALUES ('$nick','$category_id','$detail_url','$pic_url','$shop_title','$description','$sid',' $create_time',' $promote_id')";
$count = $pdo->exec($sql);
print_r($count);
if ($count > 0)
{
$createMessage= "新增成功";
}
else
{
echo $sql;
$createMessage= "添加失败";
}
}
else
{
$createMessage= "店铺重复!!";
}
}
}
include $this->admin_tpl('shop_add');
}
function delete() {
$_GET['id'] = intval($_GET['id']);
$this->db->delete($this->table,'id='.$_GET['id']);
showmessage(L('operation_success'));
}
function edit() {
if(isset($_POST['dosubmit'])) {
$id = intval($_POST['id']);
$data=$_POST['info'];
$this->db->update($data,$this->table,'id='.$id);
showmessage(L('operation_success'));
include $this->admin_tpl('shop_edit');
} else {
$id = intval($_GET['id']);
$r=$this->db->get_one('*',$this->table,'id='.$id);
if($r) extract($r);
include $this->admin_tpl('shop_edit');
}
}
/**
* 排序
*/
function listorder() {
if(isset($_POST['dosubmit'])) {
foreach($_POST['listorders'] as $id => $listorder) {
$listorder = !empty($listorder) ? $listorder : '0';
$this->db->update(array('listorder'=>$listorder),$this->table,'id='.$id);
$status = isset($_POST["status"][$id]) ? $_POST["status"][$id] : '0';
$this->db->update(array('status'=>$status),$this->table,'id='.$id);
}
showmessage(L('operation_success'));
} else {
showmessage(L('operation_failure'));
}
}
}
?><file_sep>/jae/modules/member/templates/check_invite.tpl.php
<?php include $this->admin_tpl('head','admin');?>
<div class="pad-lr-10">
<div class="table-list">
<form name="myform" action="/admin.php?m=member&c=buyer&a=pass_list&menuid=9" method="post">
<table width="100%" cellspacing="0" class="table_form">
<tbody>
<tr class="thead">
<th width="30">状态</th>
<th width="30"><?php echo L('userid');?></th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=nickname">邀请ID</a></th>
<th width="80">淘宝混肴昵称</th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=nickname">用户姓名</a></th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=wangwang">旺旺</a></th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=mobile">手机</a></th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=address">地址</a></th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=address">EMAIL</a></th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=regdate">入驻时间</a> </th>
<th width="80"><a href="/admin.php?m=member&c=buyer&a=init&menuid=8&order=point">积分</a></th>
<th align="center"><?php echo L('operations_manage');?></th>
</tr>
<?php foreach ($data as $r){ $last_sign=$this->point_db->get_one("userid=".$r['userid'], $data = '*',$order =' date desc');?>
<tr>
<td align="center"> <input style="cursor:pointer" type="checkbox" name="listorders[<?php echo $r['userid']; ?>]" value="<?php echo $r['fromuserid']; ?>" }?> </td>
<td align="center"><a href="/admin.php?m=member&c=buyer&a=show&userid=<?php echo $r['userid'];?>&menuid=<?php echo $menuid?>"><?php echo $r['userid'];?></a></td>
<td align="center"><a href="/admin.php?m=member&c=buyer&a=show&userid=<?php echo $r['userid'];?>&menuid=<?php echo $menuid?>"><?php echo $r['fromuserid'];?></a></td>
<td align="center" title="<?php echo $r['username'];?>"><?php echo str_cut($r['username'],5) ;?></td>
<td align="center"><?php echo $r['nickname'];?></td>
<td align="center"><?php echo $r['wangwang'];?></td>
<td align="center"><?php echo $r['mobile'];?></td>
<td align="center" title="<?php echo $r['address'];?>"><?php echo str_cut($r['address'],20);?></td>
<td align="center"><?php echo $r['email'];?></td>
<td align="center"><?php echo date('Y-m-d H:i' ,$r['regdate']);?></td>
<td align="center"><a href="/admin.php?m=member&c=buyer&a=show&fromuserid=<?php echo $r['fromuserid'];?>&userid=<?php echo $r['userid'];?>&menuid=<?php echo $menuid?>"><?php echo $r['point'];?></a></td>
<td align="center"><?php echo '<a href="/admin.php?m=member&c=buyer&a=pass_point&fromuserid='.$r['fromuserid'].'&userid='.$r['userid'].'&menuid='.$menuid.'">'.L('发积分').'</a> <a href="/admin.php?m=member&c=buyer&a=pass_point&userid='.$r['userid'].'&menuid='.$menuid.'">'.L('不发积分').'</a> ';?></td>
</tr>
<?php }?>
</tbody>
</table>
<div class="btns">
<button type="submit" class="button" name="dosubmit" value="1" /><?php echo L('发积分')?></button><button type="submit" class="button" name="dosubmit" value="0" /><?php echo L('不发积分')?></button>
</div>
</form>
<div class="pages"><?php echo $pages?></div>
</div>
<?php include $this->admin_tpl('foot','admin');?>
<file_sep>/jae/libs/classes/db_factory.class.php
<?php
/**
* db_factory.class.php 数据库工厂类
*
* @copyright (C) 2005-2010 PHPCMS
* @license http://www.phpcms.cn/license/
* @lastmodify 2010-6-1
*/
final class db_factory {
/**
* 当前数据库工厂类静态实例
*/
private static $db_factory;
/**
* 数据库配置列表
*/
protected $db_config = array();
/**
* 数据库操作实例化列表
*/
protected $db_list = array();
/**
* 构造函数
*/
public function __construct() {
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=uzhan', 'root', 'localmysql');
}
/**
* 返回当前终级类对象的实例
* @param $db_config 数据库配置
* @return object
*/
}
?><file_sep>/caches/caches_template/hubei/content/index.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><div class="wrap"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=f65a1cd8bc45f9b3983da2393c855cb2&pos=dingtong\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=f65a1cd8bc45f9b3983da2393c855cb2&pos=dingtong\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'dingtong',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<?php include template('content','head');?>
<link rel="stylesheet" href="/statics/css/lows.css" />
<?php jae_base::load_sys_class('user');?>
<div class="lows-banner J_TWidget" style="display:none" id="J_LowsBanner" data-widget-type="Carousel" data-widget-config="{'navCls':'ks-switchable-nav','contentCls':'ks-switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [290], 'circular': true, 'activeTriggerCls':'active','autoplay':'true','interval':3,'prevBtnCls': 'prev', 'nextBtnCls': 'next', 'disableBtnCls': 'disable' }">
<div class="trigger-wrap"> <span class="close J_LowsClose"></span> <span class="prev"></span> <span class="next"></span>
<ol class="lows-trigger ks-switchable-nav">
<li class="ks-switchable-trigger-internal297 active"></li>
<li class="ks-switchable-trigger-internal297 "></li>
<li class="ks-switchable-trigger-internal297"></li>
</ol>
</div>
<ul class="ks-switchable-content clear-fix">
<li class="pic1 ks-switchable-panel-internal298" style="display: block; opacity: 0; position: absolute; z-index: 1; ">
<div class="banner-pic" style="background: url(http://img04.taobaocdn.com/imgextra/i4/1089118323/TB2_ZYlXVXXXXXxXXXXXXXXXXXX-1089118323.png) no-repeat 0 0;"></div>
</li>
<li class="pic2 ks-switchable-panel-internal298" style="display: block; opacity: 1; position: absolute; z-index: 9; ">
<div class="banner-pic" style="background: url(http://img04.taobaocdn.com/imgextra/i4/1089118323/TB2CcYlXVXXXXaBXXXXXXXXXXXX-1089118323.png) no-repeat 0 0;"></div>
</li>
<li class="pic3 ks-switchable-panel-internal298" style="display: block; opacity: 0; position: absolute; z-index: 1; ">
<div class="banner-pic" style="background: url(http://img04.taobaocdn.com/imgextra/i4/1089118323/TB2LI_lXVXXXXXaXpXXXXXXXXXX-1089118323.png) no-repeat 0 0;"></div>
</li>
</ul>
</div>
<div class="body_w">
<div class="wrap " data-widget-type="Slide" data-widget-config="{'navCls':'w-nav','contentCls':'w-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [1920], 'circular': true,'activeTriggerCls':'on','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }" style="height:480px;">
<div class="fenlei">
<div class="list">
<ul class="w-nav" >
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=c3ed3d7e50eba5e2cf9a1fd2c69d78d4&pos=fenlei\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=c3ed3d7e50eba5e2cf9a1fd2c69d78d4&pos=fenlei\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'fenlei',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</ul>
</div>
</div>
<!--shoujiao-->
<div class="slide w-content" >
<div class="focus J_TWidget" data-widget-type="Carousel" data-widget-config="{'navCls':'tab-nav','contentCls':'tab-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [1920], 'circular': true,'activeTriggerCls':'on', 'autoplay':'true','interval':3,'prevBtnCls': 'prev', 'nextBtnCls': 'next', 'disableBtnCls': 'disable' }">
<div class="prev"></div>
<div class="next"></div>
<div class="tab-content">
<?php $sql="SELECT * FROM jae_focus WHERE status=1 ORDER BY listorder ASC ";
$r_focus=query($sql); foreach ($r_focus as $r) {?>
<div><a href="<?php echo $r["link"]?>" target="_blank"> <img src="<?php echo $r["picture"]?>" width="1920" height="480"/></a></div>
<?php }?>
</div>
<div class="tab-nav">
<?php $r_focuss=query($sql); foreach ($r_focuss as $k=>$rs) {?>
<div class="v<?php echo $k?>"></div>
<?php }?>
</div>
</div>
</div>
<!--shoujia end-->
<div class="vPersonal" data-spm="16">
<!--达人权益标题-->
<div class="hd">会员中心</div>
<!--个人信息区域开始-->
<div class="info">
<div class="photo " data-test="-1">
<div class="p" id="J_personal_photo" data-garden="-1" data-experience="10007" data-img="http://img.taobaocdn.com/sns_logo/T1xzuvFcRcXXb1upjX.jpg_80x80.jpg"> <?php echo '<img width=76 height=76 src="/_RS/user/picture?mixUserNick='.urlencode($nick,"UTF-8").'" /> ';?></div>
<span class="m"></span> <span class="m mb-hide j_changeInfo"> <b>编辑资料</b> </span> </div>
<div class="per">
<p class="title" >HI!<span class="login_tip"><a href="/member.php" style="color:#fff;">请登录</a></span></p>
<!--<p class="garden">您是湖北馆会员</p>-->
<p class="bt">
<!-- <a class="activied j_activied" href="javascript:void(0);">激活</a>-->
<a class="sign j_sign activied" href="/index.php?m=member&c=index&a=init" target="_blank">签到</a> </p>
</div>
</div>
<!--个人信息区域结束-->
<!--个人资产区域开始-->
<div class="assets unlogin"> <span class="bt1"></span>
<!--已登录开始-->
<div class="row point"> <span class="icon"></span>
<p class="ht"> <a href="/index.php?m=point&c=index&a=sign&trad=all" target="_blank">我的积分:</a> <span class="pots "> <a href="/index.php?m=point&c=index&a=sign&trad=all" target="_blank">0</a> </span> </p>
<p class="bt"> 邀请好友就能赚积分 </p>
</div>
<div class="row coupon"> <span class="icon"></span>
<p class="ht"> <a href="/index.php?m=prize&c=index&a=my_prize" target="_blank">我的奖品:</a> <span class="prizes_num" ><a href="/index.php?m=prize&c=index&a=my_prize" target="_blank">0</a></span> 个 </p>
<p class="bt"> <a href="/index.php?m=prize&c=index&a=my_prize" target="_blank"> 快来参加积分抽奖吧 </a> </p>
</div>
<div class="row message"> <span class="icon"></span>
<p class="ht"> <a href="/index.php?m=order&c=index&a=init" target="_blank">我的订单:</a> <span class="orders_num"><a href="/index.php?m=order&c=index&a=init" target="_blank">0</a></span> 个 </p>
<p class="bt"> <a class="dr" href="/index.php?m=order&c=index&a=init" target="_blank">湖北馆的积分活动</a> </p>
</div>
<!--已登录结束--> </div>
<!--个人资产区域结束-->
<!--特权区域开始-->
<div class="privilege">
<div class="title"></div>
<div class="list" id="J_privilege_tab">
<div style="position: relative; overflow: hidden; height: 130px;">
<ul class="tab-content" style="width: 190px; overflow: hidden; height: 90px; ">
<div style="position: absolute; overflow: hidden; width: 380px; -webkit-transition: 0s; -webkit-transform: translate3d(0px, 0px, 0px); -webkit-backface-visibility: hidden; ">
<li class="tab-pannel" style="float: left; overflow: hidden; width: 190px; display: block; ">
<ul class="privList">
<li> <a href="/index.php?m=point&c=index&a=sign&trad=all" target="_blank"> <span class="icon "></span> 我的签到 </a> </li>
<li> <a href="/index.php?m=prize&c=index&a=init" target="_blank"> <span class="icon "></span> 积分抽奖 </a> </li>
<li> <a href="/index.php?m=exchange&c=index&a=init" target="_blank"> <span class="icon "></span> 积分换购 </a> </li>
<li> <a href="/index.php?m=seckill&c=index&a=init" target="_blank"> <span class="icon "></span> 积分秒杀 </a> </li>
<li> <a href="/index.php?m=content&c=index&a=lists&catid=1" target="_blank"> <span class="icon "></span> 购物返积分 </a> </li>
<li> <a href="/index.php?m=point&c=index&a=point_invite" target="_blank"> <span class="icon "></span> 邀请好友 </a> </li>
</ul>
</li>
<li class="tab-pannel hidden" style="float: left; overflow: hidden; width: 190px; display: block; ">
<ul class="privList">
<li> </li>
<li> </li>
</ul>
</li>
</div>
</ul>
</div>
</div>
</div>
<!--特权区域结束--> </div>
<div class="clear"></div>
</div>
<div style="clear:both; height:30px;"></div>
<div class="wrap"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=0a9b410421557918f345c0a730217395&pos=tonglan1\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=0a9b410421557918f345c0a730217395&pos=tonglan1\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'tonglan1',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<!-- 9.9包邮专区 -->
<div class="wrap ">
<div class="f_title">9.9包邮专区<span>限时特价 精选推荐</span></div>
<div class="baoyou clearfix">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=8e3b64c070c9dd850bdcd286a79eb8ca&action=position&posid=10&order=listorder+asc&num=10\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=8e3b64c070c9dd850bdcd286a79eb8ca&action=position&posid=10&order=listorder+asc&num=10\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'10','order'=>'listorder asc','limit'=>'10',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="li"><a href="<?php echo $r['url'];?>" target="_blank"><img width="220" height="220" src="<?php echo $r['thumb'];?>">
<div class="tit"><?php echo str_cut($r['title'],16,'');?></div>
<div class="price">
<div class="jg">¥9.9 <span>原价:<?php echo $r['price'];?></span></div>
<div class="gm">立即抢购</div>
</div>
<div class="time"><?php echo date("d-h-i",$r['end_time']);?></div></a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
<!-- 9.9包邮专区end -->
<div style="height:30px;"></div>
<!-- 优质品牌推荐 -->
<?php if(0) { ?>
<div class="wrap">
<div class="pinpai J_TWidget" data-widget-type="Slide" data-widget-config="{'navCls':'pp-nav','contentCls':'pp-content','effect': 'fade',
'easing': 'easeIn','triggerType':'mouse', 'steps':1, 'viewSize': [1920], 'circular': true,'activeTriggerCls':'on','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable' }" >
<div class="tp clearfix"> <div class="tits"><span>优质品牌推荐</span><i>品质护航 购物无忧</i></div><div class="dao pp-nav"><div class="on"><img src="http://g.ald.alicdn.com/bao/uploaded/T1yMKJFlxbXXb1upjX.jpg" width="100" height="60"></div><div><img src="http://g.ald.alicdn.com/bao/uploaded/T1kTJzFhxcXXb1upjX.jpg" width="100" height="60"></div> </div>
</div>
<div class="pp-content">
<div class="gds">
<div class="li"><img width="240" height="240" src="http://gtms03.alicdn.com/tps/i3/TB1ixdMGXXXXXalapXXRVNATXXX-170-280.jpg">
<div class="tit">基本原则基本原则</div>
<div class="price">
<div class="jg"><i>¥9.9</i> <span>原价:12.5</span></div>
<div class="gm">立即抢购</div>
</div>
</div>
<div class="li"><img width="240" height="240" src="http://gtms03.alicdn.com/tps/i3/TB1ixdMGXXXXXalapXXRVNATXXX-170-280.jpg">
<div class="tit">基本原则基本原则</div>
<div class="price">
<div class="jg"><i>¥9.9</i> <span>原价:12.5</span></div>
<div class="gm">立即抢购</div>
</div>
</div>
<div class="li"><img width="240" height="240" src="http://gtms03.alicdn.com/tps/i3/TB1ixdMGXXXXXalapXXRVNATXXX-170-280.jpg">
<div class="tit">基本原则基本原则</div>
<div class="price">
<div class="jg"><i>¥9.9</i> <span>原价:12.5</span></div>
<div class="gm">立即抢购</div>
</div>
</div>
<div class="li"><img width="240" height="240" src="http://gtms03.alicdn.com/tps/i3/TB1ixdMGXXXXXalapXXRVNATXXX-170-280.jpg">
<div class="tit">基本原则基本原则</div>
<div class="price">
<div class="jg"><i>¥9.9</i> <span>原价:12.5</span></div>
<div class="gm">立即抢购</div>
</div>
</div>
</div><div class="gds">
<div class="li"><img width="240" height="240" src="http://gtms03.alicdn.com/tps/i3/TB1ixdMGXXXXXalapXXRVNATXXX-170-280.jpg">
<div class="tit">基本原则基本原则</div>
<div class="price">
<div class="jg"><i>¥9.9</i> <span>原价:12.5</span></div>
<div class="gm">立即抢购</div>
</div>
</div>
<div class="li"><img width="240" height="240" src="http://gtms03.alicdn.com/tps/i3/TB1ixdMGXXXXXalapXXRVNATXXX-170-280.jpg">
<div class="tit">基本原则基本原则</div>
<div class="price">
<div class="jg"><i>¥9.9</i> <span>原价:12.5</span></div>
<div class="gm">立即抢购</div>
</div>
</div>
<div class="li"><img width="240" height="240" src="http://gtms03.alicdn.com/tps/i3/TB1ixdMGXXXXXalapXXRVNATXXX-170-280.jpg">
<div class="tit">基本原则基本原则</div>
<div class="price">
<div class="jg"><i>¥9.9</i> <span>原价:12.5</span></div>
<div class="gm">立即抢购</div>
</div>
</div>
<div class="li"><img width="240" height="240" src="http://gtms03.alicdn.com/tps/i3/TB1ixdMGXXXXXalapXXRVNATXXX-170-280.jpg">
<div class="tit">基本原则基本原则</div>
<div class="price">
<div class="jg"><i>¥9.9</i> <span>原价:12.5</span></div>
<div class="gm">立即抢购</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
<!-- 优质品牌推荐end -->
<div class="wrap"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=a126d53d57223f46c490c80a87e0961a&pos=tonglan2\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=a126d53d57223f46c490c80a87e0961a&pos=tonglan2\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'tonglan2',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<!-- 特色品类 -->
<div class="wrap " >
<div class="sort m sm-wrap J_TWidget" style="height:550px;" data-widget-type="Carousel" data-widget-config="{'navCls':'switchable-nav','contentCls':'switchable-content','effect': 'fade',
'easing': 'easeIn','triggerType':'click', 'steps':1, 'viewSize': [1210], 'circular': true, 'activeTriggerCls':'selected','autoplay':'true','interval':3,'prevBtnCls': 'mall-prev', 'nextBtnCls': 'mall-next', 'disableBtnCls': 'disable'}" >
<div class="mt" >
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 2,1 ');
foreach ($result as $v) {
?>
<h2>
<?php echo $v['title'];?>
</h2>
<?php }
?>
<div class="ext switchable-nav">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 3,1 ');
foreach ($result as $v) {
?>
<a href="javascript:void(0)" class="filter-item selected"> <b>
<?php echo $v['title'];?>
</b> </a>
<?php }
?>
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=20 ORDER BY listorder,id ASC LIMIT 4,2 ');
foreach ($result as $v) {
?>
<a href="javascript:void(0)" class="filter-item"> <b>
<?php echo $v['title'];?>
</b> </a>
<?php }
?>
</div>
</div>
<div class="mc switchable-content" style="position: relative;">
<div class="item ui-switchable-panel selected" style="background-color: rgb(255, 255, 255); position: absolute; z-index: 1; opacity: 1; ">
<div class="left">
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(5);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 1,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(6);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 2,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(7);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 3,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(8);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 4,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(9);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 5,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(10);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 6,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(11);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 7,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(12);?></div>
</div>
</div>
</div>
<div class="right">
<div class="r1">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 8,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img width="220" height="220" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="r1">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=25 ORDER BY listorder,id ASC LIMIT 9,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img width="220" height="220" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
</div>
<div class="clr"></div>
</div>
<div class="item ui-switchable-panel selected" style="background-color: rgb(255, 255, 255); position: absolute; z-index: 1; opacity: 1; ">
<div class="left">
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(13);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 1,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(14);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 2,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(15);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 3,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(16);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 4,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(17);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 5,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(18);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 6,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(19);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 7,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(20);?></div>
</div>
</div>
</div>
<div class="right">
<div class="r1">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 8,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img width="220" height="220" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="r1">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=26 ORDER BY listorder,id ASC LIMIT 9,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img width="220" height="220" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
</div>
<div class="clr"></div>
</div>
<div class="item ui-switchable-panel selected" style="background-color: rgb(255, 255, 255); position: absolute; z-index: 1; opacity: 1; ">
<div class="left">
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 0,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(21);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 1,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(22);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 2,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(23);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 3,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(24);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 4,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(25);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 5,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(26);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 6,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(27);?></div>
</div>
</div>
<div class="li3">
<div class="li3_img">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 7,1 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img data-img="2" style="float:none;margin:0px;" width="100" height="80" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
<div class="li3_t">
<div> <?php echo block(28);?></div>
</div>
</div>
</div>
<div class="right">
<div class="r1">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 8,1 ');
foreach ($result as $v) {?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img width="220" height="220" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }?>
</div>
<div class="r1">
<?php $result=query('SELECT * FROM jae_weblink WHERE typeid=27 ORDER BY listorder,id ASC LIMIT 9,1 ');
foreach ($result as $v) {?>
<a target="_blank" href="<?php echo $v['link'];?>
"> <img width="220" height="220" data-ks-lazyload="<?php echo $v['picture'];?>"></a>
<?php }
?>
</div>
</div>
<div class="clr"></div>
</div>
</div>
</div>
</div>
<!-- 特色品类 end -->
<div style="clear:both; height:10px;"></div>
<div class="wrap"> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=0172b35e3b585f2be56ba50fb8ef1e95&pos=tonglan3\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=0172b35e3b585f2be56ba50fb8ef1e95&pos=tonglan3\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'tonglan3',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<!--见食 -->
<div class="wrap jianshi clearfix " style="background:url(http://img04.taobaocdn.com/imgextra/i4/1089118323/TB27NocXVXXXXa7XpXXXXXXXXXX-1089118323.jpg) no-repeat; padding-top:120px;">
<div class="gds">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=d1873a14efbedecaad41e79e98dffdcb&action=position&posid=7&order=listorder+asc&num=5\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=d1873a14efbedecaad41e79e98dffdcb&action=position&posid=7&order=listorder+asc&num=5\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'7','order'=>'listorder asc','limit'=>'5',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="li"><a class="tolink" href="<?php echo $r['url'];?>" target="_blank" > <img data-ks-lazyload="<?php echo $r['thumb'];?>" alt="<?php echo $r['title'];?>" width="220" height="220">
<div class="tit"><?php echo str_cut($r['title'],16,'');?></div>
<div class="price">
<div class="jg"><i>¥<?php echo $r['coupon_price'];?></i> <span>原价:¥<?php echo $r['price'];?></span></div>
<div class="gm">立即抢购</div>
</div></a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?> </div>
</div>
<div style="clear:both; height:30px;"></div>
<!--见食end -->
<div class="wrap"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=3c912622923295a3c552ceaa2f3ff427&pos=tonglan4\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=3c912622923295a3c552ceaa2f3ff427&pos=tonglan4\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'tonglan4',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<!--1楼 -->
<div class="wrap">
<div class="f_title">休闲零食<span>湖北特色休闲零食小吃</span></div>
<div class="louceng clearfix">
<div class="cat">
<div class="img"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=b1823a835f2d8c66694b6c93c9af57a5&pos=flool_1_img\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=b1823a835f2d8c66694b6c93c9af57a5&pos=flool_1_img\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'flool_1_img',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<div class="cat_list"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=7165c46517a9614aeb256edbc64130e8&pos=flool_1_list\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=7165c46517a9614aeb256edbc64130e8&pos=flool_1_list\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'flool_1_list',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
</div>
<div class="gds">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=18fbb0eabaa53df16e4b467cfbd6ebe5&action=position&posid=16&order=listorder+asc&num=8\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=18fbb0eabaa53df16e4b467cfbd6ebe5&action=position&posid=16&order=listorder+asc&num=8\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'16','order'=>'listorder asc','limit'=>'8',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="li"><a href="<?php echo $r['url'];?>" target="_blank"><img width="220" height="220" src="<?php echo $r['thumb'];?>">
<div class="tit"><?php echo str_cut($r['title'],16,'');?></div>
<div class="price">
<div class="jg"><i>¥<?php echo $r['coupon_price'];?></i> <span>原价:<?php echo $r['price'];?></span></div>
<div class="gm">立即抢购</div>
</div></a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
</div>
<!--1楼end -->
<div class="wrap"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=4093e54f8218586910e0c00dd8aaceb7&pos=tonglan5\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=4093e54f8218586910e0c00dd8aaceb7&pos=tonglan5\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'tonglan5',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<!--2楼 -->
<div class="wrap">
<div class="f_title">生鲜蔬果<span>新鲜采摘 原产地直供</span></div>
<div class="louceng clearfix">
<div class="cat">
<div class="img"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=659a953a17160adf731b87537f39efb6&pos=flool_2_img\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=659a953a17160adf731b87537f39efb6&pos=flool_2_img\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'flool_2_img',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<div class="cat_list"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=7e064aba180692d14472001607e9386a&pos=flool_2_list\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=7e064aba180692d14472001607e9386a&pos=flool_2_list\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'flool_2_list',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
</div>
<div class="gds">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=c739471924cf5861db43a443b596e101&action=position&posid=17&order=listorder+asc&num=8\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=c739471924cf5861db43a443b596e101&action=position&posid=17&order=listorder+asc&num=8\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'17','order'=>'listorder asc','limit'=>'8',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="li"><a href="<?php echo $r['url'];?>" target="_blank"><img width="220" height="220" src="<?php echo $r['thumb'];?>">
<div class="tit"><?php echo str_cut($r['title'],16,'');?></div>
<div class="price">
<div class="jg"><i>¥<?php echo $r['coupon_price'];?></i> <span>原价:<?php echo $r['price'];?></span></div>
<div class="gm">立即抢购</div>
</div></a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
</div>
<!--2楼end -->
<div class="wrap"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=a7810830331b94771d88a9ca1e539e9a&pos=tonglan6\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=a7810830331b94771d88a9ca1e539e9a&pos=tonglan6\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'tonglan6',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<!--3楼 -->
<div class="wrap">
<div class="f_title">南北干货<span>湖北特色干货 农家自制</span></div>
<div class="louceng clearfix">
<div class="cat">
<div class="img"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=26727d3b3d4ff4fd01126dbec9e1d1a3&pos=flool_3_img\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=26727d3b3d4ff4fd01126dbec9e1d1a3&pos=flool_3_img\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'flool_3_img',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<div class="cat_list"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=3f3e48c46ad68419417b80285afda7aa&pos=flool_3_list\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=3f3e48c46ad68419417b80285afda7aa&pos=flool_3_list\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'flool_3_list',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
</div>
<div class="gds">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=e3c0089d4d64443401b092a21315c206&action=position&posid=18&order=listorder+asc&num=8\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=e3c0089d4d64443401b092a21315c206&action=position&posid=18&order=listorder+asc&num=8\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'18','order'=>'listorder asc','limit'=>'8',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="li"><a href="<?php echo $r['url'];?>" target="_blank"><img width="220" height="220" src="<?php echo $r['thumb'];?>">
<div class="tit"><?php echo str_cut($r['title'],16,'');?></div>
<div class="price">
<div class="jg"><i>¥<?php echo $r['coupon_price'];?></i> <span>原价:<?php echo $r['price'];?></span></div>
<div class="gm">立即抢购</div>
</div></a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
</div>
<!--3楼end -->
<div class="wrap"> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=4d605b1abfdd9cbaca52be24a179e25a&pos=tonglan7\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=4d605b1abfdd9cbaca52be24a179e25a&pos=tonglan7\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'tonglan7',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<!--4楼 -->
<div class="wrap">
<div class="f_title">滋补养生<span>食疗滋补 养生佳品</span></div>
<div class="louceng clearfix">
<div class="cat">
<div class="img"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=e7e8a0437ab26dab3ba3ee19c808467d&pos=flool_4_img\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=e7e8a0437ab26dab3ba3ee19c808467d&pos=flool_4_img\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'flool_4_img',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<div class="cat_list"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=0cfb6c3957e7aa69353ab2f8a305c34a&pos=flool_4_list\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=0cfb6c3957e7aa69353ab2f8a305c34a&pos=flool_4_list\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'flool_4_list',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
</div>
<div class="gds">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=327d56447af1d5b75a32be617e3db051&action=position&posid=20&order=listorder+asc&num=8\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=327d56447af1d5b75a32be617e3db051&action=position&posid=20&order=listorder+asc&num=8\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'20','order'=>'listorder asc','limit'=>'8',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="li"><a href="<?php echo $r['url'];?>" target="_blank"><img width="220" height="220" src="<?php echo $r['thumb'];?>">
<div class="tit"><?php echo str_cut($r['title'],16,'');?></div>
<div class="price">
<div class="jg"><i>¥<?php echo $r['coupon_price'];?></i> <span>原价:<?php echo $r['price'];?></span></div>
<div class="gm">立即抢购</div>
</div></a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
</div>
<!--4楼end -->
<div class="wrap"> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=35bf18579f79f8bd3c1ef2eed536a33a&pos=tonglan8\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=35bf18579f79f8bd3c1ef2eed536a33a&pos=tonglan8\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'tonglan8',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<!--5楼 -->
<div class="wrap">
<div class="f_title">更多美食<span>限时特价 精选推荐</span></div>
<div class="louceng clearfix">
<div class="cat">
<div class="img"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=a5eade52997ba873bc12b314cf2cc9a2&pos=flool_5_img\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=a5eade52997ba873bc12b314cf2cc9a2&pos=flool_5_img\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'flool_5_img',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<div class="cat_list"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=09dc25c7748f1f92a0d4286742ebadb5&pos=flool_5_list\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=09dc25c7748f1f92a0d4286742ebadb5&pos=flool_5_list\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'flool_5_list',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
</div>
<div class="gds">
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"content\" data-datas=\"op=content&tag_md5=f8595ff29750df508abc97508396e074&action=position&posid=21&order=listorder+asc&num=8\"><a href=\"/admin.php?m=visualization&c=content&a=position&op=content&tag_md5=f8595ff29750df508abc97508396e074&action=position&posid=21&order=listorder+asc&num=8\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$content_tag = jae_base::load_app_class("content_tag", "content");if (method_exists($content_tag, 'position')) {$data = $content_tag->position(array('posid'=>'21','order'=>'listorder asc','limit'=>'8',));}?>
<?php $n=1;if(is_array($data)) foreach($data AS $r) { ?>
<div class="li"><a href="<?php echo $r['url'];?>" target="_blank"><img width="220" height="220" src="<?php echo $r['thumb'];?>">
<div class="tit"><?php echo str_cut($r['title'],16,'');?></div>
<div class="price">
<div class="jg"><i>¥<?php echo $r['coupon_price'];?></i> <span>原价:<?php echo $r['price'];?></span></div>
<div class="gm">立即抢购</div>
</div></a>
</div>
<?php $n++;}unset($n); ?>
<?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?>
</div>
</div>
</div>
<!--5楼end -->
<div class="wrap"><?php if(defined('IN_ADMIN') && !defined('HTML')) {echo "<div class=\"admin_piao\" data-action=\"block\" data-datas=\"op=block&tag_md5=6570610ef0e8dbc484cc380f75c5f36b&pos=tonglan9\"><a href=\"/admin.php?m=visualization&c=block&a=init&op=block&tag_md5=6570610ef0e8dbc484cc380f75c5f36b&pos=tonglan9\" target=\"_blank\" class=\"admin_piao_edit\">EDIT</a>";}$block_tag = jae_base::load_app_class('block_tag', 'block');echo $block_tag->jae_tag(array('pos'=>'tonglan9',));?> <?php if(defined('IN_ADMIN') && !defined('HTML')) {echo '<div style=clear:both></div></div>';}?></div>
<!-- 友链 -->
<div class="wrap">
<div class="jh">
<?php $result=query('SELECT * FROM jae_link WHERE typeid=0 AND passed=1 ORDER BY listorder ASC LIMIT 0,50 ');
foreach ($result as $v) {
?>
<a target="_blank" href="<?php echo $v['url'];?>" title="<?php echo $v['name'];?>"><img data-ks-lazyload="<?php echo $v['logo'];?>"></a>
<?php }
?>
</div>
</div>
<!-- 友链 end-->
<div style="clear:both; height:0px;"></div>
</div>
<?php include template('content','foot');?>
<file_sep>/jae/modules/order/classes/order.class.php
<?php
defined('IN_JAE') or exit('No permission resources.');
class order {
private $urlrules,$categorys,$html_root;
public function __construct() {
$this->order_db = jae_base::load_model('order_model');
$this->member_db = jae_base::load_model('member_model');
//self::set_siteid();
}
/**
* 变化积分
* @param $userid 用户ID
* @param $point 积分
* @param $title 标题
* @param $date 日期
* @param $picture 图片
* @param $description 当前页
* @param $status 积分状态
* @param $module 积分模块
*/
public function buy_order($data) {
$this->order_db->insert($data);
$sum=$this->point_db->query("select sum(point) as point from jae_point where userid=".$data['userid']);
$row = $sum->fetch();
$this->member_db->update(array('point'=>$row['point']),'userid="'.$data['userid'].'"');
}
/**
* 设置当前站点
*/
private function set_siteid() {
if(defined('IN_ADMIN')) {
$this->siteid = get_siteid();
} else {
if (param::get_cookie('siteid')) {
$this->siteid = param::get_cookie('siteid');
} else {
$this->siteid = 1;
}
}
}
}<file_sep>/jae/modules/visualization/weblink.php
<?php
defined('IN_JAE') or exit('No permission resources.');defined('IN_ADMIN') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
class weblink extends admin {
function __construct() {
parent::__construct();
$this->block_db = jae_base::load_model('block_model');
$this->weblink_db = jae_base::load_model('weblink_model');
$this->position = jae_base::load_model('position_data_model');
$this->menuid=14;
}
function init () {
$a=$_GET['op'];
}
function lists() {
$siteid = isset($data['siteid']) && intval($data['siteid']) ? intval($data['siteid']) : get_siteid();
$id = intval($_GET['id']);
$typeid = intval($_GET['typeid']);
if(isset($_GET['where'])) {
$sql = $_GET['where'];
} else {
$typeid = $typeid ? " AND typeid = '$typeid'" : '';
$id = $id ? " AND id = '$id'" : '';
$sql = "1".$id.$typeid;
}
$order = $_GET['order'];
echo $sql;
$data=$this->weblink_db->listinfo($sql,$order,$page,100);
$pages=$this->db->pages;
include $this->admin_tpl('weblink_list','weblink');
}
function content() { }
function block() {
if(isset($_POST['dosubmit'])) {
$id = intval($_POST['id']);
$data=$_POST['info'];
$_POST['info']['data']=htmlspecialchars($_POST['info']['data']);
$this->db->update($data,$this->table,'id='.$id);
showmessage(L('operation_success'));
include $this->admin_tpl('block_edit');
} else {
$id = intval($_GET['id']);
$pos =$_GET['pos'];
$r=$this->block_db->get_one(" `id`= '$id' or `pos`='$pos'");
if($r) extract($r);
include $this->admin_tpl('block_edit');
}
}
function listorder() {
if(isset($_POST['dosubmit'])) {
foreach($_POST['listorders'] as $id => $listorder) {
$listorder = !empty($listorder) ? $listorder : '0';
$this->db->update(array('listorder'=>$listorder),$this->table,'id='.$id);
$status = isset($_POST["status"][$id]) ? $_POST["status"][$id] : '0';
$this->db->update(array('status'=>$status),$this->table,'id='.$id);
}
showmessage(L('operation_success'));
} else {
showmessage(L('operation_failure'));
}
}
}
?><file_sep>/caches/caches_template/default/member/login.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php
include template('content','head');
?>
<div class="wrap">
<dl class="ui-tab clearfix" id="">
<dt>我的积分</dt>
<dd data-type="all" class="j_nativeHistory all select" data-template="/point/detail/all">积分明细</dd>
<dd data-type="income" class="j_nativeHistory income" data-template="/point/detail/income">积分收入</dd>
<dd data-type="used" class="j_nativeHistory used" data-template="/point/detail/used">积分支出</dd>
<dd data-type="expired" class="j_nativeHistory expired" data-template="/point/detail/expired">已经过期</dd>
<dd data-type="freezed" class="j_nativeHistory freezed" data-template="/point/detail/freezed">冻结积分</dd>
</dl>
<div class="border">
<div class="pd20">
<div class="content">
<div id="J_pointSummary">
<div class="summary clearfix">
<div class="item valid"><span class="desc">可用的积分</span><span class="point">0</span></div>
<div class="item expired-soon"><span class="desc">将要过期的积分</span><span class="point">0</span><span class="date"></span></div>
<div class="item exchange"><a href="/member.php" >
亲,请登录
</a></div>
</div>
</div>
<!-- point .summary END --><!-- point .detail END --></div>
<div class="blank"></div>
<div class="m_main"> </div>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<div class="blank"></div>
<file_sep>/demo/file.php
<?php
$pdo = new PDO();
$r=$pdo->prepare("update jae_order set userid=4 where userid=4");
$r->execute();
echo $r->rowCount();
$result = $cacheService->get('zhixin');
if ($result){
//echo $result;
}else{
//echo 123;
$result = $cacheService->set('zhixin', '1', '5');
}
//echo rand(1,5);
$result = $fileStoreService->saveTextFile("content", "/jae/cache/a.txt");
$result = $fileStoreService->saveTextFile("content111111111111111111111111111111", "index.html");
if( $fileStoreService->isFileExist("index.html") && $_GET['nocache']==false ){
echo $getFileTextResult = $fileStoreService->getFileText("index.html") ;
}
//$result2 = $fileStoreService->getFileText("/jae/cache/a.txt");
// print_r($result2);
?><file_sep>/jae/modules/member/templates/buyer_export.tpl.php
<?php include $this->admin_tpl('head','admin');
?>
<form name="myform" id="myform" action="/admin.php?m=member&c=buyer&a=export" method="post">
<table width="100%" class="table_form contentWrap">
<tbody>
<tr>
<th> USERID开始</th>
<td><input style="width:300px;" type="text" name="limit_start" value="" id="language" class="input-text"><div id="languageTip" class="onShow"></div></td>
</tr>
<tr>
<th width="100"> USERID结束</th>
<td><input style="width:300px;" type="text" name="limit_end" value="" id="language" class="input-text"><div id="languageTip" class="onShow"></div></td>
</tr>
</tbody></table>
<!--table_form_off-->
<div class="btns">
<input type="hidden" name="userid" value="<?php echo $userid?>"><input type="submit" id="dosubmit" class="button" name="dosubmit" value="提交"></div>
</form>
<?php include $this->admin_tpl('foot','admin');?><file_sep>/statics/js/layeranim.js
console.log('ÎÒµÄ...');
KISSY.io({
url: "test.html",
cache: false,
success: function(html){
KISSY.all(".msg").html(html);
}
});
var S = KISSY, D = S.DOM, E = S.Event;
var anim = new KISSY.LayerAnim([
{
node: '.prize-1',form: {left: 0, top: 0 },
to: { left: 123, top: 0 },
duration: 0.3, align: "sequence",
},
{
node: '.prize-2',form: { left: 0, top: 0 },
to: { left: 246, top: 0 },
duration: 0.3,
},
{
node: '.prize-3',form: { left: 0, top: 0 },
to: { left: 369, top: 0 },
duration: 0.3,
},
{
node: '.prize-4',form: { left: 0, top: 0 },
to: { left: 496, top: 0 },
duration: 0.3,
},
{
node: '.prize-5',form: { left: 0, top: 0 },
to: { left: 496, top: 105 },
duration: 0.3,
},
{
node: '.prize-6',form: { left: 0, top: 0 },
to: { left: 496, top: 210 },
duration: 0.3,
},
{
node: '.prize-7',form: { left: 0, top: 0 },
to: { left: 369, top: 210 },
duration: 0.3,
},
{
node: '.prize-8',form: { left: 0, top: 0 },
to: { left: 246, top: 210 },
duration: 0.3,
}, {
node: '.prize-9',form: { left: 0, top: 0 },
to: { left: 123, top: 210 },
duration: 0.3,
}, {
node: '.prize-10',form: { left: 0, top: 0 },
to: { left: 0, top: 210 },
duration: 0.3,
}, {
node: '.prize-11',form: { left: 0, top: 0 },
to: { left: 0, top: 105 },
duration: 0.3,
}, {
node: '.prize-12',form: { left: 0, top: 0 },
to: { left: 0, top: 0 },
duration: 0.3,
},[
{
node: '.prize-12',form: {left: 0, top: 0 },
to: { left: 123, top: 0 },
duration: 0.3, align: "sequence",
},
{
node: '.prize-1',form: { left: 0, top: 0 },
to: { left: 246, top: 0 },
duration: 0.3,
},
{
node: '.prize-2',form: { left: 0, top: 0 },
to: { left: 369, top: 0 },
duration: 0.3,
},
{
node: '.prize-3',form: { left: 0, top: 0 },
to: { left: 496, top: 0 },
duration: 0.3,
},
{
node: '.prize-4',form: { left: 0, top: 0 },
to: { left: 496, top: 105 },
duration: 0.3,
},
{
node: '.prize-5',form: { left: 0, top: 0 },
to: { left: 496, top: 210 },
duration: 0.3,
},
{
node: '.prize-6',form: { left: 0, top: 0 },
to: { left: 369, top: 210 },
duration: 0.3,
},
{
node: '.prize-7',form: { left: 0, top: 0 },
to: { left: 246, top: 210 },
duration: 0.3,
}, {
node: '.prize-8',form: { left: 0, top: 0 },
to: { left: 123, top: 210 },
duration: 0.3,
}, {
node: '.prize-9',form: { left: 0, top: 0 },
to: { left: 0, top: 210 },
duration: 0.3,
}, {
node: '.prize-10',form: { left: 0, top: 0 },
to: { left: 0, top: 105 },
duration: 0.3,
}, {
node: '.prize-11',form: { left: 0, top: 0 },
to: { left: 0, top: 0 },
duration: 0.3,
},[
{
node: '.prize-11',form: {left: 0, top: 0 },
to: { left: 123, top: 0 },
duration: 0.3, align: "sequence",
},
{
node: '.prize-12',form: { left: 0, top: 0 },
to: { left: 246, top: 0 },
duration: 0.3,
},
{
node: '.prize-1',form: { left: 0, top: 0 },
to: { left: 369, top: 0 },
duration: 0.3,
},
{
node: '.prize-2',form: { left: 0, top: 0 },
to: { left: 496, top: 0 },
duration: 0.3,
},
{
node: '.prize-3',form: { left: 0, top: 0 },
to: { left: 496, top: 105 },
duration: 0.3,
},
{
node: '.prize-4',form: { left: 0, top: 0 },
to: { left: 496, top: 210 },
duration: 0.3,
},
{
node: '.prize-5',form: { left: 0, top: 0 },
to: { left: 369, top: 210 },
duration: 0.3,
},
{
node: '.prize-6',form: { left: 0, top: 0 },
to: { left: 246, top: 210 },
duration: 0.3,
}, {
node: '.prize-7',form: { left: 0, top: 0 },
to: { left: 123, top: 210 },
duration: 0.3,
}, {
node: '.prize-8',form: { left: 0, top: 0 },
to: { left: 0, top: 210 },
duration: 0.3,
}, {
node: '.prize-9',form: { left: 0, top: 0 },
to: { left: 0, top: 105 },
duration: 0.3,
}, {
node: '.prize-10',form: { left: 0, top: 0 },
to: { left: 0, top: 0 },
duration: 0.3,
},[
{
node: '.prize-10',form: {left: 0, top: 0 },
to: { left: 123, top: 0 },
duration: 0.3, align: "sequence",
},
{
node: '.prize-11',form: { left: 0, top: 0 },
to: { left: 246, top: 0 },
duration: 0.3,
},
{
node: '.prize-12',form: { left: 0, top: 0 },
to: { left: 369, top: 0 },
duration: 0.3,
},
{
node: '.prize-1',form: { left: 0, top: 0 },
to: { left: 496, top: 0 },
duration: 0.3,
},
{
node: '.prize-2',form: { left: 0, top: 0 },
to: { left: 496, top: 105 },
duration: 0.3,
},
{
node: '.prize-3',form: { left: 0, top: 0 },
to: { left: 496, top: 210 },
duration: 0.3,
},
{
node: '.prize-4',form: { left: 0, top: 0 },
to: { left: 369, top: 210 },
duration: 0.3,
},
{
node: '.prize-5',form: { left: 0, top: 0 },
to: { left: 246, top: 210 },
duration: 0.3,
}, {
node: '.prize-6',form: { left: 0, top: 0 },
to: { left: 123, top: 210 },
duration: 0.3,
}, {
node: '.prize-7',form: { left: 0, top: 0 },
to: { left: 0, top: 210 },
duration: 0.3,
}, {
node: '.prize-8',form: { left: 0, top: 0 },
to: { left: 0, top: 105 },
duration: 0.3,
}, {
node: '.prize-9',form: { left: 0, top: 0 },
to: { left: 0, top: 0 },
duration: 0.3,
},[
{
node: '.prize-9',form: {left: 0, top: 0 },
to: { left: 123, top: 0 },
duration: 0.3, align: "sequence",
},
{
node: '.prize-10',form: { left: 0, top: 0 },
to: { left: 246, top: 0 },
duration: 0.3,
},
{
node: '.prize-11',form: { left: 0, top: 0 },
to: { left: 369, top: 0 },
duration: 0.3,
},
{
node: '.prize-12',form: { left: 0, top: 0 },
to: { left: 496, top: 0 },
duration: 0.3,
},
{
node: '.prize-1',form: { left: 0, top: 0 },
to: { left: 496, top: 105 },
duration: 0.3,
},
{
node: '.prize-2',form: { left: 0, top: 0 },
to: { left: 496, top: 210 },
duration: 0.3,
},
{
node: '.prize-3',form: { left: 0, top: 0 },
to: { left: 369, top: 210 },
duration: 0.3,
},
{
node: '.prize-4',form: { left: 0, top: 0 },
to: { left: 246, top: 210 },
duration: 0.3,
}, {
node: '.prize-5',form: { left: 0, top: 0 },
to: { left: 123, top: 210 },
duration: 0.3,
}, {
node: '.prize-6',form: { left: 0, top: 0 },
to: { left: 0, top: 210 },
duration: 0.3,
}, {
node: '.prize-7',form: { left: 0, top: 0 },
to: { left: 0, top: 105 },
duration: 0.3,
}, {
node: '.prize-8',form: { left: 0, top: 0 },
to: { left: 0, top: 0 },
duration: 0.3,
},[
{
node: '.msg',form: { left: 0, top: 0 , height:0 , opacity: 0.2 , },
to: { left: 0, top: 0, height : 315 , opacity: 0.95 , },
duration: 0.3,
},
]
]
]
]
]
]);
var msg = D.get('.msg');
// event
anim.on('start', function() {
//msg.innerHTML = 'anim start ...';
});
anim.on('update', function() {
// msg.innerHTML = 'anim update ... ';
});
anim.on('end', function() {
// msg.innerHTML = 'anim end ...';
});
// method
E.on('.run', 'click', function() {
anim.run();
});
anim.run();
<file_sep>/jae/modules/apply/index.php
<?php
defined('IN_JAE') or exit('No permission resources.');
jae_base::load_app_class('foreground');
class index {
private $db;
function __construct() {
$this->db = new PDO();
}
//活动报名首页
public function init() {
//获取站点配置信息
$siteinfo=siteinfo(SITEID);
$appkey =$siteinfo['appkey'];
$secret =$siteinfo['secretkey'];
jae_base::load_top('topclient');
jae_base::load_top('ItemGetRequest');
//初始化变量
$pindaoArr = rGetPindaoArr();
$categoryArr = rGetCategoryArr();
$dopost = isset($_POST['dopost']) ? $_POST['dopost'] : '';
$createMessage='';
$begin_time = isset($_POST['begin_time']) ? strtotime($_POST['begin_time']) : time();
$end_time = isset($_POST['end_time']) ? strtotime($_POST['end_time']) : time()+604800;
$detail_url = isset($_POST['detail_url']) ? $_POST['detail_url'] : '';
$freight_payer = isset($_POST['freight_payer']) ? $_POST['freight_payer'] : '';
$nick = isset($_POST['nick']) ? $_POST['nick'] : '';
$price = isset($_POST['price']) ? $_POST['price'] : 0;
$coupon_price = isset($_POST['coupon_price']) ? $_POST['coupon_price'] : 0;
$num = isset($_POST['num']) ? $_POST['num'] : 0;
$pic_url = isset($_POST['pic_url']) ? $_POST['pic_url'] : '';
$category_id = isset($_POST['category_id']) ? $_POST['category_id'] : 0;
$title = isset($_POST['title']) ? $_POST['title'] : '';
$desctiption = isset($_POST['desctiption']) ? $_POST['desctiption'] : '';
$pindao_id =isset($_POST['pindao_id']) ? $_POST['pindao_id'] : 0;
$num_iid = isset($_POST['num_iid']) ? trim($_POST['num_iid']) : '';
if ($dopost == 'caiji')
{
if ($num_iid != "" && rRuleNum($num_iid))
{
$c = new TopClient;
$c->appkey = $appkey; //top appkey
$c->secretKey = $secret; //top secretkey
//实例化具体API对应的Request类
$req = new ItemGetRequest(); //top 封装的php文件
$req->setFields("num_iid,title,pic_url,detail_url,price,num,nick,freight_payer");
$req->setNumIid($num_iid);
$resp = $c->execute($req);
if ($resp->item)
{
$detail_url = $resp->item->detail_url; //商品链接
$num_iid = $resp->item->num_iid; //商品ID
$title = $resp->item->title; //商品标题
$nick = $resp->item->nick; //卖家昵称
$pic_url = $resp->item->pic_url; //商品主图
$num = $resp->item->num; //商品数量
$price = $resp->item->price; //商品原价格
$freight_payer = $resp->item->freight_payer; //商品原价格
}else
$createMessage = '不存在这个商品';
}
else
{
$createMessage = "商品ID【不能为空】并且【必须是数字】。";
}
}
if ($dopost == 'create')
{
if($end_time-$begin_time>604800){
$createMessage = '失败!促销时间不能超过七天,请填写正确的开始时间和结束时间';
}
elseif ($num_iid == "" || $detail_url == "" || $title == "" || $pic_url == "" || $price == "" || $coupon_price == "" || intval($coupon_price)==0)
{
$createMessage = "失败!请把商品信息填写完整,星号为必填项!!";
}
else
{
$sql1 = 'SELECT * FROM `jae_goods` WHERE `num_iid`="' . $num_iid . '" OR `title`="' . $title . '"';
$pdo=new PDO();
$rs1 = $pdo->query($sql1);
$row1 = $rs1->fetchAll(); //取得所有记录
$sql2 = 'SELECT * FROM `jae_goods` WHERE `num_iid`="' . $num_iid . '" OR `title`="' . $title . '"';
$rs2 = $pdo->query($sql2);
$row2 = $rs2->fetchAll(); //取得所有记录
if (count($row1)+count($row2) == 0)
{
if (rRuleUrl($detail_url) && rRuleNum($num_iid) && rRulePrice($price) && rRulePrice($coupon_price))
{
$datetime = date("Y-m-d H:i:s");
$sql = 'INSERT INTO `jae_goods` SET `num_iid`="' . $num_iid . '", `title`="' . $title .
'", `pic_url`="' . $pic_url . '", `detail_url`="' . $detail_url . '", `price`="' . $price .
'", `coupon_price`="' . $coupon_price . '", `num`="' . $num . '", `create_time`="' . time() .
'", `description`="' . $description . '", `category_id`="' . $category_id .
'", `end_time`="' . $end_time . '", `freight_payer`="' . $freight_payer .
'", `nick`="' . $nick . '", `begin_time`="' . $begin_time . '", `pindao_id`="' . $pindao_id . '"';
$count = $pdo->exec($sql);
if ($count > 0)
{
$createMessage = "新增成功";
}
else
{
echo $sql;
$createMessage = "添加失败";
}
}
else
{
if (!rRuleUrl($detail_url))
$createMessage.='商品链接url填写不规范,带http://模式<br>';
elseif (!rRuleNum($num_iid))
$createMessage.='商品id填写不规范,数字模式<br>';
elseif (!rRulePrice($price))
$createMessage.='商品价格填写不规范,小数模式:10.00<br>';
elseif (!rRulePrice($coupon_price))
$createMessage.='促销价格填写不规范,小数模式:10.00<br>';
}
}
else
{
$createMessage = "商品已经存在【同一id或者同一标题】!!";
}
}
}
include template('apply','index');
}
}
?><file_sep>/jae/modules/prize/prize_set.php
<?php
defined('IN_JAE') or exit('No permission resources.');
defined('IN_ADMIN') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
jae_base::load_app_func('global','admin');
class prize_set extends admin {
public function __construct() {
parent::__construct();
$this->db = jae_base::load_model('prize_set_model');
$this->menuid=34;
}
public function init () {
$prize_type=jae_base::load_config('prize_type');
$where=1;
$page=$_GET['page'];
$data=$this->db->listinfo($where,$order = 'listorder,id DESC',$page, $pages = '20');
$pages=$this->db->pages;
include $this->admin_tpl('prize_set');
}
function add() {
if(isset($_POST['dosubmit'])) {
$data=$_POST['info'];
$this->db->insert($data);
showmessage(L('add_success'));
} else {
$prize_type=jae_base::load_config('prize_type');
include $this->admin_tpl('prize_set_add');
}
}
function delete() {
$_GET['id'] = intval($_GET['id']);
$this->db->delete('id='.$_GET['id']);
showmessage(L('operation_success'));
}
function edit() {
if(isset($_POST['dosubmit'])) {
$id = intval($_POST['id']);
$data=$_POST['info'];
$this->db->update($data,'id='.$id);
showmessage(L('operation_success'));
} else {
$prize_type=jae_base::load_config('prize_type');
$id = intval($_GET['id']);
$r=$this->db->get_one('id='.$id ,'*');
if($r) extract($r);
include $this->admin_tpl('prize_set_edit');
}
}
function listorder() {
if(isset($_POST['dosubmit'])) {
foreach($_POST['listorders'] as $id => $listorder) {
$listorder = !empty($listorder) ? $listorder : '0';
$this->db->update(array('listorder'=>$listorder),'id='.$id);
$status = isset($_POST["status"][$id]) ? $_POST["status"][$id] : '0';
$this->db->update(array('status'=>$status),'id='.$id);
}
showmessage(L('operation_success'));
} else {
showmessage(L('operation_failure'));
}
}
}<file_sep>/caches/caches_template/default/prize/rules.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php
include template('content','head');
?>
<link href="/statics/css/prize.css" rel="stylesheet" type="text/css" />
<div class="page-rules page-content">
<div class="head" style="background:<?php echo $data['bg_color']?>">
<div class="head-logo"><img src="<?php echo $data['bg_img'] ?>">
</div>
</div>
<div class="bcontent-wrap">
<div class="rules-content">
<h1>³é½±¹æÔò£º</h1>
<div class="rules-list">
<?php echo htmlspecialchars_decode($data['rules']);?>
</div>
</div>
</div>
</div>
<file_sep>/jae/modules/admin/templates/goods_edit.tpl.php
<?php include $this->admin_tpl('head'); ?>
<font color="red"><?php echo $message;?></font>
<form name="form2" method="post" action="/admin.php?m=admin&c=goods&a=edit">
<table class="table_form" cellpadding="0" cellspacing="0" border="0">
<tr>
<th> 商品分类: </th>
<td width="380"><select name="info[category_id]">
<option value="0">无分类</option>
<?php
foreach($categoryArr as $catId=>$catName){; ?>
<option value="<?php echo $catId; ?>" <?php if($catId==$category_id) echo "selected";?> ><?php echo $catName; ?></option>
<?php }; ?>
</select></td>
<td></td>
</tr>
<tr>
<th width="140">*商品链接:</th>
<td><input class="input-text" type="text" name="info[detail_url]" size="50" value="<?php echo $detail_url; ?>"></td>
</tr>
<tr>
<th width="140">*店铺链接:</th>
<td><input class="input-text" type="text" name="info[shop_url]" size="50" value="<?php echo $shop_url; ?>"></td>
</tr>
<tr>
<th>*商品标题:</th>
<td><input class="input-text" type="text" name="info[title]" size="50" value="<?php echo $title; ?>"></td>
<td rowspan="12" valign="top"><a target="_blank" href="<?php echo $detail_url; ?>"><img border="0" src="<?php echo $pic_url; ?>" width="200" height="200" /><br>
商品图片预览(点击跳到详情页面)</a></td>
</tr>
<tr>
<th width="145">是否显示图标:</th>
<td><label>
<input class="input-text" type="radio" name="info[isicon]" size="50" <?php if($isicon==1) echo "checked"?> value="1">
是 </label>
<label>
<input class="input-text" type="radio" name="info[isicon]" size="50" <?php if($isicon==0) echo "checked"?> value="0">
否</label></td>
</tr>
<tr>
<th width="145">图标图片地址:</th>
<td><input class="input-text" type="text" name="info[icon_url]" size="50" value="<?php echo $icon_url; ?>"></td>
</tr>
<tr>
<th>*商品图片:</th>
<td><input class="input-text" type="text" name="info[pic_url]" size="50" value="<?php echo $pic_url; ?>"></td>
</tr>
<tr>
<th>*上线时间段:</th>
<td><ul>
<li>
<label class="tit" for="J_DepDate">开始时间:</label>
<input name="info[begin_time]" class="kg_datePicker input-text" type="text" value="<?php echo date('Y-m-d H:i:s',$begin_time); ?>"/>
</li>
<li>
<label class="tit" for="J_RetDate">结束时间:</label>
<input name="info[end_time]" class="kg_datePicker input-text" type="text" value="<?php echo date('Y-m-d H:i:s',$end_time); ?>"/>
</li>
</ul></td>
</tr>
<tr>
<th>*包邮:</th>
<td><select name="info[freight_payer]">
<option<?php if($freight_payer=='seller'){?> selected="selected"<?php }; ?> value="seller">是</option>
<option<?php if($freight_payer=='buyer'){?> selected="selected"<?php }; ?> value="buyer">否</option>
</select>
</tr>
<tr>
<th>*商家昵称:</th>
<td><input class="input-text" type="text" name="info[nick]" size="50" value="<?php echo $nick; ?>"></td>
</tr>
<tr>
<th>*商品原价:</th>
<td><input class="input-text" type="text" name="info[price]" size="50" value="<?php echo $price; ?>"></td>
</tr>
<tr>
<th>*商品现价:</th>
<td><input class="input-text" type="text" name="info[coupon_price]" value="<?php echo $coupon_price; ?>" /></td>
</tr>
<tr>
<th>*商品数量:</th>
<td><input class="input-text" type="text" name="info[num]" size="50" value="<?php echo $num; ?>"></td>
</tr>
<tr>
<th>商品推荐位:</th>
<td colspan="2"><?php foreach ($position_array as $posid => $name) : ?>
<div style="padding:0 3px; margin:5px; float:left; border:1px solid #eee;">
<label>
<input name="posids[]" type="checkbox" value="<?php echo $posid; ?>" <?php if(in_array($posid,$posids_array)) echo "checked";?> >
<?php echo $name; ?> </label>
</div>
<?php endforeach ?></td>
</tr>
</table>
<div class="btns">
<input name="id" type="hidden" value="<?php echo $id?>">
<input type="submit" id="dosubmit" class="button" name="dosubmit" value="提交">
</div>
</form>
<?php include $this->admin_tpl('foot');?>
<file_sep>/jae/modules/brand/brand.php
<?php
defined('IN_JAE') or exit('No permission resources.');defined('IN_ADMIN') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
class brand extends admin {
function __construct() {
parent::__construct();
$this->db =jae_base::load_sys_class('mysql');
$this->table='jae_brand';
$this->type='jae_brand_type';
$this->menuid=48;
}
function init () {
$type=$this->db->select('*',$this->type);
$name=$_GET['name'];
$typeid=$_GET['typeid'];
$where =" 1 ";
if(!empty($typeid)) $where.= " AND typeid=".$typeid;
$page=$_GET['page'];
$data=$this->db->listinfo("*",$this->table,$where,"brandid DESC",$page,10);
$pages=$this->db->pages;
include $this->admin_tpl('brand_list');
}
function add() {
if(isset($_POST['dosubmit'])) {
$data=$_POST['info'];
$this->db->insert($data,$this->table);
include $this->admin_tpl('brand_add');
showmessage(L('add_success'));
} else {
$type=$this->db->select('*',$this->type);
include $this->admin_tpl('brand_add');
}
}
function delete() {
$_GET['brandid'] = intval($_GET['brandid']);
$this->db->delete($this->table,'brandid='.$_GET['brandid']);
showmessage(L('operation_success'));
}
function edit() {
if(isset($_POST['dosubmit'])) {
$brandid = intval($_POST['brandid']);
$data=$_POST['info'];
$this->db->update($data,$this->table,'brandid='.$brandid);
showmessage(L('operation_success'));
include $this->admin_tpl('brand_edit');
} else {
$brandid = intval($_GET['brandid']);
$r=$this->db->get_one('*',$this->table,'brandid='.$brandid); $type=$this->db->select('*',$this->type);
if($r) extract($r);
include $this->admin_tpl('brand_edit');
}
}
function listorder() {
if(isset($_POST['dosubmit'])) {
foreach($_POST['listorders'] as $brandid => $listorder) {
$listorder = !empty($listorder) ? $listorder : '0';
$this->db->update(array('listorder'=>$listorder),$this->table,'brandid='.$brandid);
echo $passed = isset($_POST["passed"][$brandid]) ? $_POST["passed"][$brandid] : '0';
$this->db->update(array('passed'=>$passed),$this->table,'brandid='.$brandid);
}
showmessage(L('operation_success'));
} else {
showmessage(L('operation_failure'));
}
}
}
?><file_sep>/jae/modules/admin/templates/category_add.tpl.php
<?php include $this->admin_tpl('head');
?>
<form name="myform" id="myform" action="/admin.php?m=admin&c=category&a=add" method="post">
<table width="100%" class="table_form ">
<tr>
<th width="200"><?php echo L('select_model')?>£؛</th>
<td>
<?php
$model_datas = array();
foreach($models as $_k=>$_v) {
//if($_v['siteid']!=$this->siteid) continue;
$model_datas[$_v['modelid']] = $_v['name'];
}
echo form::select($model_datas,$modelid,'name="info[modelid]" id="modelid" onchange="change_tpl(this.value)"',L('select_model'));
?>
</td>
</tr>
<tr>
<th width="200"><?php echo L('parent_category')?>£؛</th>
<td> <?php echo form::select_category('category_content_'.$this->siteid,$parentid,'name="info[parentid]"',L('please_select_parent_category'),0,-1);?>
</td>
</tr>
<tr>
<th><?php echo L('catname')?>£؛</th>
<td>
<span id="normal_add"><input type="text" name="info[catname]" id="catname" class="input-text" value=""></span>
<span id="batch_add" style="display:none">
<table width="100%" class="sss"><tr><td width="310"><textarea name="batch_add" maxlength="255" style="width:300px;height:60px;"></textarea></td>
<td align="left">
<?php echo L('batch_add_tips');?>
</td></tr></table>
</span>
</td>
</tr>
<tr id="catdir_tr">
<th><?php echo L('catdir')?>£؛</th>
<td><input type="text" name="info[catdir]" id="catdir" class="input-text" value=""></td>
</tr>
<tr>
<th><?php echo L('catgory_img')?>£؛</th>
<td><input type="text" name="info[image]" id="catdir" class="input-text" value=""></td>
</tr>
<tr>
<th><?php echo L('description')?>£؛</th>
<td>
<textarea name="info[description]" maxlength="255" style="width:300px;height:60px;"><?php echo $description;?></textarea>
</td>
</tr>
<tr>
<th><?php echo L('ismenu');?>£؛</th>
<td> <input type='hidden' name='info[type]' value='0'> <input type='hidden' name='info[module]' value='content'>
<input type='radio' name='info[ismenu]' value='1' checked> <?php echo L('yes');?>
<input type='radio' name='info[ismenu]' value='0' > <?php echo L('no');?></td>
</tr>
</table>
<!--table_form_off-->
<div class="btns"><input type="submit" id="dosubmit" class="button" name="dosubmit" value="جل½»"></div>
</form>
<?php include $this->admin_tpl('foot');?><file_sep>/jae/modules/weblink/weblink.php
<?php
defined('IN_JAE') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
class weblink extends admin {
function __construct() {
parent::__construct();
$this->db =jae_base::load_sys_class('mysql');
$this->table='jae_weblink';
$this->type='jae_weblink_type';
$this->menuid=13;
}
function init () {
$sitelist=getcache('sitelist','commons');
$type=$this->db->select('*',$this->type);
$typeid=$_POST['info']['typeid'];
$kw=$_POST['kw'];
$where =1;
if(!empty($typeid)) $where.= " AND typeid='$typeid'";
if(!empty($kw)) $where.= " AND title like '%$kw%'";
$page=$_GET['page'];
$data=$this->db->listinfo("*",$this->table,$where,"listorder,id DESC",$page,100);
$pages=$this->db->pages;
include $this->admin_tpl('weblink_list','weblink');
}
function add() {
$sitelist=getcache('sitelist','commons');
if(isset($_POST['dosubmit'])) {
$data=$_POST['info'];
$data['siteid']=get_siteid();
$this->db->insert($data,$this->table);
include $this->admin_tpl('weblink_add');
showmessage(L('add_success'));
} else {
$typeid=$_GET['typeid'];
$type=$this->db->select('*',$this->type);
include $this->admin_tpl('weblink_add','weblink');
}
}
function delete() {
$_GET['id'] = intval($_GET['id']);
$this->db->delete($this->table,'id='.$_GET['id']);
showmessage(L('operation_success'));
}
function edit() {
$sitelist=getcache('sitelist','commons');
if(isset($_POST['dosubmit'])) {
$id = intval($_POST['id']);
$data=$_POST['info'];
$this->db->update($data,$this->table,'id='.$id);
showmessage(L('operation_success'));
include $this->admin_tpl('weblink_edit');
} else {
$type=$this->db->select('*',$this->type);
$id = intval($_GET['id']);
$r=$this->db->get_one('*',$this->table,'id='.$id);
if($r) extract($r);
include $this->admin_tpl('weblink_edit');
}
}
function listorder() {
if(isset($_POST['dosubmit'])) {
foreach($_POST['listorders'] as $id => $listorder) {
$listorder = !empty($listorder) ? $listorder : '0';
$this->db->update(array('listorder'=>$listorder),$this->table,'id='.$id);
}
foreach($_POST['link'] as $id =>$link) {
$this->db->update(array('link'=>$link),$this->table,'id='.$id);
}
foreach($_POST['title'] as $id =>$title) {
$this->db->update(array('title'=>$title),$this->table,'id='.$id);
}
foreach($_POST['picture'] as $id =>$picture) {
$this->db->update(array('picture'=>$picture),$this->table,'id='.$id);
}
foreach($_POST['description'] as $id =>$description) {
$this->db->update(array('description'=>$description),$this->table,'id='.$id);
}
showmessage(L('operation_success'));
} else {
showmessage(L('operation_failure'));
}
}
}
?><file_sep>/jae/modules/order/index.php
<?php
defined('IN_JAE') or exit('No permission resources.');
jae_base::load_app_class('foreground','member');
jae_base::load_app_func('global');
class index extends foreground {
public function __construct() {
$this->exchange_db = jae_base::load_model('exchange_model');
$this->seckill_db = jae_base::load_model('seckill_model');
$this->seckill_person_db = jae_base::load_model('seckill_person_model');
$this->order_db = jae_base::load_model('order_model');
$this->point_db = jae_base::load_model('point_model');
$this->prize_db = jae_base::load_model('prize_model');
$this->member_db = jae_base::load_model('member_model');
$this->point =jae_base::load_app_class('point','point');
$this->point_db = jae_base::load_model('point_model');
parent::__construct();
}
public function init() {
$memberinfo = $this->memberinfo;
$order_follow=array(1=>'未支付',2=>'提交订单',3=>'已提交订单',4=>'未发货',5=>'发货',6=>'已发货',7=>'未确认收货',8=>'确认收货',9=>'已确认收货',10=>'已确认收货');
$modules=array('exchange'=>'积分换购','seckill'=>'积分整点聚');
$where=" userid=".$memberinfo['userid'];
$page=$_GET['page'];
$data=$this->order_db->listinfo($where,$order = 'id DESC',$page, $pages = '10');
$pages=$this->order_db->pages;
include template('order','order_list');
}
public function convert() {
$memberinfo = $this->memberinfo;
$id = intval($_GET['id']);
$module = $_GET['module'];
$r=$this->exchange_db ->get_one('id='.$id);
if($r) extract($r);
include template('order','convert');
}
public function submit() {
$memberinfo = $this->memberinfo;
$id = intval($_POST['id']);
$module = 'exchange';
$auction_num = intval($_POST['auction_num']);
$v=$this->exchange_db ->get_one('id='.$id);if($v) extract($v);
if (SYS_TIME < $begin_time){ showmessage(L('活动还未开始'),$detail_url,3); exit();}
if (SYS_TIME > $end_time) { showmessage(L('活动已经结束'),$detail_url,3); exit();}
$modules=array('exchange'=>'积分换购活动','seckill'=>'积分秒杀活动');
$auction_point=$point*$auction_num;
if($memberinfo['point']>=$auction_point && $num>=$auction_num ) {
$info=array('userid'=>$memberinfo['userid'],'point'=>'-'.$auction_point,'title'=>$title,'date'=>SYS_TIME,'picture'=>$pic_url,'description'=>$modules[$module],'module'=>$module);
$this->point->change_point($info);//更新积分明细
$this->exchange_db->update(array('num'=>$num-$auction_num),'id='.$id);
$order_info=array('userid'=>$memberinfo['userid'],'point'=>$auction_point,'title'=>$title,'date'=>SYS_TIME,'picture'=>$pic_url,'description'=>$description,'sellerid'=>$userid,'status'=>'2', 'url'=>$detail_url,'price'=>$price,'goodsid'=>$id,'module'=>$module);
$this->order_db->insert($order_info);
showmessage(L('operation_success'),"/index.php?m=order&c=index&a=init");
}
else {
showmessage(L('积分不足或商品数量不足,直接去购买吧'),$detail_url,3);
}
}
public function seckill_submit_pre() {
$id = intval($_POST['id']);
$goods=$this->seckill_db ->get_one('id='.$id);
if (SYS_TIME < $goods['begin_time']){ showmessage(L('活动还未开始'),$goods['detail_url'],3); exit();}
if (SYS_TIME > $goods['end_time']) { showmessage(L('活动已经结束'),$goods['detail_url'],3); exit();}
if ($goods['num']==0) {showmessage(L('很遗憾!您手太慢了,商品已经被秒杀完了!直接去购买吧!'),$goods['detail_url']); exit();}
include template('order','convert_seckill');
}
public function seckill_submit() {
$memberinfo = $this->memberinfo;
$modules=array('seckill'=>'积分整点聚活动');
$id = intval($_POST['id']);
$module = 'seckill';
$goods=$this->seckill_db ->get_one('id='.$id);
if (empty($_POST['answer']) ) { showmessage(L('答案不能为空'),$goods['detail_url'],3); exit();}
if ($goods['answer'] != $_POST['answer']){ showmessage(L('答案错误'),$goods['detail_url'],3); exit();}
if (SYS_TIME < $goods['begin_time']){ showmessage(L('活动还未开始'),$goods['detail_url'],3); exit();}
if (SYS_TIME > $goods['end_time']) { showmessage(L('活动已经结束'),$goods['detail_url'],3); exit();}
if ($goods['num']==0) {showmessage(L('很遗憾!您手太慢了,商品已经被秒杀完了!直接去购买吧!'),$goods['detail_url'],3); exit();}
if($memberinfo['point']<$goods['point'] ) {showmessage(L('积分不够!'),$goods['detail_url'],3); exit();}
$m=rand(0,3);
sleep($m);
/*秒杀用户排队*/
$this->seckill_person_db->insert(array('userid'=>$memberinfo['userid'],'username'=>$memberinfo['username'],'goodsid'=>$id,'date'=>MICRO_TIME,'regdate'=>SYS_TIME,'begin_time'=>$goods['begin_time'],'end_time'=>$goods['end_time']));
/*秒杀用户排队END*/
/*获取秒杀到的用户信息*/
$person=$this->seckill_person_db->get_one("goodsid=$id AND begin_time = ".$goods['begin_time']." AND end_time = ".$goods['end_time']." ORDER BY id ASC ");
/*获取秒杀到的用户信息END*/
$result = $cacheService->get('zhixin');
if ($result){
showmessage(L('很遗憾!您手太慢了,商品已经被秒杀完了!直接去购买吧!'),$goods['detail_url']); exit();
//echo $result; 并发提示
}else{
$result = $cacheService->set('zhixin', '1', '10'); //生成并发阻止
/*只要在当天秒杀到一个就不能再秒杀第二个*/
$begin_time= strtotime(date('Y-m-d',SYS_TIME))-186400;
$end_time =SYS_TIME;
$zj=$this->order_db->get_one("userid=$person[userid] AND module = 'seckill' AND date >$begin_time AND date<$end_time ");
if (!empty($zj['id'])){
$this->seckill_db->update(array('num'=>$goods['num']-1),'id='.$id);//减少商品数量
$this->order_db->insert(array('userid'=>1,'point'=>$goods['point'],'title'=>$goods['title'],'date'=>SYS_TIME,'picture'=>$goods['pic_url'],'description'=>$memberinfo['userid'],'sellerid'=>$goods['userid'],'status'=>'2', 'url'=>$goods['detail_url'],'price'=>$goods['price'],'goodsid'=>$goods['id'],'module'=>$module));
showmessage(L('很遗憾!您手太慢了,商品已经被秒杀完了!直接去购买吧!'),$goods['detail_url'],3); exit();
}
/*只要在当天秒杀到一个就不能再秒杀第二个END*/
//系统参与秒杀了
if($goods['iskill']==1){
$this->seckill_db->update(array('num'=>$goods['num']-1),'id='.$goods['id']);//减少商品数量
$this->order_db->insert(array('userid'=>2,'point'=>$goods['point'],'title'=>$goods['title'],'date'=>SYS_TIME,'picture'=>$goods['pic_url'],'description'=>$memberinfo['userid'],'sellerid'=>$goods['userid'],'status'=>'2', 'url'=>$goods['detail_url'],'price'=>$goods['price'],'goodsid'=>$goods['id'],'module'=>$module));
showmessage(L('很遗憾!您手太慢了,商品已经被秒杀完了!直接去购买吧'),$goods['detail_url'],3);exit();
}
//系统参与秒杀结束
/*成功秒杀*/
$this->seckill_person_db->update(array('iswin'=>1),'id='.$person['id']);
$this->seckill_db->update(array('num'=>$goods['num']-1),'id='.$goods['id']);//减少商品数量
$order_info=array('userid'=>$person['userid'],'point'=>$goods['point'],'title'=>$goods['title'],'date'=>SYS_TIME,'picture'=>$goods['pic_url'],'description'=>$goods['description'],'sellerid'=>$goods['userid'],'status'=>'2', 'url'=>$goods['detail_url'],'price'=>$goods['price'],'goodsid'=>$goods['id'],'module'=>$module);
$this->order_db->insert($order_info);
$order_result= $this->order_db->get_one(" goodsid=$goods[id] and module='seckill' order by id asc ");
//$this->order_db->update(array('userid'=>3), "id != $order_result[id] AND goodsid=$goods[id] and module='seckill' ");//替换多余订单
//if( $this->order_db->affected_rows() ) {showmessage(L('很遗憾!您手太慢了,商品已经被秒杀完了!直接去购买吧'),$goods['detail_url']);exit();}
$info=array('userid'=>$order_result['userid'],'point'=>'-'.$goods['point'],'title'=>$goods['title'],'date'=>$goods['begin_time'],'picture'=>$goods['pic_url'],'description'=>$modules[$module],'module'=>$module);//扣除积分
$this->point->change_point($info);//更新积分明细
//$point_result= $this->point_db->get_one(" userid=$order_result[userid] and module='seckill' and date = $goods[begin_time] order by id asc ");
//$this->point_db->delete( "id != $point_result[id] AND date=$goods[begin_time] and module='seckill' ");//删除被替换订单会员所扣积分
//$this->point->update_point($point_result['id']);//更新积分明细
if($memberinfo['userid']==$order_result['userid']){
showmessage(L('operation_success'),"/index.php?m=order&c=index&a=init");
}else { showmessage(L('很遗憾!您手太慢了,商品已经被秒杀完了!直接去购买吧'),$goods['detail_url'],3);exit();}
/*成功秒杀*/
}
}
public function receive() {
$memberinfo = $this->memberinfo;
$id = intval($_GET['id']);
$this->order_db->update(array('status'=>'8'),'id='.$id);//更新订单状态
}
}
?><file_sep>/caches/caches_template/default/point/point.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php
include template('content','head');
?>
<link href="/statics/css/member.css" rel="stylesheet" type="text/css" />
<div class="blank"></div>
<div class="wrap">
<dl class="ui-tab clearfix" id="">
<dt>我的积分</dt>
<dd data-type="all" class="j_nativeHistory all <?php if($trad=='all') echo "select"?> " data-template=""><a href="/index.php?m=point&c=index&a=sign&trad=all">积分明细</a></dd>
<dd data-type="income" class="j_nativeHistory income <?php if($trad=='income') echo "select"?>" data-template="/point/detail/income"><a href="/index.php?m=point&c=index&a=sign&trad=income ">积分收入</a></dd>
<dd data-type="used" class="j_nativeHistory used <?php if($trad=='used') echo "select"?>" data-template="/point/detail/used"><a href="/index.php?m=point&c=index&a=sign&trad=used">积分支出</a></dd>
<dd data-type="expired" class="j_nativeHistory expired" data-template="/point/detail/expired"><a href="/index.php?m=point&c=index&a=point_task" target="_blank">积分任务说明</a></dd>
<!-- <dd data-type="freezed" class="j_nativeHistory freezed" data-template="/point/detail/freezed">冻结积分</dd>-->
</dl>
<div class="border">
<div class="pd20">
<div class="content">
<div id="J_pointSummary">
<div class="summary clearfix">
<div class="item valid"><span class="desc">可用的积分</span><span class="point" style="color:#C00"><?php echo $memberinfo['point']?></span></div>
<div class="item expired-soon"><span class="desc">已经消耗的积分</span><span class="point"><?php if($pointeds['point'])echo $pointeds['point']; else echo 0 ?></span><span class="date"><!--2014年12月31日--></span></div>
<div class="item exchange"><?php echo $msg?><a href="/index.php?m=point&c=index&a=sign" >签到 赢积分</a></div>
</div>
</div>
<?php if (!empty($invite_sum)){?>
<div class="check_tips"><?php echo $tips="您已邀请了<b style='color:#f00; font-size:14px; '>".$invite_sum. "</b>位好友成为会员,正在审核中……。由于近期有大量用户邀请自己的小号会员刷积分,我们将会通过淘宝大数据与人工来做双重审核,次日内审核完毕(遇非工作日,时间顺延)。";?></div>
<?php }?>
<!-- point .summary END -->
<div class="detail">
<div class="masthead clearfix"><span class="why">来源/用途</span><span class="what">积分变化</span><span class="when">日期</span><span class="notes">备注</span></div>
<div id="J_pointDetail">
<ul class="item-list" id="J_item-list">
<?php foreach ($data as $v){?>
<li class="item clearfix">
<div class="why"><a class="img" href="javascript:void(0);"><img src="<?php echo $v['picture']?>" width="60" height="60" alt="小积分抽大奖"></a><a class="title" href="javascript:void(0);"><?php echo $v['title']?></a><span class="order-number">编号:<?php echo $v['id']?></span></div>
<div class="what"><span class=" <?php if ($v['point']>0) echo "plus"; else echo "minus";?> "><?php echo $v['point']?></span></div>
<div class="when"><?php echo date('Y-m-d H:i:s',$v['date'])?></div>
<div class="notes"><?php echo $v['description']?></div>
</li>
<?php }?>
</ul>
</div>
<div id="J_pointError" class="hidden error"></div>
<div id="J_pointPager" class="pages">
<?php echo $pages;?>
</div>
</div>
<!-- point .detail END --></div>
<div class="blank"></div>
<div class="m_main"> </div>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<div class="blank"></div>
<file_sep>/jae/modules/prize/templates/prize_list.tpl.php
<?php include $this->admin_tpl('head','admin');?>
<form name="myform" action="/admin.php?m=prize&c=prize_set&a=listorder" method="post">
<div class="pad-lr-10">
<div class="table-list">
<table width="100%" cellspacing="0" class="table_form">
<tbody>
<tr class="thead">
<th width="20">ID</th>
<th width="100">标题</th>
<th width="60">图片</th>
<th width="120">描述</th>
<th width="60">中奖人姓名</th>
<th width="100">中奖人旺旺</th>
<th width="80">中奖人电话</th>
<th width="100">中奖人地址</th>
<th width="100">奖品是否发送</th>
<th width="100">快递名称 </th>
<th width="100">快递单号 </th>
<th width="100">时间 </th>
<th align="center"><?php echo L('operations_manage');?></th>
</tr>
<?php foreach ($data as $v){?>
<tr>
<td align="center"><?php echo $v['id'];?></td>
<td ><?php echo $v['title']?></td>
<td align="center"><img src="<?php echo $v['picture']?>" height="60"></td>
<td ><?php echo $v['description']?></td>
<td align="center" ><?php echo get_memberinfo($v['userid'],'nickname')?></td>
<td align="center" ><?php echo get_memberinfo($v['userid'],'wangwang')?></td>
<td align="center" ><?php echo get_memberinfo($v['userid'],'mobile')?></td>
<td align="center" ><?php echo get_memberinfo($v['userid'],'address')?></td>
<td align="center" ><?php if( $v['status']==0) echo "未发"; elseif ( $v['status']==1) echo "已发" ;else "已收" ?></td>
<td align="center" ><?php echo $v['express_name']?></td>
<td align="center" ><?php echo $v['express_num']?></td>
<td><?php echo date("m-d H:i",$v['date'])?></td>
<td align="center"><?php echo '<a href="/admin.php?m=prize&c=prize&a=edit&id='.$v['id'].'&menuid='.$menuid.'">'.L('发货').'</a> | <a href="/admin.php?m=prize&c=prize&a=delete&id='.$v['id'].'&menuid='.$menuid.'">'.L('delete').'</a> ';?></td>
</tr>
<?php }?>
</tbody>
</table>
<div class="btns">
<input type="submit" class="button" name="dosubmit" value="<?php echo L('submit')?>" />
</div>
</div>
</div>
</div>
</form>
<div class="pages"><?php echo $pages;?></div>
<?php include $this->admin_tpl('foot','admin');?>
<file_sep>/jae/modules/admin/templates/shop_edit.tpl.php
<?php include $this->admin_tpl('head');?>
<form name="myform" id="myform" action="/admin.php?m=admin&c=shop&a=edit" method="post">
<table class="admin-form-table" cellpadding="0" cellspacing="0" border="0">
<tr>
<th width="145">店家昵称:</th>
<td width="380">
<input class="f-text" type="text" name="info[nick]" size="50" value="<?php echo $nick; ?>">
</td>
<td rowspan="5">
<a target="_blank" href="<?php echo $detail_url; ?>">
<img border="0" src="<?php echo $pic_url; ?>" width="200" height="200" />
</a>
</td>
</tr>
<tr>
<th>店铺连接:</th>
<td>
<input class="f-text" type="text" name="info[detail_url]" size="50" value="<?php echo $detail_url; ?>">
</td>
</tr>
<tr>
<th>店家店标:</th>
<td>
<input class="f-text" type="text" name="info[pic_url]" size="50" value="<?php echo $pic_url; ?>">
</td>
</tr>
<tr>
<th>店铺标题:</th>
<td>
<input class="f-text" type="text" name="info[shop_title]" size="50" value="<?php echo $shop_title; ?>">
</td>
</tr>
<tr>
<th>店铺描述:</th>
<td>
<textarea style="width:370px;height:200px" name="info[description]"><?php echo $description; ?></textarea>
</td>
</tr>
</table>
<!--table_form_off-->
<div class="btns"><input name="id" type="hidden" value="<?php echo $id?>"><input type="submit" id="dosubmit" class="button" name="dosubmit" value="提交"></div>
</form>
<?php include $this->admin_tpl('foot');?><file_sep>/caches/caches_template/default/exchange/index.php
<?php defined('IN_JAE') or exit('No permission resources.'); ?><?php include template('content','head');?>
<link rel="stylesheet" type="text/css" href="/statics/css/exchange.css">
<link href="/statics/css/prize.css" rel="stylesheet" type="text/css" />
<div class="jfhgymbg">
<img src="http://img03.taobaocdn.com/imgextra/i3/1089118323/TB2NkSpXFXXXXaMXpXXXXXXXXXX-1089118323.jpg">
</div>
<div class="wrap">
<div class="border">
<div class="pd20">
<div class="content">
<div class="exchange-list clearfix" >
<?php foreach ($data as $v) { ?>
<div class="exchange "><div class="ex_img"> <a href="/index.php?m=exchange&c=index&a=exchange&id=<?php echo $v['id']?>" target="_blank" title="<?php echo $v['title'];?>" > <img width="260" height="260" alt="<?php echo $v['title'];?>" src="<?php echo $v['pic_url']?>"><br><?php echo str_cut($v['title'],'15','');?></a></div>
<div class="layer clearfix"> <a class="info clearfix" href="/index.php?m=exchange&c=index&a=exchange&id=<?php echo $v['id']?>" target="_blank" title="<?php echo $v['title'];?>" >
<div class="point">
<div class="num"><?php echo $v['point']?>积分</div>
</div>
<div class="limit"><?php echo $v['num']?>件</div>
<div class="old-price"> 原价 ¥ <s><?php echo $v['price']?></s> </div>
<div class="j-sell-status status sold-out" >立即兑换</div>
</a></div>
</div>
<?php }?>
</div>
</div>
<div class="pages"><?php echo $pages;?></div>
</div>
</div>
<div class="clear"></div>
</div>
<file_sep>/jae/modules/admin/templates/main.tpl.php
<?php include $this->admin_tpl('head');?>
main.tpl.php
<?php include $this->admin_tpl('foot');?><file_sep>/demo/sql.php
<?php
$db=new PDO();
$file = fopen("ss.csv","r");
while(! feof($file))
{
$row=fgetcsv($file,10000);
$sql = "INSERT INTO `jae_member` (`phpssouid`,`username`,`nickname`,`regdate`,`lastdate`,`loginnum`,`email`,`groupid`,`point`,`islock`,`vip`,`zipcode`,`wangwang`,`siteid`,`mobile`,`address`) VALUES ";
$sql .= "(99,'".$row[0]."','".$row[1]."','".strtotime(trim($row[2]))."','".strtotime(trim($row[3]))."','".trim($row[4])."','".$row[12]."',1,'".$row[5]."',0,1,null,'".$row[9]."',1,'".$row[10]."','".$row[11]."'); ";
$sql.= "\r\n";
$lastqueryid = $db->prepare($sql);
$lastqueryid->execute();
$sql_info =$lastqueryid->errorinfo(); //取得错误信息数组(注意此处取的是$pdo的errorInfo而不是$sql的)
if($sql_info[1] != 00000) { echo '执行:' . $sql_info[2] ;$appLog->info($sql_info[2]);}; //输出错误信息
}
fclose($file);
?><file_sep>/jae/modules/member/member_menu.php
<?php
defined('IN_JAE') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
class member_menu extends admin {
function __construct() {
parent::__construct();
$this->db = jae_base::load_model('member_menu_model');
$this->menuid=3;
}
function init () {
$tree = jae_base::load_sys_class('tree');
$tree->icon = array(' │ ',' ├─ ',' └─ ');
$tree->nbsp = ' ';
$result = $this->db->select('','*','','listorder ASC,id DESC');
$array = array();
foreach($result as $r) {
$r['cname'] = L($r['name']);
$r['str_manage'] = '<a href="/admin.php?aid='.$_GET['aid'].'&cid='.$_GET['cid'].'&did='.$_GET['did'].'&m=member&c=member_menu&a=add&parentid='.$r['id'].'&menuid='.$_GET['menuid'].'">'.L('add_submenu').'</a> | <a href="/admin.php?aid='.$_GET['aid'].'&cid='.$_GET['cid'].'&did='.$_GET['did'].'&m=member&c=member_menu&a=edit&id='.$r['id'].'&menuid='.$_GET['menuid'].'">'.L('modify').'</a> | <a href="/admin.php?m=member&c=member_menu&a=delete&id='.$r['id'].'&menuid='.$_GET['menuid'].'">'.L('delete').'</a> ';
$array[] = $r;
}
$tree->init($array);
$categorys = $tree->get_tree(0, $str);
include $this->admin_tpl('member_menu');
}
function add() {
$result = $this->db->select('','*','','listorder ASC,id DESC');
if(isset($_POST['dosubmit'])) {
$data=$_POST['info'];
$this->db->insert($data);
//开发过程中用于自动创建语言包
$file = JAE_PATH.'jae'.DIRECTORY_SEPARATOR.'languages'.DIRECTORY_SEPARATOR.'zh-cn'.DIRECTORY_SEPARATOR.'system_menu.lang.php';
if(file_exists($file)) {
$content = file_get_contents($file);
$content = substr($content,0,-2);
$key = $_POST['info']['name'];
$data = $content."\$LANG['$key'] = '$_POST[language]';\r\n?>";
file_put_contents($file,$data);
} else {
$key = $_POST['info']['name'];
$data = "<?php\r\n\$LANG['$key'] = '$_POST[language]';\r\n?>";
file_put_contents($file,$data);
}
//结束
showmessage(L('add_success'));
include $this->admin_tpl('member_menu_add');
} else {
$show_validator = '';
$tree = jae_base::load_sys_class('tree');
//$result = $this->db->select();
$array = array();
foreach($result as $r) {
$r['cname'] = L($r['name']);
$r['selected'] = $r['id'] == $_GET['parentid'] ? 'selected' : '';
$array[] = $r;
}
//$str = "<option value='\$id' \$selected>\$spacer \$cname</option>";
$tree->init($array);
$select_categorys = $tree->get_option(0, $str);
//$models = jae_base::load_config('model_config');
include $this->admin_tpl('member_menu_add');
}
}
function delete() {
$_GET['id'] = intval($_GET['id']);
$this->db->delete('id='.$_GET['id']);
showmessage(L('operation_success'));
}
function edit() {
if(isset($_POST['dosubmit'])) {
$id = intval($_POST['id']);
$data=$_POST['info'];
$this->db->update($data,'id='.$id);
//修改语言文件
$file = JAE_PATH.'jae'.DIRECTORY_SEPARATOR.'languages'.DIRECTORY_SEPARATOR.'zh-cn'.DIRECTORY_SEPARATOR.'system_menu.lang.php';
require $file;
$key = $_POST['info']['name'];
if(!isset($LANG[$key])) {
$content = file_get_contents($file);
$content = substr($content,0,-2);
$data = $content."\$LANG['$key'] = '$_POST[language]';\r\n?>";
file_put_contents($file,$data);
} elseif(isset($LANG[$key]) && $LANG[$key]!=$_POST['language']) {
$content = file_get_contents($file);
$content = str_replace($LANG[$key],$_POST['language'],$content);
file_put_contents($file,$content);
}
//$this->update_menu_models($id, $r, $_POST['info']);
//结束语言文件修改
showmessage(L('operation_success'));
} else {
$show_validator = $array = $r = '';
$tree = jae_base::load_sys_class('tree');
$id = intval($_GET['id']);
$r=$this->db->get_one('id='.$id);
if($r) extract($r);
$result = $this->db->select('','*','','listorder ASC,id DESC');
foreach($result as $r) {
$r['cname'] = L($r['name']);
$r['selected'] = $r['id'] == $parentid ? 'selected' : '';
$array[] = $r;
}
//$str = "<option value='\$id' \$selected>\$spacer \$cname</option>";
$tree->init($array);
$select_categorys = $tree->get_option(0, $str);
//$models = jae_base::load_config('model_config');print_r($c);
include $this->admin_tpl('member_menu_edit');
}
}
/**
* 排序
*/
function listorder() {
if(isset($_POST['dosubmit'])) {
foreach($_POST['listorders'] as $id => $listorder) {
$listorder = !empty($listorder) ? $listorder : '0';
$this->db->update(array('listorder'=>$listorder),'id='.$id);
}
showmessage(L('operation_success'));
} else {
showmessage(L('operation_failure'));
}
}
/**
* 更新菜单的所属模式
* @param $id INT 菜单的ID
* @param $old_data 该菜单的老数据
* @param $new_data 菜单的新数据
**/
private function update_menu_models($id, $old_data, $new_data) {
$models_config = jae_base::load_config('model_config');
if (is_array($models_config)) {
foreach ($models_config as $_k => $_m) {
if (!isset($new_data[$_k])) $new_data[$_k] = 0;
if ($old_data[$_k]==$new_data[$_k]) continue; //数据没有变化时继续执行下一项
$r = $this->db->get_one(array('id'=>$id), 'parentid');
$this->db->update(array($_k=>$new_data[$_k]), array('id'=>$id));
if ($new_data[$_k] && $r['parentid']) {
$this->update_parent_menu_models($r['parentid'], $_k); //如果设置所属模式,更新父级菜单的所属模式
}
}
}
return true;
}
/**
* 更新父级菜单的所属模式
* @param $id int 菜单ID
* @param $field 修改字段名
*/
private function update_parent_menu_models($id, $field) {
$id = intval($id);
$r = $this->db->get_one(array('id'=>$id), 'parentid');
$this->db->update(array($field=>1), array('id'=>$id)); //修改父级的所属模式,然后判断父级是否存在父级
if ($r['parentid']) {
$this->update_parent_menu_models($r['parentid'], $field);
}
return true;
}
}
?><file_sep>/jae/modules/order/order.php
<?php
defined('IN_JAE') or exit('No permission resources.');defined('IN_ADMIN') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
class order extends admin {
function __construct() {
parent::__construct();
$this->order_db = jae_base::load_model('order_model');
$this->menuid=89;
}
function init () {
$order_follow=array(1=>'未支付',2=>'提交订单',3=>'已提交订单',4=>'未发货',5=>'发货',6=>'已发货',7=>'未确认收货',8=>'确认收货',9=>'已确认收货',10=>'已确认收货');
$where =1;
$title = isset($_GET['title']) ? $_GET['title'] : '';
$userid = isset($_GET['userid']) ? $_GET['userid'] : '';
if (!empty($title))$where .= " AND `title` LIKE '%$title%' ";
if (!empty($userid))$where .= " AND `userid` = '$userid' ";
$page=$_GET['page'];
$data=$this->order_db->listinfo($where,"id DESC",$page,$pages = '20');
$pages=$this->order_db->pages;
include $this->admin_tpl('order_list');
}
function add() {
if(isset($_POST['dopost'])) {
//获取站点配置信息
$siteinfo=siteinfo(SITEID);
$appkey =$siteinfo['appkey'];
$secret =$siteinfo['secretkey'];
jae_base::load_top('topclient');
jae_base::load_top('ItemGetRequest');
$numIid= isset($_POST['numIid']) ? trim($_POST['numIid']) : ''; //提交过来的num_iid
if ($numIid != "" && rRuleNum($numIid)) {
$c = new TopClient;
$c->appkey = $appkey;
$c->secretKey = $secret;
$req = new ItemGetRequest;
$req->setFields("detail_url,num_iid,title,nick,type,cid,seller_cids,props,input_pids,input_str,desc,pic_url,num,valid_thru,list_time,delist_time,stuff_status,location,price,post_fee,express_fee,ems_fee,has_discount,freight_payer,has_invoice,has_warranty,has_showcase,modified,increment,approve_status,postage_id,product_id,auction_point,property_alias,item_img,prop_img,sku,video,outer_id,is_virtual");
$req->setNumIid($numIid);
$resp = $c->execute($req, $sessionKey);
if ($resp->item) {
$detail_url = $resp->item->detail_url; //商品链接
$num_iid = $resp->item->num_iid; //商品ID
$title = $resp->item->title; //商品标题
$nick = $resp->item->nick; //卖家昵称
$pic_url = $resp->item->pic_url; //商品主图
$num = $resp->item->num; //商品数量
$price = $resp->item->price; //商品原价格
$freight_payer = $resp->item->freight_payer; //商品原价格
} else
$message = '不存在这个商品';
//print_r($resp);
} else {
$message = "商品ID【不能为空】并且【必须是数字】。";
}
}
if(isset($_POST['dosubmit'])) {
$data=$_POST['info'];
$data['begin_time'] = strtotime($_POST['info']['begin_time']);
$data['end_time'] = strtotime($_POST['info']['end_time']);
$data['status']=1;
$this->db->insert($data,$this->table);
showmessage(L('add_success'));
} else {
include $this->admin_tpl('exchange_add');
}
}
function delete() {
$_GET['id'] = intval($_GET['id']);
$this->order_db->delete('id='.$_GET['id']);
showmessage(L('operation_success'));
}
function clear() {
$this->order_db->delete('userid = 1 ');
$this->order_db->delete('userid = 2 ');
showmessage(L('operation_success'));
}
function edit() {
$order_follow=array(1=>'未支付',2=>'提交订单',3=>'已提交订单',4=>'未发货',5=>'发货',6=>'已发货',7=>'未确认收货',8=>'确认收货',9=>'已确认收货');
if(isset($_POST['dosubmit'])) {
$id = intval($_POST['id']);
$data=$_POST['info'];
$this->order_db->update($data,'id='.$id);
showmessage(L('operation_success'));
} else {
$id = intval($_GET['id']);
$r=$this->order_db->get_one('id='.$id);
if($r) extract($r);
include $this->admin_tpl('order_edit');
}
}
function listorder() {
if(isset($_POST['dosubmit'])) {
foreach($_POST['listorders'] as $id => $listorder) {
$listorder = !empty($listorder) ? $listorder : '0';
$this->db->update(array('listorder'=>$listorder),$this->table,'id='.$id);
$status = isset($_POST["status"][$id]) ? $_POST["status"][$id] : '0';
$this->db->update(array('status'=>$status),$this->table,'id='.$id);
}
showmessage(L('operation_success'));
} else {
showmessage(L('operation_failure'));
}
}
}
?><file_sep>/member.php
<?php
define('JAE_PATH', dirname(__FILE__).DIRECTORY_SEPARATOR);
if($_GET['m']=='admin') exit('No permission resources.');
include JAE_PATH.'/jae/base.php';
$fromuserid=intval($_GET['fromuserid']);
if ($fromuserid) { header("location:/index.php?m=member&c=index&a=setinfo&fromuserid=$fromuserid&spm=a216r.7118237.1.16.43HMVY");}
$forward=$_GET['forward'];
if(!empty($forward)){
header("location:".htmlspecialchars_decode($forward));
}
;
jae_base::creat_app();
?><file_sep>/jae/modules/position/templates/position_list.tpl.php
<?php include $this->admin_tpl('head','admin');?>
<form name="myform" action="/admin.php?m=admin&c=focus&a=listorder" method="post">
<div class="pad-lr-10">
<div class="table-list">
<table width="100%" cellspacing="0" class="table_form">
<tbody>
<tr class="thead">
<td width="30"><?php echo L('posid');?></td>
<td width="220" align="left">推荐位名称</td>
<td width="220" align="left">显示标题</td>
<td width="120" align="left">所属站点</td>
<td width="120" align="left">所属模型</td>
<td align="center"><?php echo L('operations_manage');?></td>
</tr>
<?php foreach ($data as $r){?>
<tr>
<td align="center"><?php echo $r['posid'];?></td>
<td align="left"><?php echo $r['name'];?></td>
<td ><?php echo $r['title'];?></td>
<td ><?php echo $sitelist[$r['siteid']]['name'];?></td>
<td ><?php echo $models[$r['modelid']]['name'];?></td>
<td align="center"><?php echo '<a href="/admin.php?m=position&c=position&a=public_item&posid='.$r['posid'].'&menuid='.$this->menuid.'">'.L('信息管理').'</a> | <a href="/admin.php?m=position&c=position&a=edit&posid='.$r['posid'].'&menuid='.$this->menuid.'">'.L('modify').'</a> | <a href="/admin.php?m=position&c=position&a=delete&posid='.$r['posid'].'&menuid='.$this->menuid.'">'.L('delete').'</a> ';?></td>
</tr>
<?php }?>
</tbody>
</table>
<div class="btns"><input type="submit" class="button" name="dosubmit" value="<?php echo L('listorder')?>" /></div> </div>
</div>
</div>
</form>
<div class="pages"><?php echo $pages;?></div>
<?php include $this->admin_tpl('foot','admin');?><file_sep>/caches/caches_commons/caches_data/special.cache.php
<?php
return array (
5 =>
array (
'id' => '5',
0 => '5',
'title' => '新品上市',
1 => '新品上市',
'description' => '有机草莓 春季购',
2 => '有机草莓 春季购',
'thumb' => 'http://img04.taobaocdn.com/imgextra/i4/18323037089698062/T2tqF.XLhaXXXXXXXX_!!1089118323-2-cs-!CS.png',
3 => 'http://img04.taobaocdn.com/imgextra/i4/18323037089698062/T2tqF.XLhaXXXXXXXX_!!1089118323-2-cs-!CS.png',
'html' => '',
4 => '',
'css' => '',
5 => '',
'islink' => '0',
6 => '0',
'status' => '0',
7 => '0',
'listorder' => '0',
8 => '0',
'url' => '',
9 => '',
),
);
?><file_sep>/caches/configs/version.php
<?php
return array(
// 'jae_version' => '212', //jae 版本号
// 'jae_release' => '20140721', //jae 更新日期
);
?><file_sep>/jae/modules/member/templates/index.tpl.php
<?php include $this->admin_tpl('head','admin');?>
member/index.php
<?php include $this->admin_tpl('foot','admin');?><file_sep>/jae/modules/admin/link.php
<?php
defined('IN_JAE') or exit('No permission resources.');
jae_base::load_app_class('admin','admin',0);
class link extends admin {
function __construct() {
parent::__construct();
$this->db =jae_base::load_sys_class('mysql');
$this->table='jae_link';
$this->menuid=46;
}
function init () {
$page=$_GET['page'];
$data=$this->db->listinfo("*",$this->table,"","linkid DESC",$page,10);
$pages=$this->db->pages;
include $this->admin_tpl('link_list');
}
function add() {
if(isset($_POST['dosubmit'])) {
print_r($info);
$data=$_POST['info'];
$this->db->insert($data,$this->table);
include $this->admin_tpl('link_add');
showmessage(L('add_success'));
} else {
include $this->admin_tpl('link_add');
}
}
function delete() {
$_GET['linkid'] = intval($_GET['linkid']);
$this->db->delete($this->table,'linkid='.$_GET['linkid']);
showmessage(L('operation_success'));
}
function edit() {
if(isset($_POST['dosubmit'])) {
$linkid = intval($_POST['linkid']);
$data=$_POST['info'];
$this->db->update($data,$this->table,'linkid='.$linkid);
showmessage(L('operation_success'));
include $this->admin_tpl('link_edit');
} else {
$linkid = intval($_GET['linkid']);
$r=$this->db->get_one('*',$this->table,'linkid='.$linkid);
if($r) extract($r);
include $this->admin_tpl('link_edit');
}
}
function listorder() {
if(isset($_POST['dosubmit'])) {
foreach($_POST['listorders'] as $linkid => $listorder) {
$listorder = !empty($listorder) ? $listorder : '0';
$this->db->update(array('listorder'=>$listorder),$this->table,'linkid='.$linkid);
echo $passed = isset($_POST["passed"][$linkid]) ? $_POST["passed"][$linkid] : '0';
$this->db->update(array('passed'=>$passed),$this->table,'linkid='.$linkid);
}
showmessage(L('operation_success'));
} else {
showmessage(L('operation_failure'));
}
}
}
?><file_sep>/jae/modules/apply/templates/goods_edit.tpl.php
<?php include $this->admin_tpl('head','admin'); ?>
<font color="red"><?php echo $message;?></font>
<form name="form2" method="post" action="/admin.php?m=apply&c=goods&a=edit">
<table class="table_form" cellpadding="0" cellspacing="0" border="0">
<tr>
<th>拒绝理由:</th>
<td>
<textarea style="width:350px;height:100px" name="info[refuse]"><?php echo $refuse; ?></textarea>
</td>
</tr>
<tr>
<th width="140">*商品1链接:</th>
<td><input class="input-text" type="text" name="info[detail_url]" size="50" value="<?php echo $detail_url; ?>"></td>
</tr>
<tr>
<th>*商品标题:</th>
<td><input class="input-text" type="text" name="info[title]" size="50" value="<?php echo $title; ?>"></td> <td rowspan="12" valign="top"> <a target="_blank" href="<?php echo $detail_url; ?>"><img border="0" src="<?php echo $pic_url; ?>" width="200" height="200" /><br>商品图片预览(点击跳到详情页面)</a> </td>
</tr>
<tr>
<th>*商品图片:</th>
<td><input class="input-text" type="text" name="info[pic_url]" size="50" value="<?php echo $pic_url; ?>"></td>
</tr>
<tr>
<th>
商品分类:
</th>
<td width="380">
<select name="info[category_id]">
<option value="0">无分类</option>
<?php
foreach($categoryArr as $catId=>$catName){; ?>
<option value="<?php echo $catId; ?>" <?php if($catId==$category_id) echo "selected";?> ><?php echo $catName; ?></option>
<?php }; ?>
</select>
</td>
<td>
</td>
</tr>
<tr>
<th>*上线时间段:</th>
<td>
<ul>
<li>
<label class="tit" for="J_DepDate">开始时间:</label>
<input name="info[begin_time]" class="kg_datePicker input-text"
data-config='{"isHoliday": false,
"minDate" :"<?php echo date('Y-m-d', time()-604800); ?>","finalTriggerNode" : "kg_datePicker input-text", "finalTriggerMinDate" : "2013-04-22"}'
type="text"
value="<?php echo date('Y-m-d', time()); ?>"/>
</li>
<li>
<label class="tit" for="J_RetDate">结束时间:</label>
<input name="info[end_time]" class="kg_datePicker input-text" type="text"
value="<?php echo date('Y-m-d', time()+604800); ?>"/>
</li>
</ul>
</td>
</tr>
<tr>
<th>*包邮:</th>
<td>
<select name="info[freight_payer]">
<option<?php if($freight_payer=='seller'){?> selected="selected"<?php }; ?> value="seller">是</option>
<option<?php if($freight_payer=='buyer'){?> selected="selected"<?php }; ?> value="buyer">否</option>
</select>
</tr>
<tr>
<th>*商家昵称:</th>
<td><input class="input-text" type="text" name="info[nick]" size="50" value="<?php echo $nick; ?>"></td>
</tr>
<tr>
<th>*商品原价:</th>
<td><input class="input-text" type="text" name="inf[price]" size="50" value="<?php echo $price; ?>"></td>
</tr>
<tr>
<th>*商品现价:</th>
<td><input class="input-text" type="text" name="info[coupon_price]" value="<?php echo $coupon_price; ?>" /></td>
</tr>
<tr>
<th>*商品数量:</th>
<td><input class="input-text" type="text" name="info[num]" size="50" value="<?php echo $num; ?>"></td>
</tr>
<tr>
<th>商品推荐位:</th>
<td>
<select name="info[promote_id]">
<option value="0">无推荐位</option>
<?php foreach ($promotePositionArr as $promoteId => $promoteName)
{
; ?>
<option value="<?php echo $promoteId; ?>" <?php if($promoteId==$promote_id) echo "selected";?> ><?php echo $promoteName; ?></option>
<?php }; ?>
</select>
</td>
</tr>
<tr>
<th>频道:</th>
<td>
<select name="info[pindao_id]">
<option value="0">无频道</option>
<?php foreach ($pindaoArr as $pindaoId => $pindaoName)
{
; ?>
<option value="<?php echo $pindaoId; ?>" <?php if($pindaoId==$pindao_id) echo "selected";?>><?php echo $pindaoName; ?></option>
<?php }; ?>
</select>
</td>
</tr>
<tr>
<th>卖点描述:</th>
<td>
<textarea style="width:350px;height:100px" name="info[description]"><?php echo $description; ?></textarea>
</td>
</tr>
</table>
<div class="btns"><input name="id" type="hidden" value="<?php echo $id?>"><input type="submit" id="dosubmit" class="button" name="dosubmit" value="提交"></div>
</form>
<?php include $this->admin_tpl('foot','admin');?><file_sep>/upgrade/20140729.sql
CREATE TABLE `jae_position_data` (
`id` MEDIUMINT(8) UNSIGNED NOT NULL DEFAULT '0',
`catid` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0',
`posid` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '0',
`module` CHAR(20) NULL DEFAULT NULL,
`modelid` SMALLINT(6) UNSIGNED NULL DEFAULT '0',
`thumb` TINYINT(1) NOT NULL DEFAULT '0',
`data` MEDIUMTEXT NULL,
`siteid` SMALLINT(5) UNSIGNED NOT NULL DEFAULT '1',
`listorder` MEDIUMINT(8) NULL DEFAULT '0',
`expiration` INT(10) NOT NULL,
`extention` CHAR(30) NULL DEFAULT NULL,
`synedit` TINYINT(1) NULL DEFAULT '0'
)
COLLATE='gbk_chinese_ci'
ENGINE=MyISAM;
UPDATE jae_site SET date='20140729' ;
UPDATE jae_site SET version='149';<file_sep>/upgrade/20140611.sql
UPDATE jae_site SET date='20140611' ;
UPDATE jae_site SET version='136';
|
38df4063a3fbeeddb6256a34d6f94daad474bc45
|
[
"JavaScript",
"SQL",
"PHP"
] | 164
|
PHP
|
zhaoke2011/JAE
|
18109b623af09bcd5d4b7c5157a5eacd9643dc9d
|
77682c5aa07a7e3bc86120285e437a03a51e2acb
|
refs/heads/main
|
<file_sep>import { HttpClient } from "aurelia-http-client";
export class Author {
public httpClient = new HttpClient();
public author;
public postId;
activate(token) {
this.httpClient.get('https://jsonplaceholder.typicode.com/users/' + token.id)
.then(author => {
this.author = JSON.parse(author.response);
});
this.postId = token.postId;
}
}<file_sep>import { HttpClient } from "aurelia-http-client";
export class Post {
public httpClient = new HttpClient();
public postData;
public author;
public comments;
activate(token) {
this.httpClient.get('https://jsonplaceholder.typicode.com/posts/' + token.id)
.then(post => {
this.postData = JSON.parse(post.response);
this.httpClient.get('https://jsonplaceholder.typicode.com/users/' + this.postData.userId)
.then(author => {
this.author = JSON.parse(author.response);
});
this.httpClient.get('https://jsonplaceholder.typicode.com/posts/' + token.id + '/comments')
.then(comments => {
this.comments = JSON.parse(comments.response);
});
// console.log(this.postData);
});
}
}<file_sep>// import from 'aurelia-'
import { PLATFORM } from "aurelia-framework";
require('bootstrap/dist/css/bootstrap.min.css');
require('bootstrap');
import '../static/css/styles.css';
export class App {
public router;
configureRouter(config, router) {
this.router = router;
config.title = 'Test App';
config.options.pushState = true;
config.options.root = '/';
config.map([
{route: ['', 'home'], name:'home', moduleId:PLATFORM.moduleName('pages/home/home'), nav:true, title:"Home"},
{route: ['post/:id?'], name:'post', moduleId:PLATFORM.moduleName('pages/post/post'), title:"Post"},
{route: ['author/:id?/:postId?'], name:'author', moduleId:PLATFORM.moduleName('pages/author/author'), title:"Author"},
]);
}
}
<file_sep>import {HttpClient} from 'aurelia-http-client';
export class Home {
public httpClient = new HttpClient();
public posts;
constructor() {
this.httpClient.get('https://jsonplaceholder.typicode.com/posts')
.then(data => {
this.posts = JSON.parse(data.response);
});
}
}
|
18f8db8213c37fab7c8be05af9c054fb3afb86f0
|
[
"TypeScript"
] | 4
|
TypeScript
|
millertn/SoftdocsAsk
|
c22c8271772869559187218a16dc9d3a5663a3d9
|
b8f043eb23c86839d7887eb7c298a15cbf16a214
|
refs/heads/main
|
<repo_name>smittytone/PreviewMarkdown<file_sep>/PreviewMarkdownTests/PreviewMarkdownTests.swift
//
// PreviewMarkdownTests.swift
// PreviewMarkdownTests
//
// Created by <NAME> on 18/09/2020.
// Copyright © 2023 <NAME>. All rights reserved.
//
import XCTest
import AppKit
@testable import PreviewMarkdown
@testable import Previewer
class PreviewMarkdownTests: XCTestCase {
let appDelegate = NSApplication.shared.delegate as! AppDelegate
let pvc: PreviewViewController = PreviewViewController()
let cmn: Common = Common(false)
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testProcessSymbols() throws {
var markdownString = "**™ ± "
var expectedString = "**™ ± "
XCTAssert(cmn.processSymbols(markdownString) == expectedString)
markdownString = "® ©"
expectedString = "® ©"
XCTAssert(cmn.processSymbols(markdownString) == expectedString)
markdownString = "² > &trad."
expectedString = "² > &trad."
XCTAssert(cmn.processSymbols(markdownString) == expectedString)
}
func testProcessCode() throws {
let markdownString = """
This is some text.
```
This is some code.
```
More text.
"""
let expectedString = """
This is some text.
This is some code.
More text.
"""
//print(processCodeTags(markdownString))
XCTAssert(cmn.processCodeTags(markdownString) == expectedString)
}
func testConvertSpaces() throws {
var markdownString = """
This is some text.
1. Tab
* Tab
- Tab
\t* Tab2
Done
"""
var expectedString = """
This is some text.
1. Tab
\t* Tab
\t\t- Tab
\t* Tab2
Done
"""
//print(convertSpaces(markdownString))
XCTAssert(cmn.convertSpaces(markdownString) == expectedString)
markdownString = " 11. Something"
expectedString = "\t11. Something"
XCTAssert(cmn.convertSpaces(markdownString) == expectedString)
}
func testProcessCheckboxes() throws {
// Negative cases
var markdownString = "[p]"
XCTAssert(cmn.processCheckboxes(markdownString) == "[p]")
markdownString = "[x]()"
XCTAssert(cmn.processCheckboxes(markdownString) == "[x]()")
// Positive cases
markdownString = "[X]"
XCTAssert(cmn.processCheckboxes(markdownString) == "✅")
markdownString = "[x]"
XCTAssert(cmn.processCheckboxes(markdownString) == "✅")
markdownString = "[]"
XCTAssert(cmn.processCheckboxes(markdownString) == "❎")
markdownString = "[ ]"
XCTAssert(cmn.processCheckboxes(markdownString) == "❎")
}
func testGetFrontMatter() throws {
var markdownString = """
---
title: ASCII
description: A macOS tool to help you design glyphs for 8x8 LED matrix displays
slug: ascii
logo: true
preview: images/ascii/preview.png
---
# Next
"""
var expectedString = """
title: ASCII
description: A macOS tool to help you design glyphs for 8x8 LED matrix displays
slug: ascii
logo: true
preview: images/ascii/preview.png
"""
XCTAssert(cmn.getFrontMatter(markdownString, #"^(-)+"#) == expectedString)
markdownString = """
------------
title: ASCII
description: A macOS tool to help you design glyphs for 8x8 LED matrix displays
slug: ascii
logo: true
preview: images/ascii/preview.png
------------
# Next
"""
XCTAssert(cmn.getFrontMatter(markdownString, #"^(-)+"#) == expectedString)
markdownString = """
+++
title: ASCII
description: A macOS tool to help you design glyphs for 8x8 LED matrix displays
slug: ascii
logo: true
preview: images/ascii/preview.png
+++
# Next
"""
XCTAssert(cmn.getFrontMatter(markdownString, #"^(\+)+"#) == expectedString)
markdownString = """
------------
title: ASCII
description: A macOS tool to help you design glyphs for 8x8 LED matrix displays
slug: ascii
logo: true
preview: images/ascii/preview.png
------------
# Next
"""
XCTAssert(cmn.getFrontMatter(markdownString, #"^(-)+"#) == expectedString)
markdownString = """
# Next
"""
expectedString = ""
XCTAssert(cmn.getFrontMatter(markdownString, #"^(-)+"#) == expectedString)
}
}
<file_sep>/README.md
# PreviewMarkdown 1.4.6
This app provides [Markdown](https://daringfireball.net/projects/markdown/syntax) file preview and thumbnailing extensions for Catalina and later versions of macOS.

## Installation and Usage
Just run the host app once to register the extensions — you can quit the app as soon as it has launched. We recommend logging out of your Mac and back in again at this point. Now you can preview markdown documents using QuickLook (select an icon and hit Space), and Finder’s preview pane and **Info*- panels.
You can disable and re-enable the Previewer and Thumbnailer extensions at any time in **System Preferences > Extensions > Quick Look**.
### Adjusting the Preview
You can alter some of the key elements of the preview by using the **Preferences*- panel:
- The colour of code blocks.
- Code blocks’ monospaced font.
- The base body text size.
- The body text font.
- Whether preview should be display white-on-black even in Dark Mode.
Changing these settings will affect previews immediately, but may not affect thumbnail until you open a folder that has not been previously opened in the current login session.
For more information on the background to this app, please see this [blog post](https://smittytone.wordpress.com/2019/11/07/create_previews_macos_catalina/).
### YAML Front Matter
*PreviewMarkdown- supports rendering YAML front matter in Markdown files. To enable it, go to **Preview Markdown > Preferences...*- and check the **Show YAML front matter*- checkbox. YAML will appear in QuickLook previews only.
## Source Code
This repository contains the primary source code for PreviewMarkdown. Certain graphical assets, code components and data files are not included. To build PreviewMarkdown from scratch, you will need to add these files yourself or remove them from your fork.
## Acknowledgements
PreviewMarkdown’s app extensions contain [SwiftyMarkdown](https://github.com/SimonFairbairn/SwiftyMarkdown) by <NAME> and other contributors, and [YamlSwift](https://github.com/behrang/YamlSwift) by <NAME> and other contributors.
## Release Notes
- 1.4.6 *21 January 2023*
- Add link to [PreviewText](https://smittytone.net/previewtext/index.html).
- Better menu handling when panels are visible.
- Better app exit management.
- 1.4.5 *23 December 2022*
- Add UTI `com.nutstore.down`.
- 1.4.4 *2 October 2022*
- Fix UTI generation.
- Add link to [PreviewJson](https://smittytone.net/previewjson/index.html).
- 1.4.3 *26 August 2022*
- Initial support for non-utf8 source code file encodings.
- 1.4.2 *7 August 2022*
- Upgrade to SwiftyMarkdown 1.2.4.
- Support checkboxes (`[x]`, `[ ]`).
- 1.4.1 *20 November 2021*
- Disable selection of thumbnail tags under macOS 12 Monterey to avoid clash with system-added tags.
- 1.4.0 *28 July 2021*
- Allow any installed font to be selected.
- Allow the heading colour to be selected.
- Allow any colour to be chosen using macOS’ colour picker.
- Tighten the thumbnailer code.
- Fixed a rare bug in the previewer error reporting code.
- 1.3.1 *18 June 2021*
- Add links to other PreviewApps.
- Support macOS 11 Big Sur’s UTType API.
- Stability improvements.
- 1.3.0 *9 May 2021*
- Add optional presentation of YAML front matter to previews.
- Recode Thumbnailer to make it thread safe: this should prevent crashes leading to generic or editor-specific thumbnail icons being seen.
- Update user-agent string.
- Minor code and UI improvements.
- 1.2.0 *4 February 2021*
- Add preview display preferences (requested by various anonymous feedback senders)
- Add file type ident tag to thumbnails (requested by @chamiu).
- Add **What’s New*- sheet to be shown with new major/minor versions.
- Include local markdown UTI with user-submitted feedback.
- Add link for app reviews.
- 1.1.4 *16 January 2021*
- Add UTI `net.ia.markdown`.
- 1.1.3 *14 January 2021*
- Add UTI `pro.writer.markdown`.
- 1.1.2 *18 November 2020*
- Apple Silicon version included.
- 1.1.1 *1 October 2020*
- Add report bugs/send feedback mechanism.
- Add usage advice to main window.
- Handle markdown formatting not yet rendered by SwiftyMarkdown: three-tick code blocks, HTML symbols, space-inset lists.
- 1.1.0 *25 September 2020*
- Add macOS Big Sur support.
- Better macOS dark/light mode support.
- Migrate engine to [SwiftyMarkdown 1.2.3](https://github.com/SimonFairbairn/SwiftyMarkdown).
- 1.0.5 *9 April 2020*
- App Store release version.
- 1.0.4 *Unreleased*
- Minor cosmetic changes to app menus.
- 1.0.3 *10 December 2019*
- Add version number to app’s info panel.
- 1.0.2 *4 December 2019*
- Fix random crash (`string index out of range` in SwiftyMarkdown).
- 1.0.1 *20 November 2019*
- Correct thumbnailer styles.
- 1.0.0 *8 November 2019*
- Initial public release.
## Copyright and Credits ##
Primary app code and UI design © 2023, <NAME>.
Code portions © 2022 <NAME>. Code portions ©2021 <NAME>.
<file_sep>/Previewer/Common.swift
/*
* Common.swift
* Code common to Previewer and Thumbnailer
*
* Created by <NAME> on 23/09/2020.
* Copyright © 2023 <NAME>. All rights reserved.
*/
import Foundation
import SwiftyMarkdown
import Yaml
import AppKit
// FROM 1.4.0
// Implement as a class
class Common: NSObject {
// MARK:- Public Properties
var doShowLightBackground: Bool = false
var doShowTag: Bool = true
// MARK:- Private Properties
private var doIndentScalars: Bool = true
private var doShowYaml: Bool = false
private var fontSize: CGFloat = CGFloat(BUFFOON_CONSTANTS.PREVIEW_FONT_SIZE)
// FROM 1.3.0
// Front Matter string attributes...
private var keyAtts: [NSAttributedString.Key:Any] = [:]
private var valAtts: [NSAttributedString.Key:Any] = [:]
// Front Matter rendering artefacts...
private var hr: NSAttributedString = NSAttributedString.init(string: "")
private var newLine: NSAttributedString = NSAttributedString.init(string: "")
// FROM 1.4.0
private var codeColourHex: String = BUFFOON_CONSTANTS.CODE_COLOUR_HEX
private var headColourHex: String = BUFFOON_CONSTANTS.HEAD_COLOUR_HEX
private var linkColourHex: String = BUFFOON_CONSTANTS.LINK_COLOUR_HEX
private var codeFontName: String = BUFFOON_CONSTANTS.CODE_FONT_NAME
private var bodyFontName: String = BUFFOON_CONSTANTS.BODY_FONT_NAME
// MARK:- Lifecycle Functions
init(_ isThumbnail: Bool) {
super.init()
// Load in the user's preferred values, or set defaults
if let prefs = UserDefaults(suiteName: MNU_SECRETS.PID + BUFFOON_CONSTANTS.SUITE_NAME) {
self.fontSize = CGFloat(isThumbnail
? BUFFOON_CONSTANTS.THUMBNAIL_FONT_SIZE
: prefs.float(forKey: "com-bps-previewmarkdown-base-font-size"))
self.doShowLightBackground = prefs.bool(forKey: "com-bps-previewmarkdown-do-use-light")
self.doShowYaml = prefs.bool(forKey: "com-bps-previewmarkdown-do-show-front-matter")
// FROM 1.4.0
self.codeColourHex = prefs.string(forKey: "com-bps-previewmarkdown-code-colour-hex") ?? BUFFOON_CONSTANTS.CODE_COLOUR_HEX
self.headColourHex = prefs.string(forKey: "com-bps-previewmarkdown-head-colour-hex") ?? BUFFOON_CONSTANTS.HEAD_COLOUR_HEX
self.linkColourHex = prefs.string(forKey: "com-bps-previewmarkdown-link-colour-hex") ?? BUFFOON_CONSTANTS.LINK_COLOUR_HEX
self.codeFontName = prefs.string(forKey: "com-bps-previewmarkdown-code-font-name") ?? BUFFOON_CONSTANTS.CODE_FONT_NAME
self.bodyFontName = prefs.string(forKey: "com-bps-previewmarkdown-body-font-name") ?? BUFFOON_CONSTANTS.BODY_FONT_NAME
self.doShowTag = prefs.bool(forKey: "com-bps-previewmarkdown-do-show-tag")
}
// Just in case the above block reads in zero values
// NOTE The other values CAN be zero
if self.fontSize < BUFFOON_CONSTANTS.FONT_SIZE_OPTIONS[0] ||
self.fontSize > BUFFOON_CONSTANTS.FONT_SIZE_OPTIONS[BUFFOON_CONSTANTS.FONT_SIZE_OPTIONS.count - 1] {
self.fontSize = CGFloat(BUFFOON_CONSTANTS.PREVIEW_FONT_SIZE)
}
// FROM 1.3.0
// Set the front matter key:value fonts and sizes
var font: NSFont
if let otherFont = NSFont.init(name: self.codeFontName, size: self.fontSize) {
font = otherFont
} else {
// This should not be hit, but just in case...
font = NSFont.systemFont(ofSize: self.fontSize)
}
self.keyAtts = [
.foregroundColor: NSColor.hexToColour(self.codeColourHex),
.font: font
]
self.valAtts = [
.foregroundColor: (isThumbnail || self.doShowLightBackground ? NSColor.black : NSColor.labelColor),
.font: font
]
self.hr = NSAttributedString(string: "\n\u{00A0}\u{0009}\u{00A0}\n\n",
attributes: [.strikethroughStyle: NSUnderlineStyle.thick.rawValue,
.strikethroughColor: (self.doShowLightBackground ? NSColor.black : NSColor.white)])
self.newLine = NSAttributedString.init(string: "\n",
attributes: self.valAtts)
}
// MARK:- The Primary Function
/**
Use SwiftyMarkdown to render the input markdown.
- parameters:
- markdownString: The markdown file contents.
- isThumbnail: Are we rendering for a thumbnail (`true`) or a preview (`false`)?
- returns: The rendered markdown as an NSAttributedString.
*/
func getAttributedString(_ markdownString: String, _ isThumbnail: Bool) -> NSAttributedString {
let swiftyMarkdown: SwiftyMarkdown = SwiftyMarkdown.init(string: "")
setSwiftStyles(swiftyMarkdown, isThumbnail)
var processed: String = processCodeTags(markdownString)
processed = convertSpaces(processed)
processed = processSymbols(processed)
processed = processCheckboxes(processed)
// Process the markdown string
var output: NSMutableAttributedString = NSMutableAttributedString.init(attributedString: swiftyMarkdown.attributedString(from: processed))
// FROM 1.3.0
// Render YAML front matter if requested by the user, and we're not
// rendering a thumbnail image (this is for previews only)
if !isThumbnail && self.doShowYaml {
// Extract the front matter
let frontMatter: String = getFrontMatter(markdownString, #"^(-)+"#)
if frontMatter.count > 0 {
// Only attempt to render the front matter if there is any
do {
let yaml: Yaml = try Yaml.load(frontMatter)
// Assemble the front matter string
let renderedString: NSMutableAttributedString = NSMutableAttributedString.init(string: "",
attributes: self.valAtts)
// Initial line
renderedString.append(self.hr)
// Render the YAML to NSAttributedString
if let yamlString = renderYaml(yaml, 0, false) {
renderedString.append(yamlString)
}
// Add a line after the front matter
renderedString.append(self.hr)
// Add in the orignal rendered markdown and then set the
// output string to the combined string
renderedString.append(output)
output = renderedString
} catch {
// No YAML to render, or mis-formatted
// No YAML to render, or the YAML was mis-formatted
// Get the error as reported by YamlSwift
let yamlErr: Yaml.ResultError = error as! Yaml.ResultError
var yamlErrString: String
switch(yamlErr) {
case .message(let s):
yamlErrString = s ?? "unknown"
}
// Assemble the error string
let errorString: NSMutableAttributedString = NSMutableAttributedString.init(string: "Could not render the YAML. Error: " + yamlErrString,
attributes: self.keyAtts)
// Should we include the raw text?
// At least the user can see the data this way
#if DEBUG
errorString.append(self.hr)
errorString.append(NSMutableAttributedString.init(string: frontMatter,
attributes: self.valAtts))
#endif
errorString.append(self.hr)
errorString.append(output)
output = errorString
}
}
}
// FROM 1.3.0
// Guard against non-trapped errors
if output.length == 0 {
return NSAttributedString.init(string: "No valid Markdown to render.",
attributes: self.keyAtts)
}
// Return the rendered NSAttributedString to Previewer or Thumbnailer
return output as NSAttributedString
}
// MARK:- SwiftyMarkdown Rendering Support Functions
func processSymbols(_ base: String) -> String {
// FROM 1.1.0
// Find and and replace any HTML symbol markup
// Processed here because SwiftyMarkdown doesn't handle this markup
let codes: [String] = [""", "&", "⁄", "<", ">", "‘", "’", "“", "”", "•", "–", "—", "™", " ", "¡", "¢", "£", "¥", "§", "©", "ª", "®", "°", "º", "±", "²", "³", "µ", "¶", "·", "¿", "÷", "€", "†", "‡"]
let symbols: [String] = ["\"", "&", "/", "<", ">", "‘", "’", "“", "”", "•", "-", "—", "™", " ", "¡", "¢", "£", "¥", "§", "©", "ª", "®", "º", "º", "±", "²", "³", "µ", "¶", "·", "¿", "÷", "€", "†", "‡"]
// Look for HTML symbol code '&...;' substrings, eg. '²'
let pattern = #"&[a-zA-Z]+[1-9]*;"#
var result = base
var range = base.range(of: pattern, options: .regularExpression)
while range != nil {
// Get the symbol from the 'symbols' array that has the same index
// as the symbol code from the 'codes' array
var repText = ""
let find = String(result[range!])
if codes.contains(find) {
repText = symbols[codes.firstIndex(of: find)!]
}
// Swap out the HTML symbol code for the actual symbol
result = result.replacingCharacters(in: range!, with: repText)
// Get the next occurence of the pattern ready for the 'while...' check
range = result.range(of: pattern, options: .regularExpression)
}
return result
}
func processCheckboxes(_ base: String) -> String {
// FROM 1.4.2
// Hack to present checkboxes a la GitHub
let patterns: [String] = [#"\[\s?\](?!\()"#, #"\[[xX]{1}\](?!\()"#]
let symbols: [String] = ["❎", "✅"]
// Look for HTML symbol code '&...;' substrings, eg. '²'
var i = 0
var result = base
for pattern in patterns {
var range = result.range(of: pattern, options: .regularExpression)
while range != nil {
// Swap out the HTML symbol code for the actual symbol
result = result.replacingCharacters(in: range!, with: symbols[i])
// Get the next occurence of the pattern ready for the 'while...' check
range = result.range(of: pattern, options: .regularExpression)
}
i += 1
}
return result
}
func processCodeTags(_ base: String) -> String {
// FROM 1.1.0
// Look for markdown code blocks top'n'tailed with three ticks ```
// Processed here because SwiftyMarkdown doesn't handle this markup
var isBlock = false
var index = 0
var lines = base.components(separatedBy: CharacterSet.newlines)
// Run through the lines looking for initial ```
// Remove any found and inset the lines in between (for SwiftyMarkdown to format)
for line in lines {
if line.hasPrefix("```") {
// Found a code block marker: remove the line and set
// the marker to the opposite what it was, off or on
lines.remove(at: index)
isBlock = !isBlock
continue
}
if isBlock {
// Pad each line with an initial four spaces - this is what SwiftyMarkdown
// looks for in a code block
lines[index] = " " + lines[index]
}
index += 1
}
// Re-assemble the string from the lines, spacing them with a newline
// (except for the final line, of course)
index = 0
var result = ""
for line in lines {
result += line + (index < lines.count - 1 ? "\n" : "")
index += 1
}
return result
}
func convertSpaces(_ base: String) -> String {
// FROM 1.1.1
// Convert space-formatted lists to tab-formatte lists
// Required because SwiftyMarkdown doesn't indent on spaces
// Find (multiline) x spaces followed by *, - or 1-9,
// where x >= 1
let pattern = #"(?m)^[ ]+([1-9]|\*|-)"#
var result = base as NSString
var nrange: NSRange = result.range(of: pattern, options: .regularExpression)
// Use NSRange and NSString because it's easier to modify the
// range to exclude the character *after* the spaces
while nrange.location != NSNotFound {
var tabs = ""
// Get the range of the spaces minus the detected list character
let crange: NSRange = NSMakeRange(nrange.location, nrange.length - 1)
// Get the number of tabs characters we need to insert
let tabCount = (nrange.length - 1) / BUFFOON_CONSTANTS.SPACES_FOR_A_TAB
// Assemble the required number of tabs
for _ in 0..<tabCount {
tabs += "\t"
}
// Swap out the spaces for the string of one or more tabs
result = result.replacingCharacters(in: crange, with: tabs) as NSString
// Get the next occurence of the pattern ready for the 'while...' check
nrange = result.range(of: pattern, options: .regularExpression)
}
return result as String
}
// MARK:- Front Matter Functions
/**
Extract and return initial front matter.
FROM 1.3.0
- Parameters:
- markdown: The markdown file content.
- markerPattern: A string literal specifying the front matter boundary marker Reg Ex, eg. #"^(-)+"# for ---.
- Returns: The parsed string, or an empty string (`""`) on error.
*/
func getFrontMatter(_ markdown: String, _ markerPattern: String) -> String {
let lines = markdown.components(separatedBy: CharacterSet.newlines)
var fm: [String] = []
var doAdd: Bool = false
for line in lines {
// Look for the pattern on the current line
let dashRange: NSRange = (line as NSString).range(of: markerPattern, options: .regularExpression)
if !doAdd && line.count > 0 {
if dashRange.location == 0 {
// Front matter start
doAdd = true
continue
} else {
// Some other text than front matter at the start
// so break
break
}
}
if doAdd && dashRange.location == 0 {
// End of front matter
var rs: String = ""
for item in fm {
rs += item + "\n"
}
return rs
}
if doAdd && line.count > 0 {
// Add the line of front matter to the store
fm.append(line)
}
}
return ""
}
/**
Render a supplied YAML sub-component ('part') to an NSAttributedString.
Indents the value as required.
FROM 1.3.0
- Parameters:
- part: A partial Yaml object.
- indent: The number of indent spaces to add.
- isKey: Is the Yaml part a key?
- Returns: The rendered string as an NSAttributedString, or nil on error.
*/
func renderYaml(_ part: Yaml, _ indent: Int, _ isKey: Bool) -> NSAttributedString? {
let returnString: NSMutableAttributedString = NSMutableAttributedString.init(string: "",
attributes: keyAtts)
switch (part) {
case .array:
if let value = part.array {
// Iterate through array elements
// NOTE A given element can be of any YAML type
for i in 0..<value.count {
if let yamlString = renderYaml(value[i], indent, false) {
// Apply a prefix to separate array and dictionary elements
if i > 0 && (value[i].array != nil || value[i].dictionary != nil) {
returnString.append(self.newLine)
}
// Add the element itself
returnString.append(yamlString)
}
}
return returnString
}
case .dictionary:
if let dict = part.dictionary {
// Iterate through the dictionary's keys and their values
// NOTE A given value can be of any YAML type
// Sort the dictionary's keys (ascending)
// We assume all keys will be strings, ints, doubles or bools
var keys: [Yaml] = Array(dict.keys)
keys = keys.sorted(by: { (a, b) -> Bool in
// Strings?
if let a_s: String = a.string {
if let b_s: String = b.string {
return (a_s.lowercased() < b_s.lowercased())
}
}
// Ints?
if let a_i: Int = a.int {
if let b_i: Int = b.int {
return (a_i < b_i)
}
}
// Doubles?
if let a_d: Double = a.double {
if let b_d: Double = b.double {
return (a_d < b_d)
}
}
// Bools
if let a_b: Bool = a.bool {
if let b_b: Bool = b.bool {
return (a_b && !b_b)
}
}
return false
})
// Iterate through the sorted keys array
for i in 0..<keys.count {
// Prefix root-level key:value pairs after the first with a new line
if indent == 0 && i > 0 {
returnString.append(self.newLine)
}
// Get the key:value pairs
let key: Yaml = keys[i]
let value: Yaml = dict[key] ?? ""
// Render the key
if let yamlString = renderYaml(key, indent, true) {
returnString.append(yamlString)
}
// If the value is a collection, we drop to the next line and indent
var valueIndent: Int = 0
if value.array != nil || value.dictionary != nil || self.doIndentScalars {
valueIndent = indent + BUFFOON_CONSTANTS.YAML_INDENT
returnString.append(self.newLine)
}
// Render the key's value
if let yamlString = renderYaml(value, valueIndent, false) {
returnString.append(yamlString)
}
}
return returnString
}
case .string:
if let keyOrValue = part.string {
let parts: [String] = keyOrValue.components(separatedBy: "\n")
if parts.count > 2 {
for i in 0..<parts.count {
let part: String = parts[i]
returnString.append(getIndentedString(part + (i < parts.count - 2 ? "\n" : ""), indent))
}
} else {
returnString.append(getIndentedString(keyOrValue, indent))
}
returnString.setAttributes((isKey ? self.keyAtts : self.valAtts),
range: NSMakeRange(0, returnString.length))
returnString.append(isKey ? NSAttributedString.init(string: " ", attributes: self.valAtts) : self.newLine)
return returnString
}
case .null:
returnString.append(getIndentedString(isKey ? "NULL KEY/n" : "NULL VALUE/n", indent))
returnString.setAttributes((isKey ? self.keyAtts : self.valAtts),
range: NSMakeRange(0, returnString.length))
returnString.append(isKey ? NSAttributedString.init(string: " ") : self.newLine)
return returnString
default:
// Place all the scalar values here
// TODO These *may* be keys too, so we need to check that
if let val = part.int {
returnString.append(getIndentedString("\(val)\n", indent))
} else if let val = part.bool {
returnString.append(getIndentedString((val ? "TRUE\n" : "FALSE\n"), indent))
} else if let val = part.double {
returnString.append(getIndentedString("\(val)\n", indent))
} else {
returnString.append(getIndentedString("UNKNOWN-TYPE\n", indent))
}
returnString.setAttributes(self.valAtts,
range: NSMakeRange(0, returnString.length))
return returnString
}
// Error condition
return nil
}
/**
Return a space-prefix NSAttributedString.
FROM 1.3.0
- Parameters:
- baseString: The string to be indented.
- indent: The number of indent spaces to add.
- Returns: The indented string as an NSAttributedString.
*/
func getIndentedString(_ baseString: String, _ indent: Int) -> NSAttributedString {
let trimmedString = baseString.trimmingCharacters(in: .whitespaces)
let spaces = " "
let spaceString = String(spaces.suffix(indent))
let indentedString: NSMutableAttributedString = NSMutableAttributedString.init()
indentedString.append(NSAttributedString.init(string: spaceString))
indentedString.append(NSAttributedString.init(string: trimmedString))
return indentedString.attributedSubstring(from: NSMakeRange(0, indentedString.length))
}
// MARK:- Formatting Functions
/**
Set common style values for the markdown render.
- Parameters:
- sm: The SwiftyMarkdown instance used for rendering
- isThumbnail: Are we rendering a thumbnail (`true`) or a preview (`false`).
*/
func setSwiftStyles(_ sm: SwiftyMarkdown, _ isThumbnail: Bool) {
sm.setFontColorForAllStyles(with: (isThumbnail || self.doShowLightBackground) ? NSColor.black : NSColor.labelColor)
sm.setFontSizeForAllStyles(with: self.fontSize)
// FROM 1.4.0 -- add colour settings for headings too
sm.h4.fontSize = self.fontSize * 1.2
sm.h4.color = NSColor.hexToColour(self.headColourHex)
sm.h3.fontSize = self.fontSize * 1.4
sm.h3.color = sm.h4.color
sm.h2.fontSize = self.fontSize * 1.6
sm.h2.color = sm.h4.color
sm.h1.fontSize = self.fontSize * 2.0
sm.h1.color = sm.h4.color
sm.setFontNameForAllStyles(with: self.bodyFontName)
sm.code.fontName = self.codeFontName
// Set the code colour
sm.code.color = NSColor.hexToColour(self.codeColourHex) // getColour(codeColourIndex)
// NOTE The following do not set link colour - this is
// a bug or issue with SwiftyMarkdown 1.2.3
sm.link.color = NSColor.hexToColour(self.linkColourHex) // getColour(linkColourIndex)
sm.link.underlineColor = sm.link.color
}
}
/**
Get the encoding of the string formed from data.
- Returns: The string's encoding or nil.
*/
extension Data {
var stringEncoding: String.Encoding? {
var nss: NSString? = nil
guard case let rawValue = NSString.stringEncoding(for: self,
encodingOptions: nil,
convertedString: &nss,
usedLossyConversion: nil), rawValue != 0 else { return nil }
return .init(rawValue: rawValue)
}
}
<file_sep>/Previewer/PreviewViewController.swift
/*
* PreviewViewController.swift
* Previewer
*
* Created by <NAME> on 31/10/2019.
* Copyright © 2023 <NAME>. All rights reserved.
*/
import Cocoa
import Quartz
class PreviewViewController: NSViewController,
QLPreviewingController {
// MARK:- Class UI Properties
@IBOutlet var errorReportField: NSTextField!
@IBOutlet var renderTextView: NSTextView!
@IBOutlet var renderTextScrollView: NSScrollView!
// MARK:- Private Properties
override var nibName: NSNib.Name? {
return NSNib.Name("PreviewViewController")
}
// MARK:- QLPreviewingController Required Functions
func preparePreviewOfFile(at url: URL, completionHandler handler: @escaping (Error?) -> Void) {
// Hide the error message field
self.errorReportField.stringValue = ""
self.errorReportField.isHidden = true
self.renderTextScrollView.isHidden = false
// FROM 1.1.0
// Get an error message ready for use
var reportError: NSError? = nil
// Load the source file using a co-ordinator as we don't know what thread this function
// will be executed in when it's called by macOS' QuickLook code
// NOTE From 1.1.0 we use plain old FileManager for this
if FileManager.default.isReadableFile(atPath: url.path) {
// Only proceed if the file is accessible from here
do {
// Get the file contents as a string
let data: Data = try Data.init(contentsOf: url, options: [.uncached])
// FROM 1.4.3
// Get the string's encoding, or fail back to .utf8
let encoding: String.Encoding = data.stringEncoding ?? .utf8
if let markdownString: String = String.init(data: data, encoding: encoding) {
// Instantiate the common code
let common: Common = Common.init(false)
// Update the NSTextView
// FROM 1.3.0
// Knock back the light background to make the scroll bars visible in dark mode
// NOTE If !doShowLightBackground,
// in light mode, the scrollers show up dark-on-light, in dark mode light-on-dark
// If doShowLightBackground,
// in light mode, the scrollers show up light-on-light, in dark mode light-on-dark
// NOTE Changing the scrollview scroller knob style has no effect
self.renderTextView.backgroundColor = common.doShowLightBackground ? NSColor.init(white: 1.0, alpha: 0.9) : NSColor.textBackgroundColor
self.renderTextScrollView.scrollerKnobStyle = common.doShowLightBackground ? .dark : .light
if let renderTextStorage: NSTextStorage = self.renderTextView.textStorage {
renderTextStorage.beginEditing()
renderTextStorage.setAttributedString(common.getAttributedString(markdownString, false))
renderTextStorage.endEditing()
// Add the subview to the instance's own view and draw
self.view.display()
// Call the QLPreviewingController indicating no error (nil)
handler(nil)
return
}
// We couldn't access the preview NSTextView's NSTextStorage
reportError = setError(BUFFOON_CONSTANTS.ERRORS.CODES.BAD_TS_STRING)
} else {
// FROM 1.4.3
// We couldn't convert to data to a valid encoding
let errDesc: String = "\(BUFFOON_CONSTANTS.ERRORS.MESSAGES.BAD_TS_STRING) \(encoding)"
reportError = NSError(domain: BUFFOON_CONSTANTS.APP_CODE_PREVIEWER,
code: BUFFOON_CONSTANTS.ERRORS.CODES.BAD_MD_STRING,
userInfo: [NSLocalizedDescriptionKey: errDesc])
}
} catch {
// We couldn't read the file so set an appropriate error to report back
reportError = setError(BUFFOON_CONSTANTS.ERRORS.CODES.FILE_WONT_OPEN)
}
} else {
// File passed isn't readable
reportError = setError(BUFFOON_CONSTANTS.ERRORS.CODES.FILE_INACCESSIBLE)
}
// Display the error locally in the window
showError(reportError!)
// Call the QLPreviewingController indicating an error (!nil)
handler(nil)
}
func preparePreviewOfSearchableItem(identifier: String, queryString: String?, completionHandler handler: @escaping (Error?) -> Void) {
// Is this ever called?
NSLog("BUFFOON searchable identifier: \(identifier)")
NSLog("BUFFOON searchable query: " + (queryString ?? "nil"))
// Hand control back to QuickLook
handler(nil)
}
// MARK:- Utility Functions
/**
Place an error message in its various outlets.
- parameters:
- error: The error as an NSError.
*/
func showError(_ error: NSError) {
let errString: String = error.userInfo[NSLocalizedDescriptionKey] as! String
self.errorReportField.stringValue = errString
self.errorReportField.isHidden = false
self.renderTextScrollView.isHidden = true
self.view.display()
NSLog("BUFFOON \(errString)")
}
/**
Generate an NSError for an internal error, specified by its code.
Codes are listed in `Constants.swift`
- Parameters:
- code: The internal error code.
- Returns: The described error as an NSError.
*/
func setError(_ code: Int) -> NSError {
// NSError generation function
var errDesc: String
switch(code) {
case BUFFOON_CONSTANTS.ERRORS.CODES.FILE_INACCESSIBLE:
errDesc = BUFFOON_CONSTANTS.ERRORS.MESSAGES.FILE_INACCESSIBLE
case BUFFOON_CONSTANTS.ERRORS.CODES.FILE_WONT_OPEN:
errDesc = BUFFOON_CONSTANTS.ERRORS.MESSAGES.FILE_WONT_OPEN
case BUFFOON_CONSTANTS.ERRORS.CODES.BAD_TS_STRING:
errDesc = BUFFOON_CONSTANTS.ERRORS.MESSAGES.BAD_TS_STRING
case BUFFOON_CONSTANTS.ERRORS.CODES.BAD_MD_STRING:
errDesc = BUFFOON_CONSTANTS.ERRORS.MESSAGES.BAD_MD_STRING
default:
errDesc = "UNKNOWN ERROR"
}
return NSError(domain: BUFFOON_CONSTANTS.APP_CODE_PREVIEWER,
code: code,
userInfo: [NSLocalizedDescriptionKey: errDesc])
}
}
<file_sep>/PreviewMarkdown/PMFontExtensions.swift
/*
* GenericExtensions.swift
* PreviewMarkdown
*
* These functions can be used by all PreviewApps
*
* Created by <NAME> on 18/06/2021.
* Copyright © 2023 <NAME>. All rights reserved.
*/
import Foundation
import Cocoa
import WebKit
import UniformTypeIdentifiers
extension AppDelegate {
// MARK: - Font Management
/**
Build a list of available fonts.
Should be called asynchronously. Two sets created: monospace fonts and regular fonts.
Requires 'bodyFonts' and 'codeFonts' to be set as instance properties.
Comment out either of these, as required.
The final font lists each comprise pairs of strings: the font's PostScript name
then its display name.
*/
internal func asyncGetFonts() {
var cf: [PMFont] = []
var bf: [PMFont] = []
let mono: UInt = NSFontTraitMask.fixedPitchFontMask.rawValue
let bold: UInt = NSFontTraitMask.boldFontMask.rawValue
let ital: UInt = NSFontTraitMask.italicFontMask.rawValue
let symb: UInt = NSFontTraitMask.nonStandardCharacterSetFontMask.rawValue
let fm: NSFontManager = NSFontManager.shared
let families: [String] = fm.availableFontFamilies
for family in families {
// Remove known unwanted fonts
if family.hasPrefix(".") || family.hasPrefix("Apple Braille") || family == "Apple Color Emoji" {
continue
}
var isCodeFont: Bool = true
// For each family, examine its fonts for suitable ones
if let fonts: [[Any]] = fm.availableMembers(ofFontFamily: family) {
// This will hold a font family: individual fonts will be added to
// the 'styles' array
var familyRecord: PMFont = PMFont.init()
familyRecord.displayName = family
for font: [Any] in fonts {
let psname: String = font[0] as! String
let traits: UInt = font[3] as! UInt
var doUseFont: Bool = false
if mono & traits != 0 {
doUseFont = true
} else if traits & bold == 0 && traits & ital == 0 && traits & symb == 0 {
isCodeFont = false
doUseFont = true
}
if doUseFont {
// The font is good to use, so add it to the list
var fontRecord: PMFont = PMFont.init()
fontRecord.postScriptName = psname
fontRecord.styleName = font[1] as! String
fontRecord.traits = traits
if familyRecord.styles == nil {
familyRecord.styles = []
}
familyRecord.styles!.append(fontRecord)
}
}
if familyRecord.styles != nil && familyRecord.styles!.count > 0 {
if isCodeFont {
cf.append(familyRecord)
} else {
bf.append(familyRecord)
}
}
}
}
DispatchQueue.main.async {
self.bodyFonts = bf
self.codeFonts = cf
}
}
/**
Build and enable the font style popup.
- Parameters:
- isBody: Whether we're handling body text font styles (`true`) or code font styles (`false`). Default: `true`.
- styleName: The name of the selected style. Default: `nil`.
*/
internal func setStylePopup(_ isBody: Bool = true, _ styleName: String? = nil) {
let selectedFamily: String = isBody ? self.bodyFontPopup.titleOfSelectedItem! : self.codeFontPopup.titleOfSelectedItem!
let familyList: [PMFont] = isBody ? self.bodyFonts : self.codeFonts
let targetPopup: NSPopUpButton = isBody ? self.bodyStylePopup : self.codeStylePopup
targetPopup.removeAllItems()
for family: PMFont in familyList {
if selectedFamily == family.displayName {
if let styles: [PMFont] = family.styles {
targetPopup.isEnabled = true
for style: PMFont in styles {
targetPopup.addItem(withTitle: style.styleName)
}
if styleName != nil {
targetPopup.selectItem(withTitle: styleName!)
}
}
}
}
}
/**
Select the font popup using the stored PostScript name
of the user's chosen font.
- Parameters:
- postScriptName: The PostScript name of the font.
- isBody: Whether we're handling body text font styles (`true`) or code font styles (`false`).
*/
internal func selectFontByPostScriptName(_ postScriptName: String, _ isBody: Bool) {
let familyList: [PMFont] = isBody ? self.bodyFonts : self.codeFonts
let targetPopup: NSPopUpButton = isBody ? self.bodyFontPopup : self.codeFontPopup
for family: PMFont in familyList {
if let styles: [PMFont] = family.styles {
for style: PMFont in styles {
if style.postScriptName == postScriptName {
targetPopup.selectItem(withTitle: family.displayName)
setStylePopup(isBody, style.styleName)
}
}
}
}
}
/**
Get the PostScript name from the selected family and style.
- Parameters:
- isBody: Whether we're handling body text font styles (`true`) or code font styles (`false`).
- Returns: The PostScript name as a string, or nil.
*/
internal func getPostScriptName(_ isBody: Bool) -> String? {
let familyList: [PMFont] = isBody ? self.bodyFonts : self.codeFonts
let fontPopup: NSPopUpButton = isBody ? self.bodyFontPopup : self.codeFontPopup
let stylePopup: NSPopUpButton = isBody ? self.bodyStylePopup : self.codeStylePopup
if let selectedFont: String = fontPopup.titleOfSelectedItem {
let selectedStyle: Int = stylePopup.indexOfSelectedItem
for family: PMFont in familyList {
if family.displayName == selectedFont {
if let styles: [PMFont] = family.styles {
let font: PMFont = styles[selectedStyle]
return font.postScriptName
}
}
}
}
return nil
}
}
<file_sep>/PreviewMarkdown/GenericColorExtensions.swift
/*
* GenericColorExtension.swift
* PreviewApps
*
* Created by <NAME> on 18/06/2021.
* Copyright © 2023 <NAME>. All rights reserved.
*/
import Foundation
import Cocoa
extension NSColor {
/**
Convert a colour's internal representation into an RGB+A hex string.
*/
var hexString: String {
guard let rgbColour = usingColorSpace(.sRGB) else {
return BUFFOON_CONSTANTS.CODE_COLOUR_HEX
}
let red: Int = Int(round(rgbColour.redComponent * 0xFF))
let green: Int = Int(round(rgbColour.greenComponent * 0xFF))
let blue: Int = Int(round(rgbColour.blueComponent * 0xFF))
let alpha: Int = Int(round(rgbColour.alphaComponent * 0xFF))
let hexString: NSString = NSString(format: "%02X%02X%02X%02X", red, green, blue, alpha)
return hexString as String
}
/**
Generate a new NSColor from an RGB+A hex string..
- Parameters:
- hex: The RGB+A hex string, eg.`AABBCCFF`.
- Returns: An NSColor instance.
*/
static func hexToColour(_ hex: String) -> NSColor {
if hex.count != 8 {
return NSColor.red
}
func hexToFloat(_ hs: String) -> CGFloat {
return CGFloat(UInt8(hs, radix: 16) ?? 0)
}
let hexns: NSString = hex as NSString
let red: CGFloat = hexToFloat(hexns.substring(with: NSRange.init(location: 0, length: 2))) / 255
let green: CGFloat = hexToFloat(hexns.substring(with: NSRange.init(location: 2, length: 2))) / 255
let blue: CGFloat = hexToFloat(hexns.substring(with: NSRange.init(location: 4, length: 2))) / 255
let alpha: CGFloat = hexToFloat(hexns.substring(with: NSRange.init(location: 6, length: 2))) / 255
return NSColor.init(srgbRed: red, green: green, blue: blue, alpha: alpha)
}
}
<file_sep>/PreviewMarkdown/Constants.swift
/*
* Constants.swift
* PreviewMarkdown
*
* Created by <NAME> on 12/08/2020.
* Copyright © 2023 <NAME>. All rights reserved.
*/
// Combine the app's various constants into a struct
import Foundation
struct BUFFOON_CONSTANTS {
struct ERRORS {
struct CODES {
static let NONE = 0
static let FILE_INACCESSIBLE = 400
static let FILE_WONT_OPEN = 401
static let BAD_MD_STRING = 402
static let BAD_TS_STRING = 403
}
struct MESSAGES {
static let NO_ERROR = "No error"
static let FILE_INACCESSIBLE = "Can't access file"
static let FILE_WONT_OPEN = "Can't open file"
static let BAD_MD_STRING = "Can't get markdown data"
static let BAD_TS_STRING = "Can't access NSTextView's TextStorage"
}
}
struct THUMBNAIL_SIZE {
static let ORIGIN_X = 0
static let ORIGIN_Y = 0
static let WIDTH = 768
static let HEIGHT = 1024
static let ASPECT = 0.75
static let TAG_HEIGHT = 204.8
static let FONT_SIZE = 130.0
}
static let PREVIEW_FONT_SIZE = 16.0
static let THUMBNAIL_FONT_SIZE: Float = 18.0
static let SPACES_FOR_A_TAB = 4
// FROM 1.2.0
static let CODE_COLOUR_INDEX = 0
static let LINK_COLOUR_INDEX = 2
static let CODE_FONT_INDEX = 0
static let BODY_FONT_INDEX = 0
static let FONT_SIZE_OPTIONS: [CGFloat] = [10.0, 12.0, 14.0, 16.0, 18.0, 24.0, 28.0]
// FROM 1.3.0
static let YAML_INDENT = 2
// FROM 1.3.1
static let URL_MAIN = "https://smittytone.net/previewmarkdown/index.html"
static let APP_STORE = "https://apps.apple.com/us/app/previewmarkdown/id1492280469"
static let SUITE_NAME = ".suite.previewmarkdown"
static let TAG_TEXT_SIZE = 180 //124
static let TAG_TEXT_MIN_SIZE = 118
// FROM 1.4.0
static let LINK_COLOUR_HEX = "0096FFFF"
static let HEAD_COLOUR_HEX = "941751FF"
static let CODE_COLOUR_HEX = "00FF00FF"
static let BODY_FONT_NAME = "System"
static let CODE_FONT_NAME = "Courier"
static let SAMPLE_UTI_FILE = "sample.md"
// FROM 1.4.1
static let THUMBNAIL_LINE_COUNT = 40
// FROM 1.4.3
static let APP_CODE_PREVIEWER = "com.bps.PreviewMarkdown.Previewer"
// FROM 1.4.6
struct APP_URLS {
static let PM = "https://apps.apple.com/us/app/previewmarkdown/id1492280469?ls=1"
static let PC = "https://apps.apple.com/us/app/previewcode/id1571797683?ls=1"
static let PY = "https://apps.apple.com/us/app/previewyaml/id1564574724?ls=1"
static let PJ = "https://apps.apple.com/us/app/previewjson/id6443584377?ls=1"
static let PT = "https://apps.apple.com/us/app/previewtext/id1660037028?ls=1"
}
static let WHATS_NEW_PREF = "com-bps-previewmarkdown-do-show-whats-new-"
}
<file_sep>/Thumbnailer/ThumbnailProvider.swift
/*
* ThumbnailProvider.swift
* Thumbnailer
*
* Created by <NAME> on 31/10/2019.
* Copyright © 2023 <NAME>. All rights reserved.
*/
import Cocoa
import QuickLookThumbnailing
class ThumbnailProvider: QLThumbnailProvider {
// MARK:- Private Properties
// FROM 1.4.0
// Add possible errors returned by autorelease pool
private enum ThumbnailerError: Error {
case badFileLoad(String)
case badFileUnreadable(String)
case badGfxBitmap
case badGfxDraw
}
// MARK:- QLThumbnailProvider Required Functions
override func provideThumbnail(for request: QLFileThumbnailRequest, _ handler: @escaping (QLThumbnailReply?, Error?) -> Void) {
/*
* This is the main entry point for the macOS thumbnailing system
*/
// Set the thumbnail frame
// NOTE This is always square, with height matched to width, so adjust
// to a 3:4 aspect ratio to maintain the macOS standard doc icon width
let iconScale: CGFloat = request.scale
let thumbnailFrame: CGRect = NSMakeRect(0.0,
0.0,
CGFloat(BUFFOON_CONSTANTS.THUMBNAIL_SIZE.ASPECT) * request.maximumSize.height,
request.maximumSize.height)
// FROM 1.4.1
// First ensure we are running on Mojave or above - Dark Mode is not supported by earlier versons
let sysVer: OperatingSystemVersion = ProcessInfo.processInfo.operatingSystemVersion
let isMontereyPlus: Bool = (sysVer.majorVersion >= 12)
// FROM 1.3.0
// Place all the remaining code within the closure passed to 'handler()'
handler(QLThumbnailReply.init(contextSize: thumbnailFrame.size) { (context) -> Bool in
// FROM 1.3.0
// Place the key code within an autorelease pool to trap possible memory issues
let result: Result<Bool, ThumbnailerError> = autoreleasepool { () -> Result<Bool, ThumbnailerError> in
// Load the source file using a co-ordinator as we don't know what thread this function
// will be executed in when it's called by macOS' QuickLook code
if FileManager.default.isReadableFile(atPath: request.fileURL.path) {
// Only proceed if the file is accessible from here
do {
// Get the file contents as a string, making sure it's not cached
// as we're not going to read it again any time soon
let data: Data = try Data.init(contentsOf: request.fileURL, options: [.uncached])
// FROM 1.4.3
// Get the string's encoding, or fail back to .utf8
let encoding: String.Encoding = data.stringEncoding ?? .utf8
guard let markdownString: String = String.init(data: data, encoding: encoding) else {
return .failure(ThumbnailerError.badFileLoad(request.fileURL.path))
}
// Instantiate the common code for a thumbnail ('true')
let common: Common = Common.init(true)
// FROM 1.4.1
// Only render the lines *likely* to appear in the thumbnail
let lines: [String] = (markdownString as NSString).components(separatedBy: "\n")
var shortString: String = ""
var gotFrontMatter: Bool = false
var markdownStart: Int = 0
if lines.count < BUFFOON_CONSTANTS.THUMBNAIL_LINE_COUNT {
shortString = markdownString
} else {
// Check for static site YAML/TOML front matter
for i in 0..<lines.count {
if (lines[i].hasPrefix("---") || lines[i].hasPrefix("+++")) && !gotFrontMatter {
// Head YAML/TOML delimiter
gotFrontMatter = true
continue
}
if (lines[i].hasPrefix("---") || lines[i].hasPrefix("+++")) && gotFrontMatter {
// Tail YAML/TOML delimiter: set the start of the Markdown
markdownStart = i + 1
break
}
}
// Count Markdown lines from the start or after any front matter
for i in markdownStart..<lines.count {
// Break at line THUMBNAIL_LINE_COUNT
if (i - markdownStart) >= BUFFOON_CONSTANTS.THUMBNAIL_LINE_COUNT || shortString.count > 3400 { break }
shortString += (lines[i] + "\n")
}
}
// Get the Attributed String
// TODO Can we save some time by reducing the length of the string before
// processing? We don't need all of a long file for the thumbnail, eg.
// 3000 chars or 50 lines?
let markdownAtts: NSAttributedString = common.getAttributedString(shortString, true)
// Set the primary NSTextView drawing frame and a base font size
let markdownFrame: CGRect = NSMakeRect(CGFloat(BUFFOON_CONSTANTS.THUMBNAIL_SIZE.ORIGIN_X),
CGFloat(BUFFOON_CONSTANTS.THUMBNAIL_SIZE.ORIGIN_Y),
CGFloat(BUFFOON_CONSTANTS.THUMBNAIL_SIZE.WIDTH),
CGFloat(BUFFOON_CONSTANTS.THUMBNAIL_SIZE.HEIGHT))
// FROM 1.3.1
// Instantiate an NSTextField to display the NSAttributedString render of the YAML,
// and extend the size of its frame
let markdownTextField: NSTextField = NSTextField.init(labelWithAttributedString: markdownAtts)
markdownTextField.lineBreakMode = .byTruncatingTail
markdownTextField.frame = markdownFrame
// Generate the bitmap from the rendered markdown text view
guard let bodyImageRep: NSBitmapImageRep = markdownTextField.bitmapImageRepForCachingDisplay(in: markdownFrame) else {
return .failure(ThumbnailerError.badGfxBitmap)
}
// Draw the view into the bitmap
markdownTextField.cacheDisplay(in: markdownFrame, to: bodyImageRep)
// FROM 1.2.0
// Also generate text for the bottom-of-thumbnail file type tag,
// if the user has this set as a preference
var tagImageRep: NSBitmapImageRep? = nil
if common.doShowTag && !isMontereyPlus {
// Define the frame of the tag area
let tagFrame: CGRect = NSMakeRect(CGFloat(BUFFOON_CONSTANTS.THUMBNAIL_SIZE.ORIGIN_X),
CGFloat(BUFFOON_CONSTANTS.THUMBNAIL_SIZE.ORIGIN_Y),
CGFloat(BUFFOON_CONSTANTS.THUMBNAIL_SIZE.WIDTH),
CGFloat(BUFFOON_CONSTANTS.THUMBNAIL_SIZE.TAG_HEIGHT))
// Build the tag
let style: NSMutableParagraphStyle = NSMutableParagraphStyle.init()
style.alignment = .center
// Build the string attributes
// FROM 1.3.0 -- do this as a literal
let tagAtts: [NSAttributedString.Key: Any] = [
.paragraphStyle: style,
.font: NSFont.systemFont(ofSize: CGFloat(BUFFOON_CONSTANTS.TAG_TEXT_SIZE)),
.foregroundColor: (NSColor.init(red: 0.58, green: 0.09, blue: 0.32, alpha: 1.0))
]
// FROM 1.3.1
// Instantiate an NSTextField to display the NSAttributedString render of the YAML,
// and extend tbhe size of its frame
let tag: NSAttributedString = NSAttributedString.init(string: "MD", attributes: tagAtts)
let tagTextField: NSTextField = NSTextField.init(labelWithAttributedString: tag)
tagTextField.frame = tagFrame
// Draw the view into the bitmap
if let imageRep: NSBitmapImageRep = tagTextField.bitmapImageRepForCachingDisplay(in: tagFrame) {
tagTextField.cacheDisplay(in: tagFrame, to: imageRep)
tagImageRep = imageRep
}
}
// Alternative drawing code to make use of a supplied context,
// scaling as required (retina vs non-retina screen)
// NOTE 'context' passed in by the caller, ie. macOS QL server
var drawResult: Bool = false
var scaleFrame: CGRect = NSMakeRect(0.0,
0.0,
thumbnailFrame.width * iconScale,
thumbnailFrame.height * iconScale)
if let image: CGImage = bodyImageRep.cgImage {
context.draw(image, in: scaleFrame, byTiling: false)
drawResult = true
}
// Add the tag
if let image: CGImage = tagImageRep?.cgImage {
scaleFrame = NSMakeRect(0.0,
0.0,
thumbnailFrame.width * iconScale,
thumbnailFrame.height * iconScale * 0.2)
context.draw(image, in: scaleFrame, byTiling: false)
}
// Required to prevent 'thread ended before CA actions committed' errors in log
CATransaction.commit()
if drawResult {
return .success(true)
} else {
return .failure(ThumbnailerError.badGfxDraw)
}
//return drawResult
} catch {
// NOP: fall through to error
}
}
// We didn't draw anything because of 'can't find file' error
return .failure(ThumbnailerError.badFileUnreadable(request.fileURL.path))
}
// Pass the outcome up from out of the autorelease
// pool code to the handler as a bool, logging an error
// if appropriate
switch result {
case .success(_):
return true
case .failure(let error):
switch error {
case .badFileUnreadable(let filePath):
NSLog("Could not access file \(filePath)")
case .badFileLoad(let filePath):
NSLog("Could not render file \(filePath)")
default:
NSLog("Could not render thumbnail")
}
}
return false
}, nil)
}
}
<file_sep>/PreviewMarkdown/sample.md
# H1 #
Some body text.
## H2 ##
*Some body text in italic.*
### H3 ###
**Some body text in bold**
#### H4 ####
**Some body text in bold** and then not bold **and then bold again**.
```
code
```
##### H5 #####
1. A list
1. A list
1. A list
###### H6 ######
- A bullet list
- A bullet list
- A bullet list
* A sub bullet list
* A sub bullet list
#### H4 Again
* Point One
* Point Two
## H2 Again ##
Some `preformatted text` in `this line`.
| A | B | C |
| :-- | :-: | --: |
| 1 | 2 | 3 |
### Code ###
func showError(_ errString: String) {
// Relay an error message to its various outlets
NSLog("BUFFOON " + errString)
self.errorReportField.stringValue = errString
self.errorReportField.isHidden = false
}
<file_sep>/PreviewMarkdown/AppDelegate.swift
/*
* AppDelegate.swift
* PreviewMarkdown
*
* Created by <NAME> on 31/10/2019.
* Copyright © 2023 <NAME>. All rights reserved.
*/
import Cocoa
import CoreServices
import WebKit
@NSApplicationMain
final class AppDelegate: NSObject,
NSApplicationDelegate,
URLSessionDelegate,
URLSessionDataDelegate,
WKNavigationDelegate {
// MARK:- Class UI Properies
// Menu Items Tab
@IBOutlet var helpMenu: NSMenuItem!
//@IBOutlet var creditMenuDiscount: NSMenuItem!
//@IBOutlet var creditMenuQLMarkdown: NSMenuItem!
@IBOutlet var helpMenuSwiftyMarkdown: NSMenuItem!
//@IBOutlet var helpMenuAcknowlegdments: NSMenuItem!
@IBOutlet var helpMenuAppStoreRating: NSMenuItem!
// FROM 1.3.0
@IBOutlet var helpMenuYamlSwift: NSMenuItem!
// FROM 1.3.1
@IBOutlet var helpMenuOthersPreviewYaml: NSMenuItem!
// FROM 1.4.0
@IBOutlet var helpMenuOthersPreviewCode: NSMenuItem!
// FROM 1.4.4
@IBOutlet var helpMenuOthersPreviewJson: NSMenuItem!
// FROM 1.4.5
@IBOutlet var helpMenuOthersPreviewText: NSMenuItem!
@IBOutlet var helpMenuOnlineHelp: NSMenuItem!
@IBOutlet var helpMenuReportBug: NSMenuItem!
@IBOutlet var helpMenuWhatsNew: NSMenuItem!
@IBOutlet var mainMenuSettings: NSMenuItem!
// Panel Items
@IBOutlet var versionLabel: NSTextField!
// Windows
@IBOutlet weak var window: NSWindow!
// FROM 1.1.1
// Report Sheet
@IBOutlet weak var reportWindow: NSWindow!
@IBOutlet weak var feedbackText: NSTextField!
@IBOutlet weak var connectionProgress: NSProgressIndicator!
// FROM 1.2.0
// Preferences Sheet
@IBOutlet weak var preferencesWindow: NSWindow!
@IBOutlet weak var fontSizeSlider: NSSlider!
@IBOutlet weak var fontSizeLabel: NSTextField!
@IBOutlet weak var useLightCheckbox: NSButton!
@IBOutlet weak var doShowTagCheckbox: NSButton!
@IBOutlet weak var bodyFontPopup: NSPopUpButton!
@IBOutlet weak var codeFontPopup: NSPopUpButton!
//@IBOutlet weak var codeColourPopup: NSPopUpButton!
// FROM 1.3.0
@IBOutlet weak var showFrontMatterCheckbox: NSButton!
// FROM 1.4.0
@IBOutlet weak var codeColourWell: NSColorWell!
@IBOutlet weak var headColourWell: NSColorWell!
@IBOutlet weak var bodyStylePopup: NSPopUpButton!
@IBOutlet weak var codeStylePopup: NSPopUpButton!
// FROM 1.4.1
@IBOutlet weak var tagInfoTextField: NSTextField!
// FROM 1.2.0
// What's New Sheet
@IBOutlet weak var whatsNewWindow: NSWindow!
@IBOutlet weak var whatsNewWebView: WKWebView!
// MARK:- Private Properies
// FROM 1.1.1
private var feedbackTask: URLSessionTask? = nil
// FROM 1.2.0 -- stores for preferences
internal var whatsNewNav: WKNavigation? = nil
private var previewFontSize: CGFloat = CGFloat(BUFFOON_CONSTANTS.PREVIEW_FONT_SIZE)
private var doShowLightBackground: Bool = false
private var doShowTag: Bool = false
private var localMarkdownUTI: String = "NONE"
// FROM 1.3.0
private var doShowFrontMatter: Bool = false
// FROM 1.3.1
private var appSuiteName: String = MNU_SECRETS.PID + BUFFOON_CONSTANTS.SUITE_NAME
private var feedbackPath: String = MNU_SECRETS.ADDRESS.B
// FROM 1.4.0
private var codeColourHex: String = BUFFOON_CONSTANTS.CODE_COLOUR_HEX
private var headColourHex: String = BUFFOON_CONSTANTS.HEAD_COLOUR_HEX
private var bodyFontName: String = BUFFOON_CONSTANTS.BODY_FONT_NAME
private var codeFontName: String = BUFFOON_CONSTANTS.CODE_FONT_NAME
internal var bodyFonts: [PMFont] = []
internal var codeFonts: [PMFont] = []
// FROM 1.4.1
internal var isMontereyPlus: Bool = false
// FROM 1.4.6
private var havePrefsChanged: Bool = false
// MARK: - Class Lifecycle Functions
func applicationDidFinishLaunching(_ notification: Notification) {
// FROM 1.4.0
// Pre-load fonts
let q: DispatchQueue = DispatchQueue.init(label: "com.bps.previewmarkdown.async-queue")
q.async {
self.asyncGetFonts()
}
// FROM 1.2.0
// Set application group-level defaults
registerPreferences()
// FROM 1.4.1
recordSystemState()
// FROM 1.2.0
// Get the local UTI for markdown files
self.localMarkdownUTI = getLocalFileUTI(BUFFOON_CONSTANTS.SAMPLE_UTI_FILE)
// FROM 1.0.3
// Add the version number to the panel
let version: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
let build: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String
versionLabel.stringValue = "Version \(version) (\(build))"
// From 1.0.4
// Disable the Help menu Spotlight features
let dummyHelpMenu: NSMenu = NSMenu.init(title: "Dummy")
let theApp = NSApplication.shared
theApp.helpMenu = dummyHelpMenu
// FROM 1.0.2
// Centre window and display
self.window.center()
self.window.makeKeyAndOrderFront(self)
// FROM 1.2.0
// Show 'What's New' if we need to
// (and set up the WKWebBiew: no elasticity, horizontal scroller)
// NOTE Has to take place at the end of the function
doShowWhatsNew(self)
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
// When the main window closed, shut down the app
return true
}
// MARK:- Action Functions
@IBAction private func doClose(_ sender: Any) {
// FROM 1.3.0
// Reset the QL thumbnail cache... just in case
_ = runProcess(app: "/usr/bin/qlmanage", with: ["-r", "cache"])
// FROM 1.4.6
// Check for open panels
if self.preferencesWindow.isVisible {
if self.havePrefsChanged {
let alert: NSAlert = showAlert("You have unsaved settings",
"Do you wish to cancel and save them, or quit the app anyway?",
false)
alert.addButton(withTitle: "Quit")
alert.addButton(withTitle: "Cancel")
alert.beginSheetModal(for: self.preferencesWindow) { (response: NSApplication.ModalResponse) in
if response == NSApplication.ModalResponse.alertFirstButtonReturn {
// The user clicked 'Quit'
self.preferencesWindow.close()
self.window.close()
}
}
return
}
self.preferencesWindow.close()
}
if self.whatsNewWindow.isVisible {
self.whatsNewWindow.close()
}
if self.reportWindow.isVisible {
if self.feedbackText.stringValue.count > 0 {
let alert: NSAlert = showAlert("You have unsent feedback",
"Do you wish to cancel and send it, or quit the app anyway?",
false)
alert.addButton(withTitle: "Quit")
alert.addButton(withTitle: "Cancel")
alert.beginSheetModal(for: self.reportWindow) { (response: NSApplication.ModalResponse) in
if response == NSApplication.ModalResponse.alertFirstButtonReturn {
// The user clicked 'Quit'
self.reportWindow.close()
self.window.close()
}
}
return
}
self.reportWindow.close()
}
// Close the window... which will trigger an app closure
self.window.close()
}
@IBAction @objc private func doShowSites(sender: Any) {
// Open the websites for contributors
let item: NSMenuItem = sender as! NSMenuItem
var path: String = BUFFOON_CONSTANTS.URL_MAIN
// FROM 1.1.0 -- bypass unused items
if item == self.helpMenuSwiftyMarkdown {
path = "https://github.com/SimonFairbairn/SwiftyMarkdown"
} else if item == self.helpMenuAppStoreRating {
path = BUFFOON_CONSTANTS.APP_STORE + "?action=write-review"
} else if item == self.helpMenuYamlSwift {
// FROM 1.3.0
path = "https://github.com/behrang/YamlSwift"
} else if item == self.helpMenuOnlineHelp {
// FROM 1.3.0
path += "#how-to-use-previewmarkdown"
} else if item == self.helpMenuOthersPreviewYaml {
// FROM 1.3.1
path = BUFFOON_CONSTANTS.APP_URLS.PY
} else if item == self.helpMenuOthersPreviewCode {
// FROM 1.4.0
path = BUFFOON_CONSTANTS.APP_URLS.PC
} else if item == self.helpMenuOthersPreviewJson {
// FROM 1.4.4
path = BUFFOON_CONSTANTS.APP_URLS.PJ
} else if item == self.helpMenuOthersPreviewText {
// FROM 1.4.6
path = BUFFOON_CONSTANTS.APP_URLS.PT
}
// Open the selected website
NSWorkspace.shared.open(URL.init(string:path)!)
}
@IBAction private func doOpenSysPrefs(sender: Any) {
// FROM 1.1.0
// Open the System Preferences app at the Extensions pane
NSWorkspace.shared.open(URL(fileURLWithPath: "/System/Library/PreferencePanes/Extensions.prefPane"))
}
// MARK: - Report Functions
@IBAction @objc private func showFeedbackWindow(sender: Any?) {
// FROM 1.1.1
// Display a window in which the user can submit feedback
// FROM 1.4.6
// Disable menus we don't want used when the panel is open
hidePanelGenerators()
// Reset the UI
self.connectionProgress.stopAnimation(self)
self.feedbackText.stringValue = ""
// Present the window
self.window.beginSheet(self.reportWindow, completionHandler: nil)
}
@IBAction @objc private func doCancelReportWindow(sender: Any) {
// FROM 1.1.1
// User has clicked 'Cancel', so just close the sheet
self.connectionProgress.stopAnimation(self)
self.window.endSheet(self.reportWindow)
// FROM 1.4.6
// Restore menus
showPanelGenerators()
}
@IBAction @objc private func doSendFeedback(sender: Any) {
// FROM 1.1.1
// User clicked 'Send' so get the message (if there is one) from the text field and send it
let feedback: String = self.feedbackText.stringValue
if feedback.count > 0 {
// Start the connection indicator if it's not already visible
self.connectionProgress.startAnimation(self)
self.feedbackTask = sendFeedback(feedback)
if self.feedbackTask != nil {
// We have a valid URL Session Task, so start it to send
self.feedbackTask!.resume()
return
} else {
// Report the error
sendFeedbackError()
}
}
// No feedback, so close the sheet
self.window.endSheet(self.reportWindow)
// FROM 1.4.6
// Restore menus
showPanelGenerators()
// NOTE sheet closes asynchronously unless there was no feedback to send
}
// MARK: - Preferences Functions
/**
Initialise and display the **Preferences** sheet.
FROM 1.2.0
- Parameters:
- sender: The source of the action.
*/
@IBAction private func doShowPreferences(sender: Any) {
// FROM 1.4.6
// Reset changed prefs flag
self.havePrefsChanged = false
// FROM 1.4.6
// Disable menus we don't want used when the panel is open
hidePanelGenerators()
// The suite name is the app group name, set in each extension's entitlements, and the host app's
if let defaults = UserDefaults(suiteName: self.appSuiteName) {
self.previewFontSize = CGFloat(defaults.float(forKey: "com-bps-previewmarkdown-base-font-size"))
self.doShowLightBackground = defaults.bool(forKey: "com-bps-previewmarkdown-do-use-light")
self.doShowTag = defaults.bool(forKey: "com-bps-previewmarkdown-do-show-tag")
// FROM 1.3.0
self.doShowFrontMatter = defaults.bool(forKey: "com-bps-previewmarkdown-do-show-front-matter")
// FROM 1.4.0
self.codeColourHex = defaults.string(forKey: "com-bps-previewmarkdown-code-colour-hex") ?? BUFFOON_CONSTANTS.CODE_COLOUR_HEX
self.headColourHex = defaults.string(forKey: "com-bps-previewmarkdown-head-colour-hex") ?? BUFFOON_CONSTANTS.HEAD_COLOUR_HEX
self.codeFontName = defaults.string(forKey: "com-bps-previewmarkdown-code-font-name") ?? BUFFOON_CONSTANTS.CODE_FONT_NAME
self.bodyFontName = defaults.string(forKey: "com-bps-previewmarkdown-body-font-name") ?? BUFFOON_CONSTANTS.BODY_FONT_NAME
}
// Get the menu item index from the stored value
// NOTE The other values are currently stored as indexes -- should this be the same?
let index: Int = BUFFOON_CONSTANTS.FONT_SIZE_OPTIONS.lastIndex(of: self.previewFontSize) ?? 3
self.fontSizeSlider.floatValue = Float(index)
self.fontSizeLabel.stringValue = "\(Int(BUFFOON_CONSTANTS.FONT_SIZE_OPTIONS[index]))pt"
self.useLightCheckbox.state = self.doShowLightBackground ? .on : .off
self.doShowTagCheckbox.state = self.doShowTag ? .on : .off
// FROM 1.3.0
self.showFrontMatterCheckbox.state = self.doShowFrontMatter ? .on : .off
// FROM 1.4.0
// Set the two colour wells
self.codeColourWell.color = NSColor.hexToColour(self.codeColourHex)
self.headColourWell.color = NSColor.hexToColour(self.headColourHex)
// FROM 1.4.0
// Extend font selection to all available fonts
// First, the body text font...
self.bodyFontPopup.removeAllItems()
self.bodyStylePopup.isEnabled = false
for i: Int in 0..<self.bodyFonts.count {
let font: PMFont = self.bodyFonts[i]
self.bodyFontPopup.addItem(withTitle: font.displayName)
}
selectFontByPostScriptName(self.bodyFontName, true)
// ...and the code font
self.codeFontPopup.removeAllItems()
self.codeStylePopup.isEnabled = false
for i: Int in 0..<self.codeFonts.count {
let font: PMFont = self.codeFonts[i]
self.codeFontPopup.addItem(withTitle: font.displayName)
}
selectFontByPostScriptName(self.codeFontName, false)
// FROM 1.4.1
// Hide tag selection on Monterey
self.doShowTagCheckbox.isEnabled = !self.isMontereyPlus
if (isMontereyPlus) {
// FROM 1.4.2
// Hide the unneeded options
self.tagInfoTextField.isHidden = true
self.doShowTagCheckbox.isHidden = true
//self.doShowTagCheckbox.toolTip = "Not available in macOS 12 and up"
//self.tagInfoTextField.stringValue = "macOS 12 adds its own thumbnail file extension tags, so this option is no longer available."
}
// Display the sheet
self.window.beginSheet(self.preferencesWindow, completionHandler: nil)
}
/**
Called when the user selects a font from either list.
FROM 1.4.0
- Parameters:
- sender: The source of the action.
*/
@IBAction private func doUpdateFonts(sender: Any) {
let item: NSPopUpButton = sender as! NSPopUpButton
setStylePopup(item == self.bodyFontPopup)
self.havePrefsChanged = true
}
/**
When the font size slider is moved and released, this function updates the font size readout.
FROM 1.2.0
- Parameters:
- sender: The source of the action.
*/
@IBAction private func doMoveSlider(sender: Any) {
let index: Int = Int(self.fontSizeSlider.floatValue)
self.fontSizeLabel.stringValue = "\(Int(BUFFOON_CONSTANTS.FONT_SIZE_OPTIONS[index]))pt"
self.havePrefsChanged = true
}
/**
Close the **Preferences** sheet without saving.
FROM 1.2.0
- Parameters:
- sender: The source of the action.
*/
@IBAction private func doClosePreferences(sender: Any) {
// FROM 1.4.0
// Close the colour selection panel if it's open
if self.codeColourWell.isActive {
NSColorPanel.shared.close()
self.codeColourWell.deactivate()
}
if self.headColourWell.isActive {
NSColorPanel.shared.close()
self.headColourWell.deactivate()
}
self.window.endSheet(self.preferencesWindow)
// FROM 1.4.6
// Restore menus
showPanelGenerators()
}
/**
Close the **Preferences** sheet and save any settings that have changed.
FROM 1.2.0
- Parameters:
- sender: The source of the action.
*/
@IBAction private func doSavePreferences(sender: Any) {
if let defaults = UserDefaults(suiteName: self.appSuiteName) {
let newValue: CGFloat = BUFFOON_CONSTANTS.FONT_SIZE_OPTIONS[Int(self.fontSizeSlider.floatValue)]
if newValue != self.previewFontSize {
defaults.setValue(newValue,
forKey: "com-bps-previewmarkdown-base-font-size")
}
var state: Bool = self.useLightCheckbox.state == .on
if self.doShowLightBackground != state {
defaults.setValue(state,
forKey: "com-bps-previewmarkdown-do-use-light")
}
state = self.doShowTagCheckbox.state == .on
if self.doShowTag != state {
defaults.setValue(state,
forKey: "com-bps-previewmarkdown-do-show-tag")
}
// FROM 1.3.0
// Get the YAML checkbox value and update
state = self.showFrontMatterCheckbox.state == .on
if self.doShowFrontMatter != state {
defaults.setValue(state,
forKey: "com-bps-previewmarkdown-do-show-front-matter")
}
// FROM 1.4.0
// Get any colour changes
let newCodeColour: String = self.codeColourWell.color.hexString
if newCodeColour != self.codeColourHex {
self.codeColourHex = newCodeColour
defaults.setValue(newCodeColour,
forKey: "com-bps-previewmarkdown-code-colour-hex")
}
let newHeadColour: String = self.headColourWell.color.hexString
if newHeadColour != self.headColourHex {
self.headColourHex = newHeadColour
defaults.setValue(newHeadColour,
forKey: "com-bps-previewmarkdown-head-colour-hex")
}
// FROM 1.4.0
// Get any font changes
if let psname: String = getPostScriptName(false) {
if psname != self.codeFontName {
self.codeFontName = psname
defaults.setValue(psname, forKey: "com-bps-previewmarkdown-code-font-name")
}
}
if let psname = getPostScriptName(true) {
if psname != self.bodyFontName {
self.bodyFontName = psname
defaults.setValue(psname, forKey: "com-bps-previewmarkdown-body-font-name")
}
}
}
// FROM 1.4.0
// Close the colour selection panel if it's open
if self.codeColourWell.isActive {
NSColorPanel.shared.close()
self.codeColourWell.deactivate()
}
if self.headColourWell.isActive {
NSColorPanel.shared.close()
self.headColourWell.deactivate()
}
// Remove the sheet now we have the data
self.window.endSheet(self.preferencesWindow)
// FROM 1.4.6
// Restore menus
showPanelGenerators()
}
/**
Generic IBAction for any Prefs control to register it has been used.
- Parameters:
- sender: The source of the action.
*/
@IBAction private func controlClicked(sender: Any) {
self.havePrefsChanged = true
}
// MARK: - What's New Functions
/**
Show the **What's New** sheet.
If we're on a new, non-patch version, of the user has explicitly
asked to see it with a menu click See if we're coming from a menu click
(`sender != self`) or directly in code from *appDidFinishLoading()*
(`sender == self`)
- Parameters:
- sender: The source of the action.
*/
@IBAction private func doShowWhatsNew(_ sender: Any) {
// See if we're coming from a menu click (sender != self) or
// directly in code from 'appDidFinishLoading()' (sender == self)
var doShowSheet: Bool = type(of: self) != type(of: sender)
if !doShowSheet {
// We are coming from the 'appDidFinishLoading()' so check
// if we need to show the sheet by the checking the prefs
if let defaults = UserDefaults(suiteName: self.appSuiteName) {
// Get the version-specific preference key
let key: String = BUFFOON_CONSTANTS.WHATS_NEW_PREF + getVersion()
doShowSheet = defaults.bool(forKey: key)
}
}
// Configure and show the sheet
if doShowSheet {
// FROM 1.4.6
// Disable menus we don't want used when the panel is open
hidePanelGenerators()
// First, get the folder path
let htmlFolderPath = Bundle.main.resourcePath! + "/new"
// Set WebView properties: limit scrollers and elasticity
self.whatsNewWebView.enclosingScrollView?.hasHorizontalScroller = false
self.whatsNewWebView.enclosingScrollView?.horizontalScrollElasticity = .none
self.whatsNewWebView.enclosingScrollView?.verticalScrollElasticity = .none
// Just in case, make sure we can load the file
if FileManager.default.fileExists(atPath: htmlFolderPath) {
let htmlFileURL = URL.init(fileURLWithPath: htmlFolderPath + "/new.html")
let htmlFolderURL = URL.init(fileURLWithPath: htmlFolderPath)
self.whatsNewNav = self.whatsNewWebView.loadFileURL(htmlFileURL, allowingReadAccessTo: htmlFolderURL)
}
}
}
@IBAction private func doCloseWhatsNew(_ sender: Any) {
// FROM 1.2.0
// Close the 'What's New' sheet, making sure we clear the preference flag for this minor version,
// so that the sheet is not displayed next time the app is run (unless the version changes)
// Close the sheet
self.window.endSheet(self.whatsNewWindow)
// Scroll the web view back to the top
self.whatsNewWebView.evaluateJavaScript("window.scrollTo(0,0)", completionHandler: nil)
// Set this version's preference
if let defaults = UserDefaults(suiteName: self.appSuiteName) {
let key: String = "com-bps-previewmarkdown-do-show-whats-new-" + getVersion()
defaults.setValue(false, forKey: key)
#if DEBUG
print("\(key) reset back to true")
defaults.setValue(true, forKey: key)
#endif
}
// FROM 1.4.6
// Restore menus
showPanelGenerators()
}
// MARK: - Misc Functions
/**
Configure the app's preferences with default values.
FROM 1.2.0
*/
private func registerPreferences() {
if let defaults = UserDefaults(suiteName: self.appSuiteName) {
// Check if each preference value exists -- set if it doesn't
// Preview body font size, stored as a CGFloat
// Default: 16.0
let bodyFontSizeDefault: Any? = defaults.object(forKey: "com-bps-previewmarkdown-base-font-size")
if bodyFontSizeDefault == nil {
defaults.setValue(CGFloat(BUFFOON_CONSTANTS.PREVIEW_FONT_SIZE),
forKey: "com-bps-previewmarkdown-base-font-size")
}
// Thumbnail view base font size, stored as a CGFloat, not currently used
// Default: 14.0
let thumbFontSizeDefault: Any? = defaults.object(forKey: "com-bps-previewmarkdown-thumb-font-size")
if thumbFontSizeDefault == nil {
defaults.setValue(CGFloat(BUFFOON_CONSTANTS.THUMBNAIL_FONT_SIZE),
forKey: "com-bps-previewmarkdown-thumb-font-size")
}
// Use light background even in dark mode, stored as a bool
// Default: false
let useLightDefault: Any? = defaults.object(forKey: "com-bps-previewmarkdown-do-use-light")
if useLightDefault == nil {
defaults.setValue(false,
forKey: "com-bps-previewmarkdown-do-use-light")
}
// Show the file identity ('tag') on Finder thumbnails
// Default: false (from 1.4.1)
let showTagDefault: Any? = defaults.object(forKey: "com-bps-previewmarkdown-do-show-tag")
if showTagDefault == nil {
defaults.setValue(false,
forKey: "com-bps-previewmarkdown-do-show-tag")
}
// Show the What's New sheet
// Default: true
// This is a version-specific preference suffixed with, eg, '-2-3'. Once created
// this will persist, but with each new major and/or minor version, we make a
// new preference that will be read by 'doShowWhatsNew()' to see if the sheet
// should be shown this run
let key: String = "com-bps-previewmarkdown-do-show-whats-new-" + getVersion()
let showNewDefault: Any? = defaults.object(forKey: key)
if showNewDefault == nil {
defaults.setValue(true, forKey: key)
}
// FROM 1.3.0
// Show any YAML front matter, if present
// Default: true
let showFrontMatterDefault: Any? = defaults.object(forKey: "com-bps-previewmarkdown-do-show-front-matter")
if showFrontMatterDefault == nil {
defaults.setValue(true, forKey: "com-bps-previewmarkdown-do-show-front-matter")
}
// FROM 1.4.0
// Colour of links in the preview, stored as hex string
let linkColourDefault: Any? = defaults.object(forKey: "com-bps-previewmarkdown-link-colour-hex")
if linkColourDefault == nil {
defaults.setValue(BUFFOON_CONSTANTS.LINK_COLOUR_HEX,
forKey: "com-bps-previewmarkdown-link-colour-hex")
}
// FROM 1.4.0
// Colour of code blocks in the preview, stored as hex string
let codeColourDefault: Any? = defaults.object(forKey: "com-bps-previewmarkdown-code-colour-hex")
if codeColourDefault == nil {
defaults.setValue(BUFFOON_CONSTANTS.CODE_COLOUR_HEX,
forKey: "com-bps-previewmarkdown-code-colour-hex")
}
// FROM 1.4.0
// Colour of headings in the preview, stored as hex string
let headColourDefault: Any? = defaults.object(forKey: "com-bps-previewmarkdown-head-colour-hex")
if headColourDefault == nil {
defaults.setValue(BUFFOON_CONSTANTS.HEAD_COLOUR_HEX,
forKey: "com-bps-previewmarkdown-head-colour-hex")
}
// FROM 1.4.0
// Font for body test in the preview, stored as a PostScript name
let bodyFontDefault: Any? = defaults.object(forKey: "com-bps-previewmarkdown-body-font-name")
if bodyFontDefault == nil {
defaults.setValue(BUFFOON_CONSTANTS.BODY_FONT_NAME,
forKey: "com-bps-previewmarkdown-body-font-name")
}
// FROM 1.4.0
// Font for code blocks in the preview, stored as a PostScript name
let codeFontDefault: Any? = defaults.object(forKey: "com-bps-previewmarkdown-code-font-name")
if codeFontDefault == nil {
defaults.setValue(BUFFOON_CONSTANTS.CODE_FONT_NAME,
forKey: "com-bps-previewmarkdown-code-font-name")
}
}
}
private func sendFeedback(_ feedback: String) -> URLSessionTask? {
// FROM 1.2.0
// Break out into separate function
// Send the string etc.
// First get the data we need to build the user agent string
let userAgent: String = getUserAgentForFeedback()
let endPoint: String = MNU_SECRETS.ADDRESS.A
// Get the date as a string
let dateString: String = getDateForFeedback()
// Assemble the message string
let dataString: String = """
*FEEDBACK REPORT*
*Date:* \(dateString)
*User Agent:* \(userAgent)
*UTI:* \(self.localMarkdownUTI)
*FEEDBACK:*
\(feedback)
"""
// Build the data we will POST:
let dict: NSMutableDictionary = NSMutableDictionary()
dict.setObject(dataString,
forKey: NSString.init(string: "text"))
dict.setObject(true, forKey: NSString.init(string: "mrkdwn"))
// Make and return the HTTPS request for sending
if let url: URL = URL.init(string: self.feedbackPath + endPoint) {
var request: URLRequest = URLRequest.init(url: url)
request.httpMethod = "POST"
do {
request.httpBody = try JSONSerialization.data(withJSONObject: dict,
options:JSONSerialization.WritingOptions.init(rawValue: 0))
request.addValue(userAgent, forHTTPHeaderField: "User-Agent")
request.addValue("application/json", forHTTPHeaderField: "Content-type")
let config: URLSessionConfiguration = URLSessionConfiguration.ephemeral
let session: URLSession = URLSession.init(configuration: config,
delegate: self,
delegateQueue: OperationQueue.main)
return session.dataTask(with: request)
} catch {
// Fall through to error condition
}
}
return nil
}
}
<file_sep>/PreviewMarkdown/PMFont.swift
/*
* PMFont.swift
* PreviewApps
*
* Created by <NAME> on 02/07/2021.
* Copyright © 2023 <NAME>. All rights reserved.
*/
import Foundation
/**
Internal font record structure.
*/
struct PMFont {
var postScriptName: String = ""
var displayName: String = ""
var styleName: String = ""
var traits: UInt = 0
var styles: [PMFont]? = nil
}
<file_sep>/PreviewMarkdown/GenericExtensions.swift
/*
* GenericExtensions.swift
* PreviewApps
*
* These functions can be used by all PreviewApps
*
* Created by <NAME> on 18/06/2021.
* Copyright © 2023 <NAME>. All rights reserved.
*/
import Foundation
import Cocoa
import WebKit
import UniformTypeIdentifiers
extension AppDelegate {
// MARK: - Process Handling Functions
/**
Generic macOS process creation and run function.
Make sure we clear the preference flag for this minor version, so that
the sheet is not displayed next time the app is run (unless the version changes)
- Parameters:
- app: The location of the app.
- with: Array of arguments to pass to the app.
- Returns: `true` if the operation was successful, otherwise `false`.
*/
internal func runProcess(app path: String, with args: [String]) -> Bool {
let task: Process = Process()
task.executableURL = URL.init(fileURLWithPath: path)
task.arguments = args
// Pipe out the output to avoid putting it in the log
let outputPipe = Pipe()
task.standardOutput = outputPipe
task.standardError = outputPipe
do {
try task.run()
} catch {
return false
}
// Block until the task has completed (short tasks ONLY)
task.waitUntilExit()
if !task.isRunning {
if (task.terminationStatus != 0) {
// Command failed -- collect the output if there is any
let outputHandle = outputPipe.fileHandleForReading
var outString: String = ""
if let line = String(data: outputHandle.availableData, encoding: String.Encoding.utf8) {
outString = line
}
if outString.count > 0 {
print("\(outString)")
} else {
print("Error", "Exit code \(task.terminationStatus)")
}
return false
}
}
return true
}
// MARK: - Misc Functions
/**
Present an error message specific to sending feedback.
This is called from multiple locations: if the initial request can't be created,
there was a send failure, or a server error.
*/
internal func sendFeedbackError() {
let alert: NSAlert = showAlert("Feedback Could Not Be Sent",
"Unfortunately, your comments could not be send at this time. Please try again later.")
alert.beginSheetModal(for: self.reportWindow) { (resp) in
// Restore menus
self.showPanelGenerators()
}
}
/**
Generic alert generator.
- Parameters:
- head: The alert's title.
- message: The alert's message.
- addOkButton: Should we add an OK button?
- Returns: The NSAlert.
*/
internal func showAlert(_ head: String, _ message: String, _ addOkButton: Bool = true) -> NSAlert {
let alert: NSAlert = NSAlert()
alert.messageText = head
alert.informativeText = message
if addOkButton { alert.addButton(withTitle: "OK") }
return alert
}
/**
Build a basic 'major.manor' version string for prefs usage.
- Returns: The version string.
*/
internal func getVersion() -> String {
let version: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
let parts: [String] = (version as NSString).components(separatedBy: ".")
return parts[0] + "-" + parts[1]
}
/**
Build a date string string for feedback usage.
- Returns: The date string.
*/
internal func getDateForFeedback() -> String {
let date: Date = Date()
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
return dateFormatter.string(from: date)
}
/**
Build a user-agent string string for feedback usage.
- Returns: The user-agent string.
*/
internal func getUserAgentForFeedback() -> String {
// Refactor code out into separate function for clarity
let sysVer: OperatingSystemVersion = ProcessInfo.processInfo.operatingSystemVersion
let bundle: Bundle = Bundle.main
let app: String = bundle.object(forInfoDictionaryKey: "CFBundleExecutable") as! String
let version: String = bundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String
let build: String = bundle.object(forInfoDictionaryKey: "CFBundleVersion") as! String
return "\(app)/\(version)-\(build) (macOS/\(sysVer.majorVersion).\(sysVer.minorVersion).\(sysVer.patchVersion))"
}
/**
Read back the host system's registered UTI for the specified file.
This is not PII. It used solely for debugging purposes
- Parameters:
- filename: The file we'll use to get the UTI.
- Returns: The file's UTI.
*/
internal func getLocalFileUTI(_ filename: String) -> String {
var localUTI: String = "NONE"
let samplePath = Bundle.main.resourcePath! + "/" + filename
if FileManager.default.fileExists(atPath: samplePath) {
// Create a URL reference to the sample file
let sampleURL = URL.init(fileURLWithPath: samplePath)
do {
// Read back the UTI from the URL
// Use Big Sur's UTType API
if #available(macOS 11, *) {
if let uti: UTType = try sampleURL.resourceValues(forKeys: [.contentTypeKey]).contentType {
localUTI = uti.identifier
}
} else {
// NOTE '.typeIdentifier' yields an optional
if let uti: String = try sampleURL.resourceValues(forKeys: [.typeIdentifierKey]).typeIdentifier {
localUTI = uti
}
}
} catch {
// NOP
}
}
return localUTI
}
/**
Disable all panel-opening menu items.
*/
internal func hidePanelGenerators() {
self.helpMenuReportBug.isEnabled = false
self.helpMenuWhatsNew.isEnabled = false
self.mainMenuSettings.isEnabled = false
}
/**
Enable all panel-opening menu items.
*/
internal func showPanelGenerators() {
self.helpMenuReportBug.isEnabled = true
self.helpMenuWhatsNew.isEnabled = true
self.mainMenuSettings.isEnabled = true
}
/**
Get system and state information and record it for use during run.
*/
internal func recordSystemState() {
// First ensure we are running on Mojave or above - Dark Mode is not supported by earlier versons
let sysVer: OperatingSystemVersion = ProcessInfo.processInfo.operatingSystemVersion
self.isMontereyPlus = (sysVer.majorVersion >= 12)
}
/**
Determine whether the host Mac is in light mode.
- Returns: `true` if the Mac is in light mode, otherwise `false`.
*/
internal func isMacInLightMode() -> Bool {
let appearNameString: String = NSApp.effectiveAppearance.name.rawValue
return (appearNameString == "NSAppearanceNameAqua")
}
// MARK: - URLSession Delegate Functions
func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
// Some sort of connection error - report it
self.connectionProgress.stopAnimation(self)
sendFeedbackError()
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
// The operation to send the comment completed
self.connectionProgress.stopAnimation(self)
if let _ = error {
// An error took place - report it
sendFeedbackError()
} else {
// The comment was submitted successfully
let alert: NSAlert = showAlert("Thanks For Your Feedback!",
"Your comments have been received and we’ll take a look at them shortly.")
alert.beginSheetModal(for: self.reportWindow) { (resp) in
// Close the feedback window when the modal alert returns
let _: Timer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: false) { timer in
self.window.endSheet(self.reportWindow)
self.showPanelGenerators()
}
}
}
}
// MARK: - WKWebNavigation Delegate Functions
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
// Asynchronously show the sheet once the HTML has loaded
// (triggered by delegate method)
if let nav = self.whatsNewNav {
if nav == navigation {
// Display the sheet
self.window.beginSheet(self.whatsNewWindow, completionHandler: nil)
}
}
}
}
extension NSApplication {
func isMacInLightMode() -> Bool {
return (self.effectiveAppearance.name.rawValue == "NSAppearanceNameAqua")
}
}
|
0ffc9b32ea25767d856fba5616e81a1639e72daa
|
[
"Swift",
"Markdown"
] | 12
|
Swift
|
smittytone/PreviewMarkdown
|
75c2adad3ae148224b0899c1ad947dd589fc4386
|
e95f5265b6c81cb568c5eb8839a2eccc447b0740
|
refs/heads/dev
|
<file_sep>import fecha from 'element-ui/src/utils/date';
import { t } from 'element-ui/src/locale';
const weeks = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
const months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];
const newArray = function(start, end) {
let result = [];
for (let i = start; i <= end; i++) {
result.push(i);
}
return result;
};
export const getI18nSettings = (timezone = 'local') => {
return {
dayNamesShort: weeks.map(week => t(`el.datepicker.weeks.${ week }`)),
dayNames: weeks.map(week => t(`el.datepicker.weeks.${ week }`)),
monthNamesShort: months.map(month => t(`el.datepicker.months.${ month }`)),
monthNames: months.map((month, index) => t(`el.datepicker.month${ index + 1 }`)),
amPm: ['am', 'pm'],
timezone
};
};
export const toDate = function(date, timezone) {
return isDate(date) ? newDate(date, timezone) : null;
};
export const isDate = function(date) {
if (date === null || date === undefined) return false;
if (isNaN(new Date(date).getTime())) return false;
if (Array.isArray(date)) return false; // deal with `new Date([ new Date() ]) -> new Date()`
return true;
};
export const isDateObject = function(val) {
return val instanceof Date;
};
export const formatDate = function(date, format, timezone = 'local') {
date = toDate(date);
if (!date) return '';
return fecha.format(date, format || 'yyyy-MM-dd', getI18nSettings(timezone));
};
export const parseDate = function(string, format, timezone = 'local') {
return fecha.parse(string, format || 'yyyy-MM-dd', getI18nSettings(timezone));
};
export const getDayCountOfMonth = function(year, month) {
if (month === 3 || month === 5 || month === 8 || month === 10) {
return 30;
}
if (month === 1) {
if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {
return 29;
} else {
return 28;
}
}
return 31;
};
export const getDayCountOfYear = function(year) {
const isLeapYear = year % 400 === 0 || (year % 100 !== 0 && year % 4 === 0);
return isLeapYear ? 366 : 365;
};
export const getFirstDayOfMonth = function(date, timezone = 'local') {
const temp = new Date(date.getTime());
setDate(temp, 1, timezone);
return getDay(temp, timezone);
};
// see: https://stackoverflow.com/questions/3674539/incrementing-a-date-in-javascript
// {prev, next} Date should work for Daylight Saving Time
// Adding 24 * 60 * 60 * 1000 does not work in the above scenario
export const prevDate = function(date, timezone, amount = 1) {
return newDate([getFullYear(date, timezone), getMonth(date, timezone), getDate(date, timezone) - amount], timezone);
};
export const nextDate = function(date, timezone, amount = 1) {
return newDate([getFullYear(date, timezone), getMonth(date, timezone), getDate(date, timezone) + amount], timezone);
};
export const getStartDateOfMonth = function(year, month, timezone = 'local') {
const result = newDate([year, month, 1], timezone);
const day = getDay(result, timezone);
if (day === 0) {
return prevDate(result, timezone, 7);
} else {
return prevDate(result, timezone, day);
}
};
export const getWeekNumber = function(src, timezone = 'local') {
if (!isDate(src)) return null;
const date = new Date(src.getTime());
setHours(date, [0, 0, 0, 0], timezone);
// Thursday in current week decides the year.
setDate(date, getDate(date, timezone) + 3 - (getDay(date, timezone) + 6) % 7, timezone);
// January 4 is always in week 1.
const week1 = newDate([getFullYear(date, timezone), 0, 4], timezone);
// Adjust to Thursday in week 1 and count number of weeks from date to week 1.
// Rounding should be fine for Daylight Saving Time. Its shift should never be more than 12 hours.
return 1 + Math.round(((date.getTime() - week1.getTime()) / 86400000 - 3 + (getDay(week1, timezone) + 6) % 7) / 7);
};
export const getRangeHours = function(ranges, timezone = 'local') {
const hours = [];
let disabledHours = [];
(ranges || []).forEach(range => {
const value = range.map(date => getHours(date, timezone));
disabledHours = disabledHours.concat(newArray(value[0], value[1]));
});
if (disabledHours.length) {
for (let i = 0; i < 24; i++) {
hours[i] = disabledHours.indexOf(i) === -1;
}
} else {
for (let i = 0; i < 24; i++) {
hours[i] = false;
}
}
return hours;
};
export const getPrevMonthLastDays = (date, amount, timezone = 'local') => {
if (amount <= 0) return [];
const temp = new Date(date.getTime());
setDate(temp, 0, timezone);
const lastDay = getDate(temp, timezone);
return range(amount).map((_, index) => lastDay - (amount - index - 1));
};
export const getMonthDays = (date, timezone = 'local') => {
const temp = newDate([getFullYear(date, timezone), getMonth(date, timezone) + 1, 0], timezone);
const days = getDate(temp, timezone);
return range(days).map((_, index) => index + 1);
};
function setRangeData(arr, start, end, value) {
for (let i = start; i < end; i++) {
arr[i] = value;
}
}
export const getRangeMinutes = function(ranges, hour, timezone = 'local') {
const minutes = new Array(60);
if (ranges.length > 0) {
ranges.forEach(range => {
const start = range[0];
const end = range[1];
const startHour = getHours(start, timezone);
const startMinute = getMinutes(start, timezone);
const endHour = getHours(end, timezone);
const endMinute = getMinutes(end, timezone);
if (startHour === hour && endHour !== hour) {
setRangeData(minutes, startMinute, 60, true);
} else if (startHour === hour && endHour === hour) {
setRangeData(minutes, startMinute, endMinute + 1, true);
} else if (startHour !== hour && endHour === hour) {
setRangeData(minutes, 0, endMinute + 1, true);
} else if (startHour < hour && endHour > hour) {
setRangeData(minutes, 0, 60, true);
}
});
} else {
setRangeData(minutes, 0, 60, true);
}
return minutes;
};
export const range = function(n) {
// see https://stackoverflow.com/questions/3746725/create-a-javascript-array-containing-1-n
return Array.apply(null, {length: n}).map((_, n) => n);
};
export const modifyDate = function(date, y, m, d, timezone = 'local') {
return newDate([y, m, d, getHours(date, timezone), getMinutes(date, timezone), getSeconds(date, timezone), getMilliseconds(date, timezone)], timezone);
};
export const modifyTime = function(date, h, m, s, timezone = 'local') {
return newDate([getFullYear(date, timezone), getMonth(date, timezone), getDate(date, timezone), h, m, s, getMilliseconds(date, timezone)], timezone);
};
export const modifyWithTimeString = (date, time, timezone = 'local') => {
if (date == null || !time) {
return date;
}
time = parseDate(time, 'HH:mm:ss', timezone);
return modifyTime(date, getHours(time, timezone), getMinutes(time, timezone), getSeconds(time, timezone), timezone);
};
export const clearTime = function(date, timezone = 'local') {
return newDate([getFullYear(date, timezone), getMonth(date, timezone), getDate(date, timezone)], timezone);
};
export const clearMilliseconds = function(date, timezone = 'local') {
return newDate([getFullYear(date, timezone), getMonth(date, timezone), getDate(date, timezone), getHours(date, timezone), getMinutes(date, timezone), getSeconds(date, timezone), 0], timezone);
};
export const limitTimeRange = function(date, ranges, timezone, format = 'HH:mm:ss') {
// TODO: refactory a more elegant solution
if (ranges.length === 0) return date;
const normalizeDate = date => fecha.parse(fecha.format(date, format, {timezone}), format, {timezone});
const ndate = normalizeDate(date);
const nranges = ranges.map(range => range.map(normalizeDate));
if (nranges.some(nrange => ndate >= nrange[0] && ndate <= nrange[1])) return date;
let minDate = nranges[0][0];
let maxDate = nranges[0][0];
nranges.forEach(nrange => {
minDate = new Date(Math.min(nrange[0], minDate));
maxDate = new Date(Math.max(nrange[1], minDate));
});
const ret = ndate < minDate ? minDate : maxDate;
// preserve Year/Month/Date
return modifyDate(
ret,
getFullYear(date, timezone),
getMonth(date, timezone),
getDate(date, timezone),
timezone
);
};
export const timeWithinRange = function(date, selectableRange, timezone, format) {
const limitedDate = limitTimeRange(date, selectableRange, timezone, format);
return limitedDate.getTime() === date.getTime();
};
export const changeYearMonthAndClampDate = function(date, year, month, timezone = 'local') {
// clamp date to the number of days in `year`, `month`
// eg: (2010-1-31, 2010, 2) => 2010-2-28
const monthDate = Math.min(getDate(date, timezone), getDayCountOfMonth(year, month));
return modifyDate(date, year, month, monthDate, timezone);
};
export const prevMonth = function(date, timezone = 'local') {
const year = getFullYear(date, timezone);
const month = getMonth(date, timezone);
return month === 0
? changeYearMonthAndClampDate(date, year - 1, 11, timezone)
: changeYearMonthAndClampDate(date, year, month - 1, timezone);
};
export const nextMonth = function(date, timezone = 'local') {
const year = getFullYear(date, timezone);
const month = getMonth(date, timezone);
return month === 11
? changeYearMonthAndClampDate(date, year + 1, 0, timezone)
: changeYearMonthAndClampDate(date, year, month + 1, timezone);
};
export const prevYear = function(date, timezone, amount = 1) {
const year = getFullYear(date, timezone);
const month = getMonth(date, timezone);
return changeYearMonthAndClampDate(date, year - amount, month, timezone);
};
export const nextYear = function(date, timezone, amount = 1) {
const year = getFullYear(date, timezone);
const month = getMonth(date, timezone);
return changeYearMonthAndClampDate(date, year + amount, month, timezone);
};
export const extractDateFormat = function(format) {
return format
.replace(/\W?m{1,2}|\W?ZZ/g, '')
.replace(/\W?h{1,2}|\W?s{1,3}|\W?a/gi, '')
.trim();
};
export const extractTimeFormat = function(format) {
return format
.replace(/\W?D{1,2}|\W?Do|\W?d{1,4}|\W?M{1,4}|\W?y{2,4}/g, '')
.trim();
};
export const validateRangeInOneMonth = function(start, end, timezone = 'local') {
return (getMonth(start, timezone) === getMonth(end, timezone)) && (getFullYear(start, timezone) === getFullYear(end, timezone));
};
export const newDate = fecha.dates.newDate;
export const getDate = fecha.dates.getDate;
export const getDay = fecha.dates.getDay;
export const getFullYear = fecha.dates.getFullYear;
export const getHours = fecha.dates.getHours;
export const getMilliseconds = fecha.dates.getMilliseconds;
export const getMinutes = fecha.dates.getMinutes;
export const getMonth = fecha.dates.getMonth;
export const getSeconds = fecha.dates.getSeconds;
export const setDate = fecha.dates.setDate;
export const setFullYear = fecha.dates.setFullYear;
export const setHours = fecha.dates.setHours;
export const setMilliseconds = fecha.dates.setMilliseconds;
export const setMinutes = fecha.dates.setMinutes;
export const setMonth = fecha.dates.setMonth;
export const setSeconds = fecha.dates.setSeconds;
|
9afb3e61fff41ac9dfa56b9d1a9732b1c7708982
|
[
"JavaScript"
] | 1
|
JavaScript
|
kesslerk/element
|
aacaeeba7c05539ef2d1928d8ccadacfe0174ea7
|
f3845e343da9a8d2b9c8dfc8670d8b337ca6b548
|
refs/heads/master
|
<file_sep>package jen.proto.classschedule;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import java.util.*;
public class MainActivity extends Activity
{
List<Schedule> sched = new ArrayList<Schedule>();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
populateData();
setCustomListView();
}
private void populateData(){
sched.add(new Schedule("7:30-9:00am", "wed", "MSD002L1", "5401", "Technological Institute of the Philippines"));
sched.add(new Schedule("9:00-10:30am", "wed", "C0012", "IT423", "Access Computer College"));
}
private void setCustomListView(){
ArrayAdapter<Schedule> thisAdapter = new CustomAdapter();
ListView classschedList = (ListView) findViewById(R.id.id_listview_classsched);
classschedList.setAdapter(thisAdapter);
}
private class CustomAdapter extends ArrayAdapter{
public CustomAdapter(){
super(MainActivity.this, R.layout.layout_listview_classsched, sched);
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View listcustom = convertView;
if(listcustom == null){
listcustom = getLayoutInflater().inflate(R.layout.layout_listview_classsched, parent, false);
}
Schedule posSched = sched.get(position);
TextView subject = (TextView) listcustom.findViewById(R.id.id_txt_subject);
subject.setText(posSched.getSubject());
TextView room = (TextView) listcustom.findViewById(R.id.id_txt_room);
room.setText(posSched.getRoom());
TextView schoolname = (TextView) listcustom.findViewById(R.id.id_txt_schoolname);
schoolname.setText(posSched.getSchoolname());
TextView curtime = (TextView) listcustom.findViewById(R.id.id_txt_schedtime);
curtime.setText(posSched.getCurTime());
return listcustom;
}
}
}
class Schedule{
private String curtime;
private String date;
private String subject;
private String room;
private String schoolname;
public Schedule(String curtime, String date, String subject, String room, String schoolname)
{
this.curtime = curtime;
this.date = date;
this.subject = subject;
this.room = room;
this.schoolname = schoolname;
}
public String getCurTime()
{
return curtime;
}
public String getDate()
{
return date;
}
public String getSubject()
{
return subject;
}
public String getRoom()
{
return room;
}
public String getSchoolname()
{
return schoolname;
}
}
<file_sep>package zarch.project.selectclass;
public class AddClass
{
}
<file_sep>package zarch.proto.staticmethod;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import java.util.*;
public class SectionActivity extends Activity
{
List<Sections> sections = new ArrayList<Sections>();
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.category_list_activity_layout);
setUpdated();
setSectionActivity();
setListView();
addButtonAction();
}
private void setUpdated(){
Databank info = new Databank(this);
String category = ListStatus.getCategory();
info.open();
String[] sectionList = info.getData(category);
info.close();
for(int i = 0; i < sectionList.length; i++){
sections.add(new Sections(sectionList[i]));
}
}
private void setSectionActivity(){
TextView header = (TextView) findViewById(R.id.id_categoryName);
String headerTitle = ListStatus.getCategory();
header.setText(headerTitle);
}
private void setListView(){
ArrayAdapter<Sections> adapter = new CustomListAdapter();
ListView sectionList = (ListView) findViewById(R.id.id_listview_sections);
sectionList.setAdapter(adapter);
}
private void addButtonAction(){
Button addSection = (Button) findViewById(R.id.id_addbtn);
addSection.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
boolean didWork = true;
try{
Databank addData = new Databank(SectionActivity.this);
String category = ListStatus.getCategory();
String sectionName = "<NAME>";
addData.open();
addData.createEntry(category, sectionName);
addData.close();
// notify the adapter
sections.add(new Sections(sectionName));
ListView sectionList = (ListView) findViewById(R.id.id_listview_sections);
((ArrayAdapter) sectionList.getAdapter()).notifyDataSetChanged();
}catch(Exception e){
didWork = false;
String error = e.toString();
Dialog d = new Dialog(SectionActivity.this);
d.setTitle("Error");
TextView t = new TextView(SectionActivity.this);
t.setText(error);
d.setContentView(t);
d.show();
}finally{
Dialog d = new Dialog(SectionActivity.this);
d.setTitle("Insert Data...");
TextView t = new TextView(SectionActivity.this);
t.setText("Successfully Inserted");
d.setContentView(t);
d.show();
}
}
});
}
private class CustomListAdapter extends ArrayAdapter{
public CustomListAdapter(){
super(SectionActivity.this, R.layout.section_itemlist_layout, sections);
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
if(view == null){
view = getLayoutInflater().inflate(R.layout.section_itemlist_layout, parent, false);
}
Sections sectionPos = sections.get(position);
TextView sectionName = (TextView) view.findViewById(R.id.id_section_name);
sectionName.setText(sectionPos.getSectionName());
return view;
}
}
}
class Sections{
private String sectionName;
public Sections(String sectionName)
{
this.sectionName = sectionName;
}
public String getSectionName()
{
return sectionName;
}
}
<file_sep>package zarch.output.sample;
import android.app.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import java.util.*;
public class SectionList extends Activity
{
List<Section> section = new ArrayList<Section>();
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.section_list_layout);
setListView();
populateFinalSection();
}
private void populateFinalSection(){
section.add(new Section("ELEMENTARY", "10001"));
section.add(new Section("HIGHSCHOOL", "10002"));
section.add(new Section("TERTIARY", "10003"));
}
private void setListView(){
ArrayAdapter<Section> adapter = new CategoryAdapter();
ListView mySecList = (ListView) findViewById(R.id.category_listview);
mySecList.setAdapter(adapter);
}
private class CategoryAdapter extends ArrayAdapter{
public CategoryAdapter(){
super(SectionList.this, R.layout.section_item_layout, section);
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View itemView = convertView;
if(itemView == null){
itemView = getLayoutInflater().inflate(R.layout.section_item_layout, parent, false);
}
Section secItemPos = section.get(position);
TextView sectionName = (TextView) itemView.findViewById(R.id.category_item_id);
sectionName.setText(secItemPos.getSectionName());
return itemView;
}
}
}
class Section{
private String sectionName;
private String sectionID;
public Section(String sectionName, String sectionID)
{
this.sectionName = sectionName;
this.sectionID = sectionID;
}
public String getSectionName()
{
return sectionName;
}
public String getCategoryID()
{
return sectionID;
}
}
|
7cd93a532440fdc227400ab1ece1a674532271e8
|
[
"Java"
] | 4
|
Java
|
iamcheche/TCManager
|
0fc0fc07e34dda351244fbcffe0ec79f3bdd297c
|
a063b79f993ce2f72e49495ba8a26c2e06d715f2
|
refs/heads/master
|
<repo_name>cran/MRmediation<file_sep>/R/mediation_single.R
#' A causal mediation method with a single CpG site as the mediator
#'
#' @name mediation_single
#' @aliases mediation_single
#' @param pheno A vector of continuous or binary phenotypes (class: numeric).
#' @param predictor A vector of values for the exposure variable (class: numeric).
#' @param cpg A vector of a CpG (class: numeric).
#' @param covariate A matrix of covariates. Each column is a covariate (class: data.frame).
#' @param family "gaussian" for continuous outcome or "binomial" for binary outcome.
#' @importFrom MASS ginv
#' @importFrom stats glm lm pf anova var
#' @return 1. pval$TE: total effect (TE) p-value \cr
#' 2. pval$DE: direct effect (DE) p-value \cr
#' 3. pval$IE: indirect effect (IE) p-value \cr
#' 4. pval_MX: p-value for the association between methylation and exposure \cr
#' @examples
#' ################
#' ### Examples ###
#' ################
#' data("example_data")
#' predictor = data$exposure
#' cpg = data[,9] #any number in c(7:dim(data)[2])
#' covariates = subset(data, select=c("age","gender"))
#' # binary outcome
#' pheno_bin = data$pheno_bin
#' mediation_single(pheno_bin, predictor, cpg, covariate=covariates, family="binomial")
#' # continuous outcome
#' pheno_con = data$pheno_con
#' mediation_single(pheno_con, predictor, cpg, covariate=covariates, family="gaussian")
#' @export
mediation_single <- function(pheno, predictor, cpg, covariate, family="gaussian")
{
covariate = as.matrix(covariate)
predictor = as.vector(as.matrix(predictor)[,1])
interaction = predictor*cpg
###########################
if (family=="gaussian") {
# cpg ~ covariate + predictor
coef2_all = summary(lm(cpg ~ covariate + predictor))$coefficients
alpha_cov = coef2_all[c(1:(dim(covariate)[2]+1)),1]
coef2_all_nocov = coef2_all[-c(1:(dim(covariate)[2]+1)), ]
alpha_predictor = coef2_all_nocov[1]
pval2 = coef2_all_nocov[4]
pval <- list()
# TE null hypothesis: b_predictor = b_cpg = b_interaction = 0
test_part = cbind(predictor, cpg, interaction)
untest_part = covariate
fit = glm(pheno ~ untest_part + test_part, family="gaussian")
pval$TE = anova(fit, test = "F")[3,6]
# DE null hypothesis: b_predictor = b_interaction = 0
test_part = cbind(predictor, interaction)
untest_part = cbind(covariate, cpg)
fit = glm(pheno ~ untest_part + test_part, family="gaussian")
pval$DE = anova(fit, test = "F")[3,6]
# IE null hypothesis: b_cpg = b_interaction = 0
test_part = cbind(cpg, interaction)
untest_part = cbind(covariate, predictor)
fit = glm(pheno ~ untest_part + test_part, family="gaussian")
pval$IE = anova(fit, test = "F")[3,6]
}
if (family=="binomial") {
# cpg ~ covariate + predictor using controls
cpg_c = cpg[which(pheno==0)]
covariate_c = covariate[which(pheno==0),]
covariate_cdqr = qr(covariate_c)
covariate_cindex = covariate_cdqr$pivot[1:covariate_cdqr$rank]
covariate_c = covariate_c[, covariate_cindex]
diff = colnames(covariate)[!(colnames(covariate)%in%colnames(covariate_c))]
predictor_c = as.vector(predictor)[which(pheno==0)]
coef2_all = summary(lm(cpg_c ~ covariate_c + predictor_c))$coefficients
alpha_cov = coef2_all[c(1:(dim(covariate_c)[2]+1)),1]
coef2_all_nocov = coef2_all[-c(1:(dim(covariate_c)[2]+1)), ]
alpha_predictor = coef2_all_nocov[1]
pval2 = coef2_all_nocov[4]
pval <- list()
# TE null hypothesis: b_predictor = b_cpg = b_interaction = 0
test_part = cbind(predictor, cpg, interaction)
untest_part = covariate
fit = glm(pheno ~ untest_part + test_part, family="binomial")
pval$TE = anova(fit, test = "Rao")[3,6]
# DE null hypothesis: b_predictor = b_interaction = 0
test_part = cbind(predictor, interaction)
untest_part = cbind(covariate, cpg)
fit = glm(pheno ~ untest_part + test_part, family="binomial")
pval$DE = anova(fit, test = "Rao")[3,6]
# IE null hypothesis: b_cpg = b_interaction = 0
test_part = cbind(cpg, interaction)
untest_part = cbind(covariate, predictor)
fit = glm(pheno ~ untest_part + test_part, family="binomial")
pval$IE = anova(fit, test = "Rao")[3,6]
}
return(list(pval=pval, pval_MX=pval2))
}
<file_sep>/R/MRmediation.R
#' A causal mediation method with methylated region as the mediator
#'
#' @name mediation
#' @aliases mediation
#' @param pheno A vector of continuous or binary phenotypes (class: numeric).
#' @param predictor A vector of values for the exposure variable (class: numeric).
#' @param region A matrix of CpGs in a region. Each column is a CpG (class: data.frame).
#' @param pos A vector of CpG locations from the defined region and they are from the same chromosome (class: integer).
#' @param order A value for the order of bspline basis. 1: constant, 2: linear, 3: quadratic and 4: cubic.
#' @param gbasis A value for the number of basis being used for functional transformation on CpGs.
#' @param covariate A matrix of covariates. Each column is a covariate (class: data.frame).
#' @param base "bspline" for B-spline basis or "fspline" for Fourier basis.
#' @param family "gaussian" for continuous outcome or "binomial" for binary outcome.
#' @import fda
#' @importFrom MASS ginv
#' @importFrom stats glm lm pf anova var
#' @return 1. pval$TE: total effect (TE) p-value \cr
#' 2. pval$DE: direct effect (DE) p-value \cr
#' 3. pval$IE: indirect effect (IE) p-value \cr
#' 4. pval_MX: p-value for the association between methylation and exposure \cr
#' @examples
#' ################
#' ### Examples ###
#' ################
#' data("example_data")
#' predictor = data$exposure
#' region = data[,7:dim(data)[2]]
#' covariates = subset(data, select=c("age","gender"))
#' # binary outcome
#' pheno_bin = data$pheno_bin
#' mediation(pheno_bin, predictor, region, pos, covariate=covariates, order=4,
#' gbasis=4, base="bspline", family="binomial")
#' # continuous outcome
#' pheno_con = data$pheno_con
#' mediation(pheno_con, predictor, region, pos, covariate=covariates, order=4,
#' gbasis=4, base="bspline", family="gaussian")
#' @export
#library(fda)
#library(MASS) #ginv
mediation <- function(pheno, predictor, region, pos, order, gbasis, covariate, base="bspline", family="gaussian")
{
predictor[is.na(predictor)] = 0
region[is.na(region)] = 0
covariate[is.na(covariate)] = 0
idx = is.na(pheno)
pheno = pheno[!idx]
region = region[!idx,]
covariate = covariate[!idx,]
dqr = qr(region)
index = dqr$pivot[1:dqr$rank]
region = region[, index]
pos = pos[index]
nsample = nrow(region)
nsnp = ncol(region)
if(max(pos) > 1) pos = (pos - min(pos)) / (max(pos) - min(pos))
betabasis = create.bspline.basis(norder = 1, nbasis = 1)
if (base == "bspline"){
regionbasis = create.bspline.basis(norder = order, nbasis = gbasis)
} else if (base == "fspline"){
regionbasis = create.fourier.basis(c(0,1), nbasis = gbasis)
}else { }
region = as.matrix(region)
B = eval.basis(pos, regionbasis)
to_mul = ginv(t(B) %*% B) %*% t(B)
U = region %*% t( to_mul )
J = inprod(regionbasis, betabasis)
UJ = matrix( U %*% J, ncol = ncol(J) )
region_transformed = as.vector(UJ)
covariate = as.matrix(covariate)
predictor = as.matrix(predictor)
interaction = as.vector(predictor)*region_transformed
###########################
if (family=="gaussian") {
# region_transformed ~ covariate + predictor
coef2_all = summary(lm(region_transformed ~ covariate + predictor))$coefficients
alpha_cov = coef2_all[c(1:(dim(covariate)[2]+1)),1]
coef2_all_nocov = coef2_all[-c(1:(dim(covariate)[2]+1)), ]
alpha_predictor = coef2_all_nocov[1]
pval2 = coef2_all_nocov[4]
pval <- list()
# TE null hypothesis: b_predictor = b_region_transformed = b_interaction = 0
test_part = cbind(predictor, region_transformed, interaction)
untest_part = covariate
fit = glm(pheno ~ untest_part + test_part, family="gaussian")
pval$TE = anova(fit, test = "F")[3,6]
# DE null hypothesis: b_predictor = b_interaction = 0
test_part = cbind(predictor, interaction)
untest_part = cbind(covariate, region_transformed)
fit = glm(pheno ~ untest_part + test_part, family="gaussian")
pval$DE = anova(fit, test = "F")[3,6]
# IE null hypothesis: b_region_transformed = b_interaction = 0
test_part = cbind(region_transformed, interaction)
untest_part = cbind(covariate, predictor)
fit = glm(pheno ~ untest_part + test_part, family="gaussian")
pval$IE = anova(fit, test = "F")[3,6]
}
if (family=="binomial") {
# region_transformed ~ covariate + predictor using controls
region_transformed_c = region_transformed[which(pheno==0)]
covariate_c = covariate[which(pheno==0),]
covariate_cdqr = qr(covariate_c)
covariate_cindex = covariate_cdqr$pivot[1:covariate_cdqr$rank]
covariate_c = covariate_c[, covariate_cindex]
diff = colnames(covariate)[!(colnames(covariate)%in%colnames(covariate_c))]
predictor_c = as.vector(predictor)[which(pheno==0)]
coef2_all = summary(lm(region_transformed_c ~ covariate_c + predictor_c))$coefficients
alpha_cov = coef2_all[c(1:(dim(covariate_c)[2]+1)),1]
coef2_all_nocov = coef2_all[-c(1:(dim(covariate_c)[2]+1)), ]
alpha_predictor = coef2_all_nocov[1]
pval2 = coef2_all_nocov[4]
pval <- list()
# TE null hypothesis: b_predictor = b_region_transformed = b_interaction = 0
test_part = cbind(predictor, region_transformed, interaction)
untest_part = covariate
fit = glm(pheno ~ untest_part + test_part, family="binomial")
pval$TE = anova(fit, test = "Rao")[3,6]
# DE null hypothesis: b_predictor = b_interaction = 0
test_part = cbind(predictor, interaction)
untest_part = cbind(covariate, region_transformed)
fit = glm(pheno ~ untest_part + test_part, family="binomial")
pval$DE = anova(fit, test = "Rao")[3,6]
# IE null hypothesis: b_region_transformed = b_interaction = 0
test_part = cbind(region_transformed, interaction)
untest_part = cbind(covariate, predictor)
fit = glm(pheno ~ untest_part + test_part, family="binomial")
pval$IE = anova(fit, test = "Rao")[3,6]
}
return(list(pval=pval, pval_MX=pval2))
}
<file_sep>/R/example_data.R
#' This is the data for examples
#'
#' \itemize{
#' \item data. phenotype file. 1st column is ID, 2nd column is continuous outcome, 3rd column is binary outcome, 4th column is exposure, 5th column is age, 6th column is gender, 7th-last columns are CpGs
#' \item pos. CpG locations from the defined region and they are from the same chromosome.
#' }
#'
#' @name example_data
#' @aliases data pos
#' @docType data
#' @usage data(example_data)
NULL
|
f7cf5b4469f5c2d4db3f58da47ec822369e5b61b
|
[
"R"
] | 3
|
R
|
cran/MRmediation
|
8f84ea02a25a1973d34e3609e56a8e56a86a767a
|
f1500e808dd5e70f0ad425dd57edf9ea2d3dff84
|
refs/heads/master
|
<repo_name>alekseypivovar/Labyrinth-Server<file_sep>/server.cpp
#include "server.h"
#include <QMessageBox>
#include <QDebug>
#include <QPoint>
Server::Server(int port, QWidget *parent)
: QTcpServer(parent), blockSize(0)
{
m_ptcpServer = new QTcpServer(this);
if(!m_ptcpServer->listen(QHostAddress::Any, port)){
qDebug() << "Unable to start server: " << m_ptcpServer->errorString();
m_ptcpServer->close();
return;
}
else
qDebug() << "Listening port: " << port;
for (int i=0;i<SIZE;i++) {
QVector <quint8> vector;
map.append(vector);
for (int j=0;j<SIZE;j++){
map[i].append(ROAD);
}
}
for (int i=0;i<SIZE;i++) {
for (int j=0;j<SIZE;j++){
int random = QRandomGenerator::global()->bounded(4);
if (random==0)
map[i][j]=WALL;
}
}
// нижняя граница
for (int i=0;i<SIZE;i++) {
map[SIZE-1][i]=WALL;
}
// верхняя граница
for (int i=0;i<SIZE;i++) {
map[0][i]=WALL;
}
// левая граница
for (int i=0;i<SIZE;i++) {
map[i][0]=WALL;
}
// правая граница
for (int i=0;i<SIZE;i++) {
map[i][SIZE-1]=WALL;
}
map[0][4]=EXIT;
map[13][13]=ROAD;
connect(m_ptcpServer, SIGNAL(newConnection()), this, SLOT(slotNewConnection()));
}
Server::~Server()
{
}
void Server::slotNewConnection(){
QTcpSocket* pClientSocket = m_ptcpServer->nextPendingConnection();
connect(pClientSocket, SIGNAL(disconnected()), pClientSocket, SLOT(deleteLater()));
connect(pClientSocket, SIGNAL(readyRead()), this, SLOT(slorReadClient()));
qDebug() << "Connected!";
}
void Server::slorReadClient()
{
QTcpSocket* pClientSocket = qobject_cast<QTcpSocket*>(sender());
QDataStream in(pClientSocket);
if (blockSize == 0){
if (pClientSocket->bytesAvailable() < sizeof (quint16))
return;
in >> blockSize;
}
if (pClientSocket->bytesAvailable() < blockSize)
return;
blockSize = 0;
QPoint point;
in >> point;
calculateCells(pClientSocket, point);
}
void Server::sendToClient(QTcpSocket *pSocket, QVector<quint8> points)
{
QByteArray block;
QDataStream out (&block, QIODevice::WriteOnly);
out << (quint16)0 << points;
out.device()->seek(0);
out << (quint16)(block.size() - sizeof (quint16));
pSocket->write(block);
}
void Server::calculateCells(QTcpSocket *pSocket, QPoint point)
{
QVector<quint8> pointsVector;
int x = point.x();
int y = point.y();
pointsVector << map[y-1][x-1] << map [y-1][x] << map[y-1][x+1] << map[y][x-1] << map[y][x+1]
<< map[y+1][x-1] << map[y+1][x] << map[y+1][x+1];
sendToClient(pSocket, pointsVector);
}
<file_sep>/server.h
#ifndef SERVER_H
#define SERVER_H
#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
#include <QVector>
#include <QRandomGenerator>
#define SIZE 15
enum {
ROAD = 0,
WALL = 1,
PLAYER = 2,
EXIT = 3
};
class Server : public QTcpServer
{
Q_OBJECT
private:
QTcpServer* m_ptcpServer;
quint16 blockSize;
void sendToClient(QTcpSocket* pSocket, QVector<quint8> points);
// void incomingConnection(qintptr handle);
void calculateCells(QTcpSocket *pSocket, QPoint point);
QVector <QVector <quint8> > map;
public:
Server(int port, QWidget *parent = 0);
~Server();
public slots:
// void slotNewConnection();
void slorReadClient();
virtual void slotNewConnection();
};
#endif // SERVER_H
|
a5e344e709372e1e1a3474b10d8ccfc8fe831f2c
|
[
"C++"
] | 2
|
C++
|
alekseypivovar/Labyrinth-Server
|
0fc733cf4cbf0342117f8666045c89a70b7ad4a1
|
a7ab1530756e45cd16f8939c64cdc669cef6081b
|
refs/heads/main
|
<file_sep>DROP DATABASE IF EXISTS studygroup_db;
CREATE DATABASE studygroup_db;
USE studygroup_db;
CREATE TABLE member (
id INT AUTO_INCREMENT,
joined_group VARCHAR(100) NOT NULL,
first_name VARCHAR(10) NOT NULL,
last_name VARCHAR(10) NOT NULL,
social_handle VARCHAR (300) NOT NULL,
zip_code INT,
description VARCHAR (500),
-- img_url VARCHAR (1000),
PRIMARY KEY(id)
);
CREATE TABLE study_group (
id INT AUTO_INCREMENT,
group_name VARCHAR(100) NOT NULL,
group_blurb VARCHAR(500) NOT NULL,
PRIMARY KEY(id)
);
CREATE TABLE upcoming_events (
id INT AUTO_INCREMENT,
event_group VARCHAR(100) NOT NULL,
event_title VARCHAR(100) NOT NULL,
event_date TIMESTAMP NOT NULL,
event_url VARCHAR(500) NOT NULL,
PRIMARY KEY(id)
);<file_sep>module.exports = function(sequelize, DataTypes) {
const upcoming_events = sequelize.define("upcoming_events", {
id: {
type: DataTypes.INTEGER,
primaryKey: true,
autoIncrement: true,
},
event_group: {
type: DataTypes.STRING
},
event_title :{
type: DataTypes.STRING
},
event_date :{
type: DataTypes.DATE
},
event_url :{
type: DataTypes.STRING
}
});
return upcoming_events ;
};<file_sep>
# Project2
## Landing Page

## User Entry Info

## Creating Group

## Group Landing Page

|
9ac1e7e0019bcd79accbfda17b9b2272d60d6528
|
[
"JavaScript",
"SQL",
"Markdown"
] | 3
|
SQL
|
blalbeharry/Project2
|
a1556ca6aa7c2031cda2cc6db2cfc05ef6c3ea61
|
a18e6800a13bd7ffaeeda204f5669436a39bf6b7
|
refs/heads/master
|
<file_sep># ManBaby
A simulation of the Manchester Baby, the world's first stored computer along with an assembler for coverting assembly code to machine code
<file_sep>#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <bitset>
#include <algorithm>
using namespace std;
string instructionSet[7][2];
//vector<string> instructionSet[8][2];
struct symbol
{
string name;
string data;
string line;
};
vector<symbol> symbolTable;
vector<string> program;
void trim(string& s)
{
size_t p = s.find_first_not_of(" \t");
s.erase(0, p);
p = s.find_last_not_of(" \t");
if (string::npos != p)
s.erase(p+1);
}
void removeSpace(string& s)
{
for (int j=0; j<s.size(); j++)
{
if(s.at(j)==' ')
{
s.erase(j,1);
}
}
}
string binaryConv(int n)
{
string str="";
int binary;
bitset<32> x(n);
if(n<0)
{
n=n-(n+n);
bitset<32> y(n);
y.flip();
bitset<32> z(y.to_ulong() + 1);
str=z.to_string();
x=z;
}
str=x.to_string();
reverse(str.begin(),str.end());
return str;
}
void openInstSet()
{
string lines[7];
string line="";
ifstream file ("instructionSet.txt");
if (file.is_open())
{
for(int i=0; i<7; i++)
{
getline (file,line);
lines[i]=line;
}
file.close();
}
for(int j=0; j<7; j++)
{
stringstream split(lines[j]);
for (int k=0; k<2; k++)
{
getline(split, instructionSet[j][k],' ');
}
}
}
void openProgram()
{
ifstream file ("BabyTest1-Assembler.txt");
string line="";
if (file.is_open())
{
while(getline (file,line))
{
for (int j=0; j<line.size(); j++)
{
if(line.at(j)==';')
{
line.erase(j,(line.size()-j));
}
}
if(!line.empty())
program.push_back(line);
}
file.close();
}
}
//POPULATE SYMBOL TABLE
void loadSymbols()
{
string sLines[3]="";
for (int i=0; i<program.size(); i++)
{
for (int j=0; j<program.at(i).size(); j++)
{
if(program.at(i).at(j)==':')
{
stringstream split(program.at(i));
getline(split, sLines[0],':');
stringstream ss;
ss << i;
string str = ss.str();
sLines[1]=program.at(i);
sLines[1].erase(0,j+1);
sLines[2]=str;
//REMOVE WHITESPACE
for (int i=0; i<3; i++)
{
removeSpace(sLines[i]);
trim(sLines[i]);
}
//ADD SYMBOL TO TABLE WITH IT'S DATA AND LINE NUMBER
symbolTable.push_back(symbol());
symbolTable[symbolTable.size()-1].name=sLines[0];
symbolTable[symbolTable.size()-1].data=sLines[1];
symbolTable[symbolTable.size()-1].line=sLines[2];
}
}
}
}
void convProgram()
{
string op="";
string operand="";
string newLine="00000000000000000000000000000000";
for (int i=0; i<program.size(); i++)
{
newLine="00000000000000000000000000000000";
for (int k=0; k<7; k++)
if (program.at(i).find(instructionSet[k][1])!=std::string::npos)
{
op=instructionSet[k][0];
newLine.at(13)=op.at(0);
newLine.at(14)=op.at(1);
newLine.at(15)=op.at(2);
}
for (int j=0; j<symbolTable.size(); j++)
if (program.at(i).find(symbolTable.at(j).name)!=std::string::npos&&op!="111")
{
operand="";
operand=symbolTable.at(j).line;
int n=0;
istringstream (operand) >> n;
operand=binaryConv(n);
newLine.at(0)=operand.at(0);
newLine.at(1)=operand.at(1);
newLine.at(2)=operand.at(2);
newLine.at(3)=operand.at(3);
newLine.at(4)=operand.at(4);
}
program.at(i)=newLine;
}
for (int i=0; i<symbolTable.size(); i++)
{
if (symbolTable.at(i).data.at(0)=='V'&&symbolTable.at(i).data.at(1)=='A'&&symbolTable.at(i).data.at(2)=='R')
{
int n;
string str=symbolTable.at(i).data;
str.erase(0,3);
istringstream (str) >> n;
int line;
istringstream (symbolTable.at(i).line) >> line;
program.at(line)=binaryConv(n);
}
}
for (int i=0; i<symbolTable.size(); i++)
{
if (symbolTable.at(i).data.at(0)!='V'&&symbolTable.at(i).data.at(1)!='A'&&symbolTable.at(i).data.at(2)!='R')
{
int line;
istringstream (symbolTable.at(i).line) >> line;
program.push_back(binaryConv(line));
}
}
}
void outToFile()
{
ofstream file ("machineCode.txt");
if (file.is_open())
{
for (int i; i<program.size(); i++)
{
file<<program.at(i)<<endl;
}
file.close();
}
}
int main()
{
openInstSet();
openProgram();
loadSymbols();
convProgram();
outToFile();
for (int i; i<program.size(); i++)
{
cout<<program.at(i)<<endl;
}
return 0;
}
<file_sep>/**
*Class which holds the nessessary data structures and logic to simulate the Manchester Baby's processor.
*
*Authors : <NAME>, <NAME>, <NAME>
*Version : 1.0 22nd November 2015
*
*/
class Processor{
private :
//Boolean Array for the Accumulator
bool accumulator[32];
//Boolean Array for the CI (Control Instruction)
bool ci[32];
//Boolean Array for the PI (Present Instruction)
bool pi[32];
public :
Processor();
void setAccumulator(bool accumulator[32]);
bool* getAccumulator();
void setCI(bool memoryAddress[32]);
bool* getCI();
void setPI(bool instruction[32]);
bool* getPI();
void resetCI();
void resetAccumulator();
int convertBinToDec(bool binary[], int length);
bool* convertDecToBin(int decimal);
bool* negate(bool operand[32]);
void increment();
int getOp(int start, int end);
};
<file_sep>/**
*Authors : <NAME>, <NAME>, <NAME>
*Version : 1.0 22nd November 2015
*
*/
#include <iostream>
#include <cmath>
#include <algorithm>
#include "Processor.h"
using namespace std;
/**
*Constructor for the processor which sets the contents of the CI, PI and accumulator to all 0s
*
*/
Processor::Processor(){
for (int i = 0; i < 32; i++)
{
accumulator[i] = 0;
ci[i] = 0;
pi[i] = 0;
}
}
/**
*Setter Method for the Accumulator
*
*/
void Processor::setAccumulator(bool accumulator[]){
for(int i = 0; i < 32; i++){
this -> accumulator[i] = accumulator[i];
}
}
/**
*Getter Method for the Accumulator
*
*/
bool* Processor::getAccumulator(){
return accumulator;
}
/**
*Setter Method for the CI
*
*/
void Processor::setCI(bool memoryAddress[32]){
for (int i = 0; i < 32; i++)
{
ci[i] = memoryAddress[i];
}
}
/**
*Getter Method for the CI
*
*/
bool* Processor::getCI(){
return ci;
}
/**
*Setter Method for the PI
*
*/
void Processor::setPI(bool instruction[32]){
for(int i = 0; i < 32; i++){
pi[i] = instruction[i];
}
}
/**
*Getter Method for the PI
*
*/
bool* Processor::getPI(){
return pi;
}
/**
*Method which resets each element of ci to 0
*
*/
void Processor::resetCI(){
for (int i = 0; i < 32; i++)
{
ci[i] = 0;
}
}
/**
*Method which resets each element of the accumulator to 0
*
*/
void Processor::resetAccumulator(){
for (int i = 0; i < 32; i++)
{
accumulator[i] = 0;
}
}
/**
*Method which converts a twos complement binary number into a decimal integer
*
*param a: bool binary[] - binary array for conversion
*return : int decimal - binary array converted to integer
*/
int Processor::convertBinToDec(bool binary[], int length){
int decimal = 0;
//Checks if the binary number is less than 32 bits long (ie. an operand or opcode which aren't
//two's complement numbers or if the number begins with a 0 and therefore is positive
if(length != 32 || binary[31] == 0){
for (int i = length - 1; i >= 0; i--){
decimal += (int(binary[i]))*pow(2,i);
}
}
else{
//If the number begins with one the MSB (most signifigant bit) calcualted as a negative
//value
decimal = -1 * ((int(binary[31]))*pow(2,31));
for (int i = 30; i >= 0; i--){
decimal += (int(binary[i]))*pow(2,i);
}
}
return decimal;
}
/**
*Method which converts decimal integer into binary number
*
*param a: int decimal - decimal number for conversion
*return : array[] - decimal number converted to binary
*/
bool* Processor::convertDecToBin(int decimal){
bool static array[32];
int index = 0;
for (int i = 0; i < 32; i++)
{
array[i] = 0;
}
while(decimal !=0){
array[index] = decimal%2;
decimal/=2;
index++;
}
return array;
}
/**
*Method which flips all the bits after the first 1 (read from right to left)
*
*param : operand - The binary number to be negated
*return : operand - The negated binary number
*
*/
bool* Processor::negate(bool operand[32]){
int first1;
//For loop to find the first 1 in the binary number
for(int i = 0; i < 32; i++){
if(operand[i] == 1){
first1 = i;
break;
}
}
for(int i = 31; i > first1; i--){
//Condition operator used to flip the bits
operand[i]==0 ? operand[i]=1 : operand[i]=0;
}
return operand;
}
/**
*Method which converts ci into decimal, increments the result
*and finally, converts the decimal integer back into ci
*
*/
void Processor::increment(){
int decimal = convertBinToDec(ci,32);
decimal++;
setCI(convertDecToBin(decimal));
}
/**
*Method to get a sub array from the present instruction used to get the operand and opcode from
*the present instruction
*
*param : start - the start position for the sub array in present instruction
*param : end - the end position for the sub array in present instruction
*return : decOP - the decimal value for the operand or opcode taken from the present instruction
*/
int Processor::getOp(int start, int end){
int size = (end-start)+1;
bool op[size];
int j = 0;
for(int i= start; i < (end+1); i++){
op[j] = pi[i];
cout << op[j];
j++;
}
cout << endl;
int decOP = convertBinToDec(op,size);
return decOP;
}
<file_sep>/**
*Program to simulate the hardware of the Manchester Baby which is able to take txt files of machine
*code and execute them
*
*Authors : <NAME>, <NAME>, <NAME>
*Version : 1.0 22nd November 2015
*
*/
#include <iostream>
#include <string>
#include <sstream>
#include "Processor.cpp"
#include "Store.cpp"
using namespace std;
/**
*Class which for the Manchester Baby which contains the processor and the store and the functions
*they require to perform the fetch execute cycle
*
*/
class ManBaby{
private :
//Object for the processor
Processor theProcessor;
//Object for the store (memory)
Store theStore;
public :
void printCI();
void printPI();
void printAcc();
void printStore();
void printStoreLine(int operand);
bool loadProgramToMemory();
void jmp(int operand);
void jrp(int operand);
void ldn(int operand);
void sto(int operand);
void sub(int operand);
void cmp();
void fetch();
bool decode();
bool execute(int opcode, int operand);
void run();
};
/**
*Method to print the contents of the CI (Control Instruction)
*
*/
void ManBaby::printCI(){
cout << "CI : ";
for(int i = 0; i < 32; i++){
cout << theProcessor.getCI()[i];
}
cout << endl;
}
/**
*Method to print the contents of the PI (Present Instruction)
*
*/
void ManBaby::printPI(){
cout << "PI : ";
for(int i = 0; i < 32; i++){
cout << theProcessor.getPI()[i];
}
cout << endl;
}
/**
*Method to print the contents of the Accumulator
*
*/
void ManBaby::printAcc(){
cout << "Accumulator : ";
for(int i = 0; i < 32; i++){
cout << theProcessor.getAccumulator()[i];
}
cout << endl;
}
/**
*Method to print the contents of the store (memory)
*
*/
void ManBaby::printStore(){
cout << "Store : " << endl;
for(int j = 0; j < 32; j++){
for(int i = 0; i < 32; i++){
cout << theStore.readMemory(j)[i];
}
cout << endl;
}
}
/**
*Method to print the contents of the a given line of memory in the store (memory)
*
*param : operand - the memory location for the line of memory to be printed
*/
void ManBaby::printStoreLine(int operand){
cout << "Value at Store : ";
for(int i = 0; i < 32; i++){
cout << theStore.readMemory(operand)[i];
}
cout << endl;
}
/**
*Method to take the file name of for the txt file containing the machine code to be executed and
*then load the contents of said file into the stoe (memory)
*
*return : whether or not the file entered by the user exists or not
*/
bool ManBaby::loadProgramToMemory(){
string fileName;
bool exists;
cout << "Enter Filename (Without Extension): " << endl;
getline(cin, fileName);
//adds the files extension to the file name
fileName.append(".txt");
exists = theStore.loadProgram(fileName);
if(exists){
theProcessor.resetCI();
theProcessor.resetAccumulator();
printStore();
cout << endl;
return true;
}
else{
return false;
}
}
/**
*Method which jumps to the instruction at the address obtained from the specific memory address
*by setting the CI to the value stored at said address
*
*param a: int operand - integer to be used for operation
*/
void ManBaby::jmp(int operand){
theProcessor.setCI(theStore.readMemory(operand));
}
/**
*Method which jumps to the instruction at the program counter + the relative value obtained from the specified memory address
*
*param a: int operand - integer to be used for operation
*/
void ManBaby::jrp(int operand){
int ciInt = theProcessor.convertBinToDec(theProcessor.getCI(), 32);
int memStore = theProcessor.convertBinToDec(theStore.readMemory(operand), 32);
ciInt += memStore;
theProcessor.setCI(theProcessor.convertDecToBin(ciInt));
}
/**
*Method which takes the number from the specified memory address and puts it into the accumulator
*
*param a: int operand - integer to be used for operation
*/
void ManBaby::ldn(int operand){
theProcessor.setAccumulator(theProcessor.negate(theStore.readMemory(operand)));
}
/**
*Method which stores the number in the accumulator at the specified memory address
*
*param a: int operand - integer to be used for operation
*/
void ManBaby::sto(int operand){
theStore.writeMemory(operand, theProcessor.getAccumulator());
}
/**
*Method which subtracts the number at the specified memory address from the value in the accumulator
*and then stores the result in the accumulator
*
*param a: int operand - integer to be used for operation
*/
void ManBaby::sub(int operand){
int accuDecimal = theProcessor.convertBinToDec(theProcessor.getAccumulator(), 32);
int memStore = theProcessor.convertBinToDec(theStore.readMemory(operand), 32);
accuDecimal -= memStore;
theProcessor.setAccumulator(theProcessor.convertDecToBin(accuDecimal));
}
/**
*Method which skips the next instruction if the accumulator contains a negative number
*
*/
void ManBaby::cmp(){
int accuDecimal = theProcessor.convertBinToDec(theProcessor.getAccumulator(), 32);
if(accuDecimal < 0){
theProcessor.increment();
}
}
/**
*Method which fetches the present instruction from the store (memory)
*
*/
void ManBaby::fetch(){
int memoryAddress;
printCI();
theProcessor.increment();
memoryAddress = theProcessor.convertBinToDec(theProcessor.getCI(),32);
printCI();
theProcessor.setPI(theStore.readMemory(memoryAddress));
printPI();
}
/**
*Method which extratcs the operand and opcode from the presnet instruction and uses them for the
*execute method
*
*return - whether or not the program has finished
*/
bool ManBaby::decode(){
int operand;
int opcode;
int num;
cout << "Operand : ";
//Gets the operand as the first 5 values in the present instruction
operand = theProcessor.getOp(0, 4);
cout << "Opcode : ";
//Gets the opcode as the values from position 13 to position 15 in the present instrcution
opcode = theProcessor.getOp(13, 15);
cout << endl;
execute(opcode, operand);
}
/**
*Method which uses ths decoded instruction to execute the instruction
*
*return - whether or not the program has finished
*/
bool ManBaby::execute(int opcode, int operand){
switch(opcode){
case 0 :
cout << "JMP" << endl;
jmp(operand);
printStoreLine(operand);
printCI();
cout << endl;
break;
case 1 :
cout << "JRP" << endl;
printCI();
jrp(operand);
printStoreLine(operand);
printCI();
cout << endl;
break;
case 2 :
cout << "LDN" << endl;
ldn(operand);
printStoreLine(operand);
printAcc();
cout << endl;
break;
case 3 :
cout << "STO" << endl;
sto(operand);
printAcc();
printStoreLine(operand);
cout << endl;
break;
case 4 :
cout << "SUB" << endl;
printAcc();
printStoreLine(operand);
sub(operand);
printAcc();
cout << endl;
break;
case 5 :
cout << "SUB" << endl;
printAcc();
printStoreLine(operand);
sub(operand);
printAcc();
sub(operand);
cout << endl;
break;
case 6 :
cout << "CMP" << endl;
printAcc();
printCI();
cmp();
printCI();
break;
case 7 :
cout << "STP" << endl;
cout << "Program Terminated" << endl;
cout << endl;
return false;
break;
default :
cout << "Error in Machine Code, opcode does not exist" << endl;
break;
}
}
/**
*Method to load the program into memeory then run the fetch execute cycle until the stop instruction
*is given
*
*/
void ManBaby::run(){
bool run;
if(loadProgramToMemory()){
do{
fetch();
run = decode();
}while(run);
}
}
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
*Method which validates if what is entered by the user is an integer
*
*return : myInt - integer value entered by the user
*/
int readInt(){
string input;
int myInt;
while (true){
getline(cin, input);
stringstream stream(input);
if (stream >> myInt){
break;
}
cout << "Please only enter an integer value" << endl;
}
return myInt;
}
/**
* Displays a basic text menu to the user
*
*/
void displayMenu(){
cout << "(1) Load Program" << endl;
cout << "(2) Exit" << endl;
}
/**
*Method to handle the user selection for the menu
*
*/
void menu(){
ManBaby theBaby;
int option;
do
{
displayMenu();
cout << "Enter an Option: ";
option = readInt();
switch(option){
case 1:
theBaby.run();
break;
case 2:
cout << "Exiting Program" << endl;
break;
default:
cout << "Invalid Option" << endl;
break;
}
}
while(option != 2);
}
/**
*Main method where the program is run from
*
*/
int main(){
menu();
return 0;
}
<file_sep>/**
*Authors : <NAME>, <NAME>, <NAME>
*Version : 1.0 22nd November 2015
*
*/
#include <iostream>
#include <string>
#include <fstream>
#include "Store.h"
using namespace std;
/**
*Constructor to initialise the Store to all 0s
*
*/
Store::Store(){
for(int i = 0; i < 32; i++){
for(int j = 0; j < 32; j++){
memory[i][j] = 0;
}
}
}
/**
*Method to read a line of memory from a specified address
*
*param : location - the memory addres to be read from
*return : data - the binary number stored at the specified memory address
*/
bool* Store::readMemory(int location){
//Static array for the data held at the memory location so that it is not destroyed when the
//function terminates
bool static data[32];
for(int i = 0; i < 32; i++){
data[i] = memory[location][i];
}
return data;
}
/**
*Method to write to a specific memory address
*
*param : location - the memory address to be written to
*param : data - the data to be written to the address
*/
void Store::writeMemory(int location, bool data[32]){
for(int i = 0; i < 32; i++){
memory[location][i] = data[i];
}
}
/**
*Method to load the machine code from a text filme into the store
*
*param : fileName - the name of the file to be read from
*return whether or not the file existed
*/
bool Store::loadProgram(string fileName){
ifstream reader;
string nextLine;
reader.open(fileName.c_str());
if(reader.is_open()){
int j = 0;
while(!reader.eof()){
getline(reader, nextLine);
for(int i = 0; i < nextLine.length(); i++){
memory[j][i] = nextLine.at(i) - '0';
}
j++;
}
return true;
}
else{
cout << "File does not exist" << endl;
return false;
}
}
<file_sep>/**
*Class which holds the nessessary data structures and logic to simulate the Manchester Baby's Store.
*(memory)
*
*Authors : <NAME>, <NAME>, <NAME>
*Version : 1.0 22nd November 2015
*
*/
class Store{
private :
//2D boolean array for the memory
bool memory[32][32];
public :
Store();
bool* readMemory(int location);
void writeMemory(int location, bool data[32]);
bool loadProgram(string fileName);
};
|
94b30124c69413f1b95807c7a742a0257b1be3ba
|
[
"Markdown",
"C++"
] | 7
|
Markdown
|
TwoRice/ManBaby
|
048ea7fd7d2c8087ba7d73b647131515e817f1fb
|
5dec5d5d887fddc241169f8276bacb974819d4b4
|
refs/heads/master
|
<repo_name>yuchen16/Activity<file_sep>/analyse/log_analyser.py
#coding=utf-8
import sys
api_count = {}
if __name__=="__main__":
print "in main..."
filename = sys.argv[1]
print "filename is : ", filename
fd = open(filename, 'r')
if not fd:
print "open file error.."
sys.exit()
line = fd.readline()
while line:
data = line.strip('\r\n')
info = data.split(' ')
api_name = info[5].split('/')[1].strip(']')
cost_time = info[6].split(':')[1].strip('[').strip(']').strip('s')
#print api_name, ' ', cost_time
if api_count.has_key(api_name):
api_count[api_name]['count'] += 1
api_count[api_name]['cost'] += float(cost_time)
else:
temp = {'count':1, 'cost':float(cost_time)}
api_count[api_name] = temp
line = fd.readline()
print "END"
#print api_count
for apiname, info in api_count.items():
#print info['count'], 'times', apiname, 'avg cost: ', info['cost']/info['count']
print "%4s times %30s avg cost: %40s"%(info['count'], apiname, info['cost']/info['count'])
<file_sep>/README.md
# Activity
upgrade activity sever
|
433f5e3c815455f5acf7ae14f8891b3e8560a2ea
|
[
"Markdown",
"Python"
] | 2
|
Python
|
yuchen16/Activity
|
2da960287ec826c0f78c3906fc47d18cdd09ccfb
|
4286f45bdb17f8f8e08aacd563222d785d1a4099
|
refs/heads/main
|
<file_sep>const { expect } = require("chai");
const qty = "100000000000000000000000";
const month_in_seconds = 2628000;
const r = {
m1: "1680633033310046341168",
m2: "3389511340546621956208",
m12m1: "22140274964779807753125",
m12: "22140275739388350171449",
};
describe("Staking Contract", function () {
let ERC20TokenContract;
let StakingContract;
let ERC20Token;
let Staking;
let owner;
let addr1;
let addr2;
let addrs;
let depositTime;
before(async function () {
[owner, addr1, addr2, ...addrs] = await ethers.getSigners();
ERC20TokenContract = await ethers.getContractFactory("CARR");
// [walletOwner, wallet1, ...wallets] = ethers.getWallets();
StakingContract = await ethers.getContractFactory("Staking");
ERC20Token = await ERC20TokenContract.deploy();
Staking = await StakingContract.deploy(ERC20Token.address);
await ERC20Token.transfer(addr1.address, qty);
});
describe("debug", async function () {
it("Does not accept ether", async function () {
const params = { to: Staking.address, value: ethers.utils.parseEther("1.0") };
await expect(owner.sendTransaction(params)).to.be.reverted;
await expect(addr1.sendTransaction(params)).to.be.reverted;
});
});
describe("Deployment", async function () {
describe("Ownership", async function () {
it("Is owned by the deployer", async function () {
expect(await Staking.owner()).to.equal(owner.address);
});
it("Allows successful ownership transfer", async function () {
await expect(Staking.transferOwnership(addr1.address)).to.emit(Staking, "OwnershipTransferred").withArgs(owner.address, addr1.address);
expect(await Staking.owner()).to.equal(addr1.address);
});
it("Allows ownership to revert back", async function () {
await expect(Staking.connect(addr1).transferOwnership(owner.address)).to.emit(Staking, "OwnershipTransferred").withArgs(addr1.address, owner.address);
expect(await Staking.owner()).to.equal(owner.address);
});
});
describe("Balances", async function () {
it("Has no balance for the owner", async function () {
expect(await Staking.balanceOf(owner.address)).to.equal(0);
});
it("Has no rewards for the owner", async function () {
expect(await Staking.rewardsOf(owner.address)).to.equal(0);
});
it("Has no balance for regular users", async function () {
expect(await Staking.balanceOf(addr1.address)).to.equal(0);
});
it("Has no rewards for regular users", async function () {
expect(await Staking.rewardsOf(addr1.address)).to.equal(0);
});
it("Has no totalSupply", async function () {
expect(await Staking.totalSupply()).to.equal(0);
});
})
describe("Carr Management", async function () {
it("Has an balance of CARR tokens to distribute", async function () {
expect(await ERC20Token.balanceOf(Staking.address)).to.equal("5000000000000000000000000");
});
it("Can receive CARR directly", async function () {
await ERC20Token.transfer(Staking.address, "1000")
expect(await ERC20Token.balanceOf(Staking.address)).to.equal("5000000000000000000001000");
});
it("Can recover CARR to owner address", async function () {
await expect(Staking.recoverERC20(ERC20Token.address, "1000")).to.emit(Staking, "Recovered").withArgs(ERC20Token.address, "1000")
expect(await ERC20Token.balanceOf(Staking.address)).to.equal("5000000000000000000000000");
});
});
});
describe("Active", async function () {
it("Accepts deposits", async function () {
await ERC20Token.approve(Staking.address, qty); // owner stakes qty
await expect(Staking.stake(qty)).to.emit(Staking, 'Staked').withArgs(owner.address, qty);
depositTime = (await ethers.provider.getBlock(await ethers.provider.getBlockNumber())).timestamp;
expect(await Staking.balanceOf(owner.address)).to.equal(qty);
});
it("Has no rewards initially", async function () {
expect(await Staking.rewardsOf(owner.address)).to.equal("0");
});
it("Allows deposits from regular users", async function () {
await ERC20Token.connect(addr1).approve(Staking.address, qty); // owner stakes qty
await expect(Staking.connect(addr1).stake(qty)).to.emit(Staking, 'Staked').withArgs(addr1.address, qty);
expect(await Staking.balanceOf(addr1.address)).to.equal(qty);
});
it("Set the finishTime to 1 year after deposit", async function () {
await expect(Staking.setFinish(depositTime + 31536000))
.to.emit(Staking, "StakingEnds").withArgs(depositTime + 31536000); // finish 1 year after deposit
});
it("Verifies interest after 1 month", async function () {
await ff(month_in_seconds);
expect(await Staking.rewardsOf(owner.address)).to.equal(r.m1);
});
it("Verifies interest after 2 months", async function () {
await ff(2 * month_in_seconds);
expect(await Staking.rewardsOf(owner.address)).to.equal(r.m2);
});
it("Verifies interest after 1 year (- 1 second)", async function () {
await ff(12 * month_in_seconds - 1);
expect(await Staking.rewardsOf(owner.address)).to.equal(r.m12m1);
});
it("Verifies interest after 1 year", async function () {
await ff(12 * month_in_seconds);
expect(await Staking.rewardsOf(owner.address)).to.equal(r.m12);
});
});
describe("Finished", async function () {
it("Stops accepting deposits", async function () {
// await ERC20Token.approve(Staking.address, qty); // owner stakes qty
await expect(Staking.stake(qty)).to.be.revertedWith("Staking period has ended");
});
it("Stops increasing rewards", async function () {
await ff(month_in_seconds * 12 + 1);
expect(await Staking.rewardsOf(owner.address)).to.equal(r.m12);
await ff(month_in_seconds * 13);
expect(await Staking.rewardsOf(owner.address)).to.equal(r.m12);
});
it("Has expected totalSupply", async function () {
expect(await Staking.totalSupply()).to.equal("200000000000000000000000");
});
it("Allows withdrawals", async function () {
// emit Withdrawn(to, amount);
await expect(Staking.withdraw(qty))
.to.emit(Staking, "Withdrawn").withArgs(owner.address, qty)
.to.emit(Staking, 'Staked').withArgs(owner.address, r.m12);
expect(await Staking.balanceOf(owner.address)).to.equal(r.m12);
expect(await ERC20Token.balanceOf(owner.address)).to.equal("4900000000000000000000000");
});
it("Has expected totalSupply", async function () {
expect(await Staking.totalSupply()).to.equal("122140275739388350171449");
});
it("Allows full withdrawals", async function () {
await expect(Staking.withdrawAll())
.to.emit(Staking, "Withdrawn").withArgs(owner.address, r.m12)
.to.not.emit(Staking, "Staked");
expect(await Staking.balanceOf(owner.address)).to.equal(0);
expect(await ERC20Token.balanceOf(owner.address)).to.equal("4922140275739388350171449");
});
it("Has expected totalSupply", async function () {
expect(await Staking.totalSupply()).to.equal("100000000000000000000000");
});
it("Allows withdrawals from regular user", async function () {
await expect(Staking.connect(addr1).withdraw(qty))
.to.emit(Staking, 'Withdrawn').withArgs(addr1.address, qty)
.to.emit(Staking, 'Staked').withArgs(addr1.address, "22140274190171270240817");
expect(await Staking.balanceOf(addr1.address)).to.equal("22140274190171270240817");
expect(await ERC20Token.balanceOf(addr1.address)).to.equal("100000000000000000000000");
expect(await Staking.totalSupply()).to.equal("22140274190171270240817");
});
it("Allows regular users to withdrawAll", async function () {
await expect(Staking.connect(addr1).withdrawAll())
.to.emit(Staking, 'Withdrawn')
.to.not.emit(Staking, "Staked");
expect(await Staking.balanceOf(addr1.address)).to.equal("0");
expect(await ERC20Token.balanceOf(addr1.address)).to.equal("122140274190171270240817");
expect(await Staking.totalSupply()).to.equal("0");
});
it("Can receive CARR directly", async function () {
await ERC20Token.transfer(Staking.address, qty)
expect(await ERC20Token.balanceOf(Staking.address)).to.equal("5055719450070440379587734");
});
it("Can recover CARR to owner address", async function () {
const q = "55719450070440379587734";
await expect(Staking.recoverERC20(ERC20Token.address, q)).to.emit(Staking, "Recovered").withArgs(ERC20Token.address, q)
expect(await ERC20Token.balanceOf(Staking.address)).to.equal("5000000000000000000000000");
});
});
async function ff(t) {
let block = await ethers.provider.getBlock(await ethers.provider.getBlockNumber());
const deltaT = depositTime + t - block.timestamp;
if (deltaT) {
await ethers.provider.send('evm_increaseTime', [deltaT]); // one year
await hre.ethers.provider.send('evm_mine');
}
}
});
<file_sep>test:
npx hardhat test
.PHONY: test<file_sep># Carnmaly CARR Token Staking Contract
This project contains the CARR Staking contract, and a variety of test cases.
* Private Repo: https://gitlab.it.ardentcreative.com/clients/carnomaly/staking/solidity-contract
* Public Mirror: https://github.com/CarnomalyDevTeam/carr-staking-contract/
You must provide your own ERC20 token contract, and initialize the Staking
contract with the token's address in order to use this.
|
2b1127eafcf49aa1f6eb5dfe05c0091f645479e7
|
[
"JavaScript",
"Makefile",
"Markdown"
] | 3
|
JavaScript
|
CarnomalyDevTeam/carr-staking-contract
|
37cd26ba2ecbc3ff906a29373f88fd8b11222ec2
|
638d40f2a116b7a351d16a2860d67a43210e0db0
|
refs/heads/main
|
<repo_name>Ankur45/MERN-SHOPPING-<file_sep>/backend/config/db.js
const mongoose = require('mongoose');
require('dotenv').config();
const connectDB = async() =>{
try {
await mongoose.connect(process.env.MONGO_URI,{
useNewUrlParser : true,
// useUnifiedTopologu:true
});
console.log('MongoDB connection Successful');
} catch (error) {
console.error('MongoDB connection Fails');
process.exit(1);
}
}
module.exports = connectDB;
|
65643d47412931f16ab369eaf1bb7192c87bc65e
|
[
"JavaScript"
] | 1
|
JavaScript
|
Ankur45/MERN-SHOPPING-
|
bbe27f69749f6b6cdaeb5344fce0df319fb655ba
|
5ac430b3bc35c6ecfa62352cfa9b970fdd071c6a
|
refs/heads/master
|
<repo_name>pl2599/Image-Classification-Otters<file_sep>/functions/functions.py
#!/usr/bin/env python
# coding: utf-8
# In[1]:
get_ipython().run_line_magic('matplotlib', 'inline')
# In[ ]:
from fastai import *
from fastai.vision import *
# In[2]:
def downloadImages(path, folder, file, max_pic_n):
#This function takes in the path, folder, and txt file names and downloads all the images
dest = path/folder
dest.mkdir(parents = True, exist_ok = True)
download_images(path/file, dest, max_pics = max_pic_n)
# # Uncomment below to convert to py script
# In[4]:
#!jupyter nbconvert --to script functions.ipynb
<file_sep>/README.md
# Image Classification - Otters
A Convoluted Neural Network that classifies images as a Sea Otter or River Otter.
<p align = 'center'>
<img src="figs/seaOtter.jpg" width = '360'>
</p>
## Objective
The purpose of this project is to predict whether an image is a Sea Otter or a River Otter. Many people mix up sea otters with river otters, as there are physical similarities between them. This project serves to see if a machine would be able to distinguish between the two species despite their similarities.
## Motivation
This is primarily an *educational* project for me to learn about deep learning through Python. My model relies on the [fastai](https://github.com/fastai/fastai) library, a deep learning library built on top of [PyTorch](https://github.com/pytorch/pytorch).
I added a fun element to this project by training the model on images of otters. As many of my friends know, sea otters are my favorite animal, and I get asked a lot about the visual differences between sea otters and river otters. This motivated me to build a CNN model, which is known to perform well on image classification, and deploy it on a [Web App](https://otter-classifier-255602.appspot.com/).
## Project Description
### Set Up
1. Jupyter Notebook
The main file uses Jupyter Notebook. Please follow the instructions [here](https://github.com/pl2599/Image-Classification-Otters/tree/master/doc) to install Jupyter Notebook.
2. fastai Library
Likewise, please follow the instructions [here]((https://github.com/pl2599/Image-Classification-Otters/tree/master/doc)) to install fastai.
### Data
The data used to train the modle are 400 images from google for each of the two classes:
* Sea Otter
* River Otter
These images are read from a text file containing the urls and validated using the *download_images* and *verify_images* functions respectively. The classes are tagged based on the folder that the images reside in using the *ImageDataBunch.from_folder* function.
Here is a glimpse of the data:

### Model
I use a Convoluted Neural Network ("CNN") to train images of otters, as CNN is known to perform well on image classification. The model implements the following concepts:
#### Transfer Learning
I use [ResNet50](https://www.mathworks.com/help/deeplearning/ref/resnet50.html), a pre-trained CNN that uses the imagenet dataset as the backbone of our model. Transfer learning allows me to utilize this model that has already been trained on a large dataset and customize it for my more specific use-case.
When initialized, the initial layers of the CNN are frozen, so only the last layer could be trained on. Therefore I have to *unfreeze* the models after each training iteration. After unfreezing the layers of the model, I can adjust the weights of the layers by training it on only the sea otters and river otter images.
#### One Cycle Policy
The *learn.fit_one_cycle* model that is utilized to train the CNN follows <NAME>'s [One Cycle Policy](https://arxiv.org/abs/1803.09820). Essentially, the motivation is to vary the learning rate as it progresses through the layers to improve performance and speed up training. I implement the One Cycle Policy by following this general progression:
1. Determine Learning Rate (lr) via *learn.recorder.plot*
2. Train using *learn.fit_one_cycle*
3. Unfreeze Layers
4. Determine new learning rate (new_lr)
4. Train using *learn.fit_one_cycle*
An example of the reading the learning plot to determine the learning rate is shown below:

Looking at this plot, the slope is steepest from 1e-4 to 1e-2. Therefore, an appropriate learning rate here is around 3e-3.
#### Progressive Resizing
This concept is taught and used by <NAME> to enhance model performance. In this project, I initially trained our model using 64x64 images of otters using the One Cycle Policy. Afterwards, using the trained model, I repeated the process using the same images, but sized to 128x128.
## Outcome
In the end, the model has a 89% accuracy tested on the validation set. The confusion matrix below illustrates this.

As there are many similarities between Sea Otters and River Otters (especially in water), this accuracy rate is pretty high for this case.
|
ed31c139a57af4c85cedf68c4e039ec66806e378
|
[
"Markdown",
"Python"
] | 2
|
Python
|
pl2599/Image-Classification-Otters
|
b8c8d7002f3c2f912035ad94714abb9c8c8d158a
|
a4d537fecf7d46f5e6604f8a82a10cf305e053bc
|
refs/heads/master
|
<file_sep>import os
from setuptools import setup
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as fp:
long_description = fp.read()
setup(
name='datauri',
description="implementation of the data uri scheme defined in rfc2397",
long_description=long_description,
version='1.0.0',
author="EclecticIQ",
author_email="<EMAIL>",
packages=['datauri'],
url='https://github.com/eclecticiq/python-data-uri',
license="BSD",
classifiers=[
'Development Status :: 5 - Production/Stable',
"License :: OSI Approved :: BSD License",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
'Topic :: Software Development :: Libraries',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
<file_sep>=======
datauri
=======
``datauri`` is a small Python library implementing the ``data:`` uri
scheme defined in RFC2397_. The generic format is::
data:[<mediatype>][;base64],<data>
.. _RFC2397: https://tools.ietf.org/html/rfc2397
Installation
============
Install ``datauri`` from PyPI using::
pip install datauri
Note: this library is for Python 3 only.
Usage
=====
.. code-block:: python
>>> import datauri
To parse a string containing a ``data:`` uri, use ``parse()``:
.. code-block:: python
>>> parsed = datauri.parse('data:text/plain,A%20brief%20note')
This returns a parse result:
.. code-block:: python
>>> parsed.media_type
'text/plain'
>>> parsed.data
b'A brief note'
>>> parsed.uri
'data:text/plain,A%20brief%20note'
This is a simple container class with a few attributes:
* The ``media_type`` attribute is a string (``str``) or ``None`` in
case it was absent. Any (optional) embedded text encoding
specifications are not processed in any way; it is up to the
application to deal with that.
* The ``data`` attribute is a byte string (``bytes``) with the decoded
data. URL encoding and base64 is handled transparently.
* For convenience, the ``uri`` attribute contains the input uri.
Parsed URIs compare equal if their media type and data are the same.
Instances are hashable, so they can be used as dictionary keys.
Parsing failures will raise a ``DataURIError``:
.. code-block:: python
>>> datauri.parse('invalid')
Traceback (most recent call last):
…
datauri.DataURIError: invalid data uri
The ``DataURIError`` subclasses the built-in ``ValueError``,
so this will work as expected:
.. code-block:: python
try:
datauri.parse('invalid')
except ValueError:
pass
In addition to parsing a string, this library can also discover (and
directly parse) any ``data:`` URIs found in a larger string:
.. code-block:: python
s = 'long string with data:text/plain,A%20brief%20note and more'
for parsed in datauri.discover(s):
print(s)
More information
================
- RFC2397:
https://tools.ietf.org/html/rfc2397
- Wikipedia:
https://en.wikipedia.org/wiki/Data_URI_scheme
- Mozilla developer documentation:
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
Known issues
============
Currently, only parsing has been implemented.
Contributing
============
Please use Github issues to report problems or propose improvements.
Version history
===============
* 1.0.0
Initial release.
License
=======
*(This is the OSI approved 3-clause "New BSD License".)*
Copyright © 2017, EclecticIQ
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
* Neither the name of the author nor the names of its contributors may be used
to endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<file_sep>[tox]
envlist = py33,py34,py35,py36
[testenv]
deps=-rrequirements-test.txt
commands=
pytest --cov {envsitepackagesdir}/datauri {posargs} tests/
flake8 datauri/
<file_sep>import datauri
import pytest
SAMPLE_URL_ENCODED = 'data:,A%20brief%20note'
SAMPLE_BASE64_ENCODED = (
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA'
'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO'
'9TXL0Y4OHwAAAABJRU5ErkJggg==')
def test_parse_url_encoded():
# from https://tools.ietf.org/html/rfc2397
parsed = datauri.parse(SAMPLE_URL_ENCODED)
assert parsed.media_type is None
assert parsed.data == b'A brief note'
assert parsed.uri == SAMPLE_URL_ENCODED
parsed = datauri.parse('data:text/plain;charset=whatever,%aa%bb%cc')
assert parsed.media_type == 'text/plain;charset=whatever'
assert parsed.data == b'\xaa\xbb\xcc'
def test_parse_base64():
# from https://en.wikipedia.org/wiki/Data_URI_scheme
parsed = datauri.parse(SAMPLE_BASE64_ENCODED)
assert parsed.media_type == 'image/png'
assert parsed.data.startswith(b'\x89PNG')
def test_parse_base64_with_missing_padding():
# from https://en.wikipedia.org/wiki/Base64#Output_Padding
parsed = datauri.parse('data:text/plain;base64,YW55IGNhcm5hbCBwbGVhcw')
assert parsed.data == b'any carnal pleas'
parsed = datauri.parse('data:text/plain;base64,YW55IGNhcm5hbCBwbGVhc3U')
assert parsed.data == b'any carnal pleasu'
parsed = datauri.parse('data:text/plain;base64,YW55IGNhcm5hbCBwbGVhc3Vy')
assert parsed.data == b'any carnal pleasur'
def test_parse_invalid():
invalid_inputs = [
'',
'foobar',
'http://not-a-data-uri',
'data:',
'data:text/plain;base64,Y'
]
for s in invalid_inputs:
with pytest.raises(datauri.DataURIError) as excinfo:
datauri.parse(s)
assert 'data uri' in str(excinfo.value)
def test_discover():
template = """
blah {} blah and
{} and some more blah
this one is incomplete data:
and this one is malformed data:foobar
"""
text = template.format(SAMPLE_URL_ENCODED, SAMPLE_BASE64_ENCODED)
g = datauri.discover(text)
actual = list(g)
expected = [
datauri.parse(SAMPLE_URL_ENCODED),
datauri.parse(SAMPLE_BASE64_ENCODED)]
assert actual == expected
def test_container_equality():
a = datauri.parse(SAMPLE_URL_ENCODED)
b = datauri.parse(SAMPLE_URL_ENCODED)
assert a == b
def test_repr():
a = datauri.parse(SAMPLE_URL_ENCODED)
actual = repr(a)
expected = "<ParsedDataURI media_type=None data=b'A brief note'>"
assert actual == expected
b = datauri.parse(SAMPLE_BASE64_ENCODED)
assert repr(b).endswith("...'>")
def test_is_hashable():
a = datauri.parse(SAMPLE_URL_ENCODED)
b = datauri.parse(SAMPLE_URL_ENCODED)
assert hash(a) == hash(b)
<file_sep>import base64
import re
import urllib.parse
# RFC 3986: reserved characters, unreserved characters, and percent.
# See https://tools.ietf.org/html/rfc3986#section-2
RE_DATA_URI = re.compile(
'data:[{unreserved}{reserved}{percent}]+'
.format(
unreserved="A-Za-z0-9-_.~",
reserved=":/?#\[\]@!$&'()*+,;=", # only square brackets are escaped
percent='%'))
class DataURIError(ValueError):
"""
Exception raised when parsing fails.
This class subclasses the built-in ``ValueError``.
"""
pass
class ParsedDataURI:
"""
Container for parsed data URIs.
Do not instantiate directly; use ``parse()`` instead.
"""
def __init__(self, media_type, data, uri):
self.media_type = media_type
self.data = data
self.uri = uri
def __repr__(self):
raw = self.data
if len(raw) > 20:
raw = raw[:17] + b'...'
return '<ParsedDataURI media_type={!r} data={!r}>'.format(
self.media_type, raw)
def __eq__(self, other):
return (self.media_type, self.data) == (other.media_type, other.data)
def __hash__(self):
return hash((self.media_type, self.data))
def parse(uri):
"""
Parse a 'data:' URI.
Returns a ParsedDataURI instance.
"""
if not uri.startswith('data:'):
raise DataURIError('invalid data uri')
s = uri[5:]
if not s or ',' not in s:
raise DataURIError('invalid data uri')
media_type, _, raw_data = s.partition(',')
is_base64_encoded = media_type.endswith(';base64')
if is_base64_encoded:
media_type = media_type[:-7]
missing_padding = '=' * (-len(raw_data) % 4)
if missing_padding:
raw_data += missing_padding
try:
data = base64.b64decode(raw_data)
except ValueError as exc:
raise DataURIError('invalid base64 in data uri') from exc
else:
# Note: unquote_to_bytes() does not raise exceptions for invalid
# or partial escapes, so there is no error handling here.
data = urllib.parse.unquote_to_bytes(raw_data)
if not media_type:
media_type = None
return ParsedDataURI(media_type, data, uri)
def discover(s):
"""
Discover 'data:' URIs in a string.
This returns a generator that yields data URIs found in the string.
"""
for match in RE_DATA_URI.finditer(s):
try:
yield parse(match.group())
except DataURIError:
continue
<file_sep>"""
datauri, library for "data:" URIs as defined in RFC 2397.
"""
from .datauri import ( # noqa: F401
DataURIError,
discover,
parse)
|
ebea538173f35e6bb732c083701823992c1ed2cf
|
[
"Python",
"reStructuredText",
"INI"
] | 6
|
Python
|
eclecticiq/python-data-uri
|
4e4a781c14a740f1054914b60fe1c8eea47cbbd5
|
3a368f451572854f69b7daa67b64bca8192f8e07
|
refs/heads/master
|
<repo_name>betasspace/MNIST<file_sep>/v1/create_dataset_npy.py
import os
import numpy as np
from PIL import Image
from sklearn.model_selection import train_test_split
x, y = [], []
for i, image_path in enumerate(os.listdir('../images/')):
label = int(image_path.split('_')[0])
label_one_hot = [int(i == label) for i in range(10)]
# print('label_one_hot: ', label_one_hot)
y.append(label_one_hot)
image = Image.open('../images/%s' % image_path).convert('L')
image_arr = 1 - np.reshape(image, 784) / 255.0
# print('image_arr:', image_arr)
x.append(image_arr)
np.save('../manual_data_set/X.npy', np.array(x))
np.save('../manual_data_set/Y.npy', np.array(y))
class DataSet:
def __init__(self):
x, y = np.load('../manual_data_set/X.npy'), np.load('../manual_data_set/Y.npy')
self.train_x, self.test_x, self.train_y, self.test_y = \
train_test_split(x, y, test_size=0.2, random_state=0)
self.train_size = len(self.train_x)
def get_train_batch(self, batch_size=64):
# size 连续多次随机,可重复
choice = np.random.randint(self.train_size, size=batch_size)
print(choice)
batch_x = self.train_x[choice, :]
batch_y = self.train_y[choice, :]
return batch_x, batch_y
def get_test_set(self):
return self.test_x, self.test_y
data = DataSet()
x, y = data.get_train_batch()
print(x)
print(y)
<file_sep>/v1/predict.py
import numpy as np
from PIL import Image
from v1.model import Network
import tensorflow as tf
import os
class Predict:
def __init__(self):
self.CKPT_DIR = './ckpt'
self.net = Network()
self.sess = tf.Session()
self.sess.run(tf.global_variables_initializer())
self.restore()
def restore(self):
saver = tf.train.Saver()
ckpt = tf.train.get_checkpoint_state(self.CKPT_DIR)
if ckpt and ckpt.model_checkpoint_path:
saver.restore(self.sess, ckpt.model_checkpoint_path)
else:
raise FileNotFoundError("未找到保存的模型")
def predict(self, image_path):
# 读图片,归一化,并转为黑白的
img = Image.open(image_path).convert('L')
flatten_img = np.reshape(img, 784) / 255.0
x = np.array([1 - flatten_img])
# print(x)
y = self.sess.run(self.net.y, feed_dict={self.net.x: x})
print(image_path)
print(' -> predict digit', np.argmax(y))
if __name__ == '__main__':
print("pwd:", os.getcwd())
app = Predict()
app.predict('../images/0_11.png')
app.predict('../images/1_8.png')
app.predict('../images/2_1.png')
app.predict('../images/3_169.png')
app.predict('../images/4_35.png')
app.predict('../images/4_94.png')
app.predict('../images/5_15.png')
# ../images/0_11.png
# -> predict digit 0
# ../images/1_8.png
# -> predict digit 1
# ../images/2_1.png
# -> predict digit 3
# ../images/3_169.png
# -> predict digit 3
# ../images/4_35.png
# -> predict digit 0
# ../images/5_15.png
# -> predict digit 5
<file_sep>/v2/model.py
import tensorflow as tf
class Network:
def __init__(self):
self.learning_rate = 0.001
self.x = tf.placeholder(tf.float32, [None, 784], name='x/input_layer')
self.label = tf.placeholder(tf.float32, [None, 10], name='label')
with tf.device('/device:GPU:0'):
self.w1 = tf.Variable(tf.random_uniform([784, 300], -1, 1), name='w/hidden_layer1')
self.b1 = tf.Variable(tf.random_uniform([300], -1, 1), name='bias/hidden_layer1')
self.h1 = tf.nn.sigmoid(tf.matmul(self.x, self.w1) + self.b1)
self.w2 = tf.Variable(tf.random_uniform([300, 10], -1, 1), name='w/hidden_layer2')
self.b2 = tf.Variable(tf.random_uniform([10], -1, 1), name='b/hidden_layer2')
self.y = tf.nn.softmax(tf.matmul(self.h1, self.w2) + self.b2, name='output_layer')
# # cross-entropy
# self.loss = -tf.reduce_sum(self.label * tf.log(self.y + 1e-10))
# MSE
self.loss = tf.reduce_mean(tf.square(self.label - self.y))
self.global_step = tf.Variable(0, trainable=False)
self.train = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate).minimize(self.loss,
self.global_step)
error = tf.not_equal(tf.argmax(self.label, 1), tf.argmax(self.y, 1))
self.error_rate = tf.reduce_mean(tf.cast(error, 'float'))
class NetworkLayer3:
def __init__(self):
self.learning_rate = 0.001
self.x = tf.placeholder(tf.float32, [None, 784], name='x/input_layer')
self.label = tf.placeholder(tf.float32, [None, 10], name='label')
with tf.device('/device:GPU:0'):
self.w1 = tf.Variable(tf.random_uniform([784, 500], -1, 1), name='w/hidden_layer1')
self.b1 = tf.Variable(tf.random_uniform([500], -1, 1), name='bias/hidden_layer1')
self.h1 = tf.nn.sigmoid(tf.matmul(self.x, self.w1) + self.b1)
self.w2 = tf.Variable(tf.random_uniform([500, 150], -1, 1), name='w/hidden_layer2')
self.b2 = tf.Variable(tf.random_uniform([150], -1, 1), name='b/hidden_layer2')
self.h2 = tf.nn.sigmoid(tf.matmul(self.h1, self.w2) + self.b2)
self.w3 = tf.Variable(tf.random_uniform([150, 10], -1, 1), name='w/hidden_layer3')
self.b3 = tf.Variable(tf.random_uniform([10], -1, 1), name='b/hidden_layer3')
self.y = tf.nn.softmax(tf.matmul(self.h2, self.w3) + self.b3, name='output_layer')
# cross-entropy
self.loss = -tf.reduce_sum(self.label * tf.log(self.y + 1e-10))
self.global_step = tf.Variable(0, trainable=False)
self.train = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate).minimize(self.loss,
self.global_step)
error = tf.not_equal(tf.argmax(self.label, 1), tf.argmax(self.y, 1))
self.error_rate = tf.reduce_mean(tf.cast(error, 'float'))
class NetworkLayer3TruncatedNormal:
def __init__(self):
self.learning_rate = 0.001
self.x = tf.placeholder(tf.float32, [None, 784], name='x/input_layer')
self.label = tf.placeholder(tf.float32, [None, 10], name='label')
with tf.device('/device:GPU:0'):
self.w1 = tf.Variable(tf.truncated_normal([784, 500], 0, 0.1), name='w/hidden_layer1')
self.b1 = tf.Variable(tf.truncated_normal([500], 0, 0.1), name='bias/hidden_layer1')
self.h1 = tf.nn.sigmoid(tf.matmul(self.x, self.w1) + self.b1)
self.w2 = tf.Variable(tf.truncated_normal([500, 150], 0, 0.1), name='w/hidden_layer2')
self.b2 = tf.Variable(tf.truncated_normal([150], 0, 0.1), name='b/hidden_layer2')
self.h2 = tf.nn.sigmoid(tf.matmul(self.h1, self.w2) + self.b2)
self.w3 = tf.Variable(tf.truncated_normal([150, 10], 0, 0.1), name='w/hidden_layer3')
self.b3 = tf.Variable(tf.truncated_normal([10], 0, 0.1), name='b/hidden_layer3')
self.y = tf.nn.softmax(tf.matmul(self.h2, self.w3) + self.b3, name='output_layer')
# cross-entropy
self.loss = -tf.reduce_sum(self.label * tf.log(self.y + 1e-10))
self.global_step = tf.Variable(0, trainable=False)
self.train = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate).minimize(self.loss,
self.global_step)
error = tf.not_equal(tf.argmax(self.label, 1), tf.argmax(self.y, 1))
self.error_rate = tf.reduce_mean(tf.cast(error, 'float'))
class NetworkLayer3WithReLU:
def __init__(self):
self.learning_rate = 0.001
self.x = tf.placeholder(tf.float32, [None, 784], name='x/input_layer')
self.label = tf.placeholder(tf.float32, [None, 10], name='label')
with tf.device('/device:GPU:0'):
self.w1 = tf.Variable(tf.truncated_normal([784, 500], 0, 0.1), name='w/hidden_layer1')
self.b1 = tf.Variable(tf.truncated_normal([500], 0, 0.1), name='bias/hidden_layer1')
self.h1 = tf.nn.relu(tf.matmul(self.x, self.w1) + self.b1)
self.w2 = tf.Variable(tf.truncated_normal([500, 150], 0, 0.1), name='w/hidden_layer2')
self.b2 = tf.Variable(tf.truncated_normal([150], 0, 0,1), name='b/hidden_layer2')
self.h2 = tf.nn.relu(tf.matmul(self.h1, self.w2) + self.b2)
self.w3 = tf.Variable(tf.truncated_normal([150, 10], 0, 0.1), name='w/hidden_layer3')
self.b3 = tf.Variable(tf.truncated_normal([10], 0, 0.1), name='b/hidden_layer3')
self.y = tf.nn.softmax(tf.matmul(self.h2, self.w3) + self.b3, name='output_layer')
# cross-entropy
self.loss = -tf.reduce_sum(self.label * tf.log(self.y + 1e-10))
self.global_step = tf.Variable(0, trainable=False)
self.train = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate).minimize(self.loss,
self.global_step)
error = tf.not_equal(tf.argmax(self.label, 1), tf.argmax(self.y, 1))
self.error_rate = tf.reduce_mean(tf.cast(error, 'float'))
<file_sep>/v1/train.py
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from v1.model import Network
class Train:
def __init__(self):
self.CKPT_DIR = './v1/ckpt'
self.net = Network()
self.sess = tf.Session()
self.sess.run(tf.global_variables_initializer())
# print("pwd:", os.getcwd())
self.data = input_data.read_data_sets('./data/', one_hot=True)
def train(self):
saver = tf.train.Saver(max_to_keep=5)
save_interval = 2000
batch_size = 64
train_step = 12000
step = 0
# merge所有的summary node 的op
merged_summary_op = tf.summary.merge_all()
# 存放在当前目录下的 log 文件夹中,获得文件句柄
merged_writer = tf.summary.FileWriter('./v1/log', self.sess.graph)
ckpt = tf.train.get_checkpoint_state(self.CKPT_DIR)
if ckpt and ckpt.model_checkpoint_path:
print('ckpt.model_checkpoint_path:', ckpt.model_checkpoint_path)
saver.restore(self.sess, ckpt.model_checkpoint_path)
step = self.sess.run(self.net.global_step)
print('Continue from')
print(' -> Minibatch update : ', step)
while step < train_step:
x, label = self.data.train.next_batch(batch_size)
_, loss, merged_summary = self.sess.run([self.net.train, self.net.loss, merged_summary_op],
feed_dict={
self.net.x: x,
self.net.label: label
})
step = self.sess.run(self.net.global_step)
if step % 100 == 0:
merged_writer.add_summary(merged_summary, step)
# if step % 10 == 0:
# print('step %5d loss: %.3f' % (step, loss))
if step % save_interval == 0:
saver.save(self.sess, self.CKPT_DIR + '/model', global_step=step)
print('%s/model-%d saved' % (self.CKPT_DIR, step))
self.calculate_accuracy()
def calculate_accuracy(self):
test_x = self.data.test.images
test_label = self.data.test.labels
accuracy = self.sess.run(self.net.accuracy,
feed_dict={
self.net.x: test_x,
self.net.label: test_label
})
print("test set accuracy: %.4f, total test case: %d" % (accuracy, len(test_label)))
if __name__ == "__main__":
app = Train()
app.train()
app.calculate_accuracy()
<file_sep>/v3/train.py
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np
from v3.model import LeNet5
import tensorflow as tf
from sklearn.utils import shuffle
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--epochs', type=int, default=10,
help='how many epochs should train.py run')
parser.add_argument('--save_interval', type=int, default=10,
help='interval epochs of saver')
parser.add_argument('--batch_size', type=int, default=64,
help='how many epochs should train.py run')
parser.add_argument('--dropout_prob', type=float, default=0.5,
help='how many epochs should train.py run')
args = parser.parse_args()
BATCH_SIZE = args.batch_size
class Train:
def __init__(self):
self.CKPT_DIR = './ckpt'
# Generate data set
mnist = input_data.read_data_sets("../data/", reshape=False, one_hot=True)
self.X_train, self.Y_train = mnist.train.images, mnist.train.labels
self.X_validation, self.Y_validation = mnist.validation.images, mnist.validation.labels
self.X_test, self.Y_test = mnist.test.images, mnist.test.labels
print("X_train.shape: ", self.X_train.shape)
print("X_validation.shape: ", self.X_validation.shape)
print("X_test.shape: ", self.X_test.shape)
self.X_train = np.pad(self.X_train, ((0, 0), (2, 2), (2, 2), (0, 0)), "constant", constant_values=0)
self.X_validation = np.pad(self.X_validation, ((0, 0), (2, 2), (2, 2), (0, 0)), "constant", constant_values=0)
self.X_test = np.pad(self.X_test, ((0, 0), (2, 2), (2, 2), (0, 0)), "constant", constant_values=0)
print("X_train.shape: ", self.X_train.shape)
print("X_validation.shape: ", self.X_validation.shape)
print("X_test.shape: ", self.X_test.shape)
self.net = LeNet5(learning_rate=0.001)
self.sess = tf.Session(config=tf.ConfigProto(
allow_soft_placement=True, log_device_placement=True))
self.sess.run(tf.global_variables_initializer())
def train(self):
epochs = args.epochs
num_examples = len(self.X_train)
saver = tf.train.Saver(max_to_keep=5)
save_interval = args.save_interval
for i in range(epochs):
x_train, y_train = shuffle(self.X_train, self.Y_train)
for offset in range(0, num_examples, BATCH_SIZE):
end = offset + BATCH_SIZE
x, y = x_train[offset:end], y_train[offset:end]
_, loss = self.sess.run([self.net.train, self.net.loss], feed_dict={
self.net.x: x,
self.net.label: y,
self.net.prob: args.dropout_prob,
})
error_rate, validation_loss = self.evaluate(self.X_validation, self.Y_validation)
print("EPOCH {} ...".format(i + 1))
print('Validation error rate = {:.5f}, Validation_loss = {:.5f}'.format(error_rate, validation_loss))
test_error_rate, test_loss = self.evaluate(self.X_test, self.Y_test)
print('-> Test error rate = {:.5f}, test_loss = {:.5f}'.format(test_error_rate, test_loss))
if (i + 1) % save_interval == 0:
saver.save(self.sess, self.CKPT_DIR + '/model_epochs_', global_step=i)
print('Model Saved.\n')
def evaluate(self, x_data, y_data):
error_rate, loss = self.sess.run([self.net.error_rate, self.net.loss], feed_dict={
self.net.x: x_data,
self.net.label: y_data,
self.net.prob: 1.0,
})
return error_rate, loss
if __name__ == '__main__':
app = Train()
app.train()
<file_sep>/v2/train.py
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from v2.model import NetworkLayer3TruncatedNormal
class Train:
def __init__(self):
self.CKPT_DIR = './ckpt9'
self.net = NetworkLayer3TruncatedNormal()
self.sess = tf.Session(config=tf.ConfigProto(
allow_soft_placement=True, log_device_placement=True))
self.sess.run(tf.global_variables_initializer())
# print("pwd:", os.getcwd())
self.data = input_data.read_data_sets('../data/', one_hot=True)
def train(self):
saver = tf.train.Saver(max_to_keep=20)
save_interval = 20000
batch_size = 64
train_step = 1100000
step = 0
# # merge所有的summary node 的op
# merged_summary_op = tf.summary.merge_all()
# # 存放在当前目录下的 log 文件夹中,获得文件句柄
# merged_writer = tf.summary.FileWriter('./log', self.sess.graph)
ckpt = tf.train.get_checkpoint_state(self.CKPT_DIR)
if ckpt and ckpt.model_checkpoint_path:
print('ckpt.model_checkpoint_path:', ckpt.model_checkpoint_path)
saver.restore(self.sess, ckpt.model_checkpoint_path)
step = self.sess.run(self.net.global_step)
print('Continue from')
print(' -> Minibatch update : ', step)
while step < train_step:
x, label = self.data.train.next_batch(batch_size)
_, loss = self.sess.run([self.net.train, self.net.loss],
feed_dict={
self.net.x: x,
self.net.label: label
})
step = self.sess.run(self.net.global_step)
# if step % 100 == 0:
# merged_writer.add_summary(merged_summary, step)
# if step % 10 == 0:
# print('step %5d loss: %.3f' % (step, loss))
if step % save_interval == 0:
saver.save(self.sess, self.CKPT_DIR + '/model', global_step=step)
print('%s/model-%d saved' % (self.CKPT_DIR, step))
# self.calculate_accuracy()
if step % 2000 == 0:
print('step %d loss: %f' % (step, loss))
if step % 20000 == 0:
self.calculate_train_error()
self.calculate_test_error()
def calculate_train_error(self):
train_x = self.data.train.images
train_label = self.data.train.labels
error_rate = self.sess.run(self.net.error_rate,
feed_dict={
self.net.x: train_x,
self.net.label: train_label
})
print(" -> Training set error_rate: %f" % error_rate)
def calculate_test_error(self):
test_x = self.data.test.images
test_label = self.data.test.labels
error_rate = self.sess.run(self.net.error_rate,
feed_dict={
self.net.x: test_x,
self.net.label: test_label
})
print(" -> Test set error_rate: %f" % error_rate)
if __name__ == "__main__":
app = Train()
app.train()
app.calculate_test_error()
|
89589ee7e254867fff95da5251bf4c4931a51674
|
[
"Python"
] | 6
|
Python
|
betasspace/MNIST
|
9d735373f6270ca0e4e75c87508e64f9122d01e2
|
79dda485254ae5fa892bb5798c5a6f74c98930a8
|
refs/heads/master
|
<repo_name>xinyang1812/show_gaze<file_sep>/check_gaze_circle.py
# -*- coding: UTF-8 -*-
import cv2
import sys
import time
import imutils
import show_gaze as vs
import matplotlib.pyplot as plt
import ellipse_util as uu
import argparse
import numpy as np
import ShapeDetector as iris
import math
def cal_gaze(ell_A, ell_B, ell_C, ell_D, ell_E, ell_F):
# print('---', ell_A * aa * aa + ell_B * aa * bb + ell_C * bb * bb + ell_D * aa + ell_E * bb + ell_F)
Z = np.array([[ell_A, ell_B / 2.0, -ell_D / (2.0)],
[ell_B / 2.0, ell_C, -ell_E / (2.0)],
[-ell_D / (2.0), -ell_E / (2.0), ell_F]])
eig_vals, eig_vecs = np.linalg.eig(Z)
# print(eig_vals, eig_vecs)
idx = eig_vals.argsort()[::-1]
eig_vals = eig_vals[idx]
eig_vecs = eig_vecs[:, idx]
# print(eig_vals, eig_vecs)
g = np.sqrt((eig_vals[1] - eig_vals[2]) / (eig_vals[0] - eig_vals[2]))
h = np.sqrt((eig_vals[0] - eig_vals[1]) / (eig_vals[0] - eig_vals[2]))
tt = np.array([h, 0, g]) * np.array([[1, 0, -1], [1, 0, 1], [-1, 0, -1], [-1, 0, 1]])
# tt = np.array([[h, 0, -g], [h, 0, g], [-h, 0, -g], [-h, 0, g]])
R = eig_vecs
# print(tt,tt.T)
normals = R.dot(tt.T)
return normals.T
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", required=True,
help="path to the input video")
args = vars(ap.parse_args())
cap = cv2.VideoCapture(args["video"])
while (True):
# Capture frame-by-frame
ret, frame = cap.read()
image = frame
# cv2.imshow('frame',frame)
# continue
resized = frame
ratio = 1
# convert the resized image to grayscale, blur it slightly,
# and threshold it
gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)
# cv2.imshow('gray',gray)
imgray = cv2.Canny(image, 600, 100, 3) # Canny边缘检测,参数可更改
# cv2.imshow("0",imgray)
imgray = imgray[480:,:]
ss = image[480:,:]
ret, thresh = cv2.threshold(imgray, 127, 255, cv2.THRESH_BINARY)
image, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE) # contours为轮廓集,可以计算轮廓的长度、面积等
circle = []
for cnt in contours:
if 100 > len(cnt) > 50:
S1 = cv2.contourArea(cnt)
ell = cv2.fitEllipse(cnt)
S2 = math.pi * ell[1][0] * ell[1][1]
if (S1 / S2) > 0.2: # 面积比例,可以更改,根据数据集。。。
ss = cv2.ellipse(ss, ell, (0, 255, 0), 2)
circle.append(cnt)
# cv2.imshow("0", ss)
normals = np.array([[0, 0, 0]])
contour = []
# loop over the contours
for c in circle:
# compute the center of the contour, then detect the name of the
# shape using only the contour
contour = c[:, 0, :]
for con in contour:
cv2.circle(resized, (con[0], (con[1] + 480)), 1, (255, 0, 255), -1)
# cv2.imshow('outline', image)
# TODO:undistort
# contour = contour - [image.shape[0] / 2, image.shape[1] / 2]
fx = 883.3836
fy = 879.1104
cx = 282.9217
cy = 495.5409
u = (contour[:,1] - cy + 480) / fy
v = (contour[:,0] - cx) / fx
ell_A, ell_B, ell_C, ell_D, ell_E, ell_F, _ = uu.Ellipse(v, u)
print(ell_A, ell_B, ell_C, ell_D, ell_E, ell_F)
# evalute ellipse fitting
xx = _[0]
yy = _[1]
zz = _[2]
plt.plot(np.array(v), np.array(u), color='pink')
plt.plot(xx, yy, color='red')
plt.plot(xx, zz, color='green')
val = cal_gaze(ell_A, ell_B, ell_C, ell_D, ell_E, ell_F)
normals = np.concatenate((normals, val))
plt.title('Ellipse fittig evaluation')
plt.ylabel('contour points in height')
plt.show()
# show gaze
vs.show_gaze(resized, normals)
print normals
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
<file_sep>/show_gaze.py
import numpy as np
import cv2
#2D image points. If you change the image, you need to change vector
image_points = np.zeros((15,2), dtype="double")
def angle(x,y):
Lx = np.sqrt(x.dot(x))
Ly = np.sqrt(y.dot(y))
cos_angle = x.dot(y) / (Lx * Ly)
# print(cos_angle)
angle_r = np.arccos(cos_angle)
angle_a = angle_r * 360 / 2 / np.pi
return angle_a
def indexofMin(arr):
minindex = 0
currentindex = 1
while currentindex < len(arr):
if arr[currentindex] < arr[minindex]:
minindex = currentindex
currentindex += 1
return minindex
# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
def show_gaze(img, normals):
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((3 * 4, 3), np.float32)
objp[:, :2] = np.mgrid[0:3, 0:4].T.reshape(-1, 2)
# Arrays to store object points and image points from all the images.
objpoints = [] # 3d point in real world space
imgpoints = [] # 2d points in image plane.
# 3D model points.
model_points = np.array([
(0.0, 0.0, 0.0),
(0.0, 25.0, 0.0),
(0.0, 50.0, 0.0),
(25.0, 0.0, 0.0),
(25.0, 25.0, 0.0),
(25.0, 50.0, 0.0),
(50.0, 0.0, 0.0),
(50.0, 25.0, 0.0),
(50.0, 50.0, 0.0),
(75.0, 0.0, 0.0),
(75.0, 25.0, 0.0),
(75.0, 50.0, 0.0)
])
# Find the chess board corners
ret, corners = cv2.findChessboardCorners(gray, (3,4),None)
print('ret', ret)
# If found, add object points, image points (after refining them)
if ret == True:
objpoints.append(objp)
corners2 = cv2.cornerSubPix(gray,corners,(11,11),(-1,-1),criteria)
imgpoints.append(corners2)
print('imgpoints', imgpoints)
# Draw and display the corners
# img = cv2.drawChessboardCorners(img, (5,3), corners2,ret)
# cv2.imshow('img',img)
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1],None,None)
print('mtx', mtx)
# img = cv2.imread('left12.jpg')
# h, w = img.shape[:2]
# mtx, roi=cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))
image_points = np.asarray(imgpoints, dtype=np.float32)[0,:,0,:]
# image_points = imgpoints
print('img points', image_points)
for p in image_points:
# print('p',p)
p1 = ( int(p[0]), int(p[1]))
cv2.circle(img, p1, 3, (255,0,0), -1)
(ret, rotation_vector, translation_vector) = cv2.solvePnP(model_points, image_points, mtx, dist, flags=cv2.SOLVEPNP_ITERATIVE)
print('ret', ret)
# (success, rotation_vector, translation_vector) = cv2.solvePnP(model_points, image_points, mtx, dist)
(gaze_point2D, jacobian) = cv2.projectPoints(model_points, rotation_vector, translation_vector, mtx, dist)
print(image_points,'===',gaze_point2D)
# exit(1)
# (start_point2D, jacobian) = cv2.projectPoints(np.array([(0.0, 0.0, 0.0)]), rotation_vector, translation_vector, mtx, dist)
# p1 = ( int(start_point2D[0][0][0]), int(start_point2D[0][0][1]))
# print('start_point2D', p1)
# Project a 3D point (0, 0, 1000.0) onto the image plane.
# We use this to draw a line sticking out of the nose
(compare1, jacobian) = cv2.projectPoints(np.array([(0.0, 25.0, 0.0)]), rotation_vector, translation_vector, mtx, dist)
(compare2, jacobian) = cv2.projectPoints(np.array([(0.0, 25.0, 100.0)]), rotation_vector, translation_vector, mtx, dist)
com1 = (int(compare1[0][0][0]), int(compare1[0][0][1]))
com2 = (int(compare2[0][0][0]), int(compare2[0][0][1]))
cv2.line(img, com1, com2, (0, 255, 0), 2)
Angle = []
nn = np.array([0.0, 0.0, 100.0])
for ii in normals:
ii = np.array(ii)
Angle.append(angle(ii, nn))
print Angle
inmin = indexofMin(Angle[1:])
inmin += 1
normals_big = normals*100
(normals_point2d, jacobian) = cv2.projectPoints(normals_big, rotation_vector, translation_vector, mtx, dist)
p0 = ( int(normals_point2d[0][0][0]), int(normals_point2d[0][0][1]))
# minangle
print('start point', p0)
color = (100,0,0)
q1 = ( int(normals_point2d[inmin][0][0]), int(normals_point2d[inmin][0][1]))
print('gaze_points2d', q1)
cv2.circle(img, q1, 3, (0,0,255), -1)
cv2.line(img, p0, q1, color, 2)
idx = 25
for p in normals_point2d:
color = (idx,0,0)
idx = idx+25
q1 = ( int(p[0][0]), int(p[0][1]))
print('gaze_points2d', q1)
cv2.circle(img, q1, 3, (0,0,255), -1)
cv2.line(img, p0, q1, color, 2)
#
# text1 = "Minimum angle: " + str(Angle[inmin])
# aa = map(int, Angle[1:])
# text2 = "all angles: " + str(aa[0:4])
# text3 = str(aa[4:])
# AddText = img.copy()
# cv2.putText(AddText, text1, (10, 50), cv2.FONT_HERSHEY_COMPLEX, 0.8, (255, 0, 0), 2)
# cv2.putText(AddText, text2, (1, 80), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 255), 2)
# cv2.putText(AddText, text3, (1, 100), cv2.FONT_HERSHEY_COMPLEX, 0.5, (0, 0, 255), 2)
cv2.imshow('img',img)
cv2.waitKey(100)
<file_sep>/ellipse_util.py
from numpy.linalg import eig, inv
import numpy as np
def fitEllipse(x, y):
x = x[:, np.newaxis]
y = y[:, np.newaxis]
x = np.array(x)
y = np.array(y)
D = np.hstack((x * x, x * y, y * y, x, y, np.ones_like(x)))
S = np.dot(D.T, D)
C = np.zeros([6, 6])
C[0, 2] = C[2, 0] = 2
C[1, 1] = -1
E, V = eig(np.dot(inv(S), C))
n = np.argmax(np.abs(E))
a = V[:, n]
return a
def ellipse_center(a):
b, c, d, f, g, a = a[1] / 2, a[2], a[3] / 2, a[4] / 2, a[5], a[0]
num = b * b - a * c
x0 = (c * d - b * f) / num
y0 = (a * f - b * d) / num
return np.array([x0, y0])
def ellipse_angle_of_rotation(a):
b, c, d, f, g, a = a[1] / 2, a[2], a[3] / 2, a[4] / 2, a[5], a[0]
return 0.5 * np.arctan(2 * b / (a - c))
def ellipse_axis_length(a):
b, c, d, f, g, a = a[1] / 2, a[2], a[3] / 2, a[4] / 2, a[5], a[0]
up = 2 * (a * f * f + c * d * d + g * b * b - 2 * b * d * f - a * c * g)
down1 = (b * b - a * c) * ((c - a) * np.sqrt(1 +
4 * b * b / ((a - c) * (a - c))) - (c + a))
down2 = (b * b - a * c) * ((a - c) * np.sqrt(1 +
4 * b * b / ((a - c) * (a - c))) - (c + a))
res1 = np.sqrt(up / down1)
res2 = np.sqrt(up / down2)
return np.array([res1, res2])
def ellipse_angle_of_rotation2(a):
b, c, d, f, g, a = a[1] / 2, a[2], a[3] / 2, a[4] / 2, a[5], a[0]
if b == 0:
if a > c:
return 0
else:
return np.pi / 2
else:
if a > c:
return np.arctan(2 * b / (a - c)) / 2
else:
return np.pi / 2 + np.arctan(2 * b / (a - c)) / 2
def Ellipse(x,y):
# TODO: check accuracy
a = fitEllipse(x,y)
center = ellipse_center(a)
phi = ellipse_angle_of_rotation2(a)
phi = ellipse_angle_of_rotation(a)
axes = ellipse_axis_length(a)
arc = 1.8
R = np.arange(0, arc * np.pi, 0.01)
a, b = axes
xx = center[0] + a * np.cos(R) * np.cos(phi) - b * np.sin(R) * np.sin(phi)
yy = center[1] + a * np.cos(R) * np.sin(phi) + b * np.sin(R) * np.cos(phi)
(ell_x0, ell_y0), (ell_w, ell_h) = (
center[0], center[1]), (axes[0], axes[1])
# get coeff -- A*x^2+B*x*y+C*y^2+D*x+E*y+F=0
# Initialise ellipse conic equation constants
ell_A = ell_w * ell_w * np.sin(phi) * np.sin(phi) + \
ell_h * ell_h * np.cos(phi) * np.cos(phi)
ell_B = 2 * (ell_h * ell_h - ell_w * ell_w) * np.sin(phi) * np.cos(phi)
ell_C = ell_w * ell_w * np.cos(phi) * np.cos(phi) + \
ell_h * ell_h * np.sin(phi) * np.sin(phi)
ell_D = -2 * ell_A * ell_x0 - ell_B * ell_y0
ell_E = -ell_B * ell_x0 - 2 * ell_C * ell_y0
ell_F = ell_A * ell_x0 * ell_x0 + ell_B * ell_x0 * ell_y0 + \
ell_C * ell_y0 * ell_y0 - ell_w * ell_w * ell_h * ell_h
zz = np.copy(yy)
for i in range(xx.shape[0]):
zz[i] = (-(ell_E + ell_B * xx[i]) + \
np.sqrt((ell_E + ell_B * xx[i]) * (ell_E + ell_B * \
xx[i]) - 4 * ell_C * (ell_A * xx[i] * xx[i] + ell_D * xx[i] + ell_F))) / (2. * ell_C)
# (aa,bb) = (xx[i],yy[i])
return ell_A, ell_B, ell_C, ell_D, ell_E, ell_F, [xx, yy, zz]
<file_sep>/check_gaze.py
import cv2
import sys
import time
import imutils
import show_gaze as vs
import matplotlib.pyplot as plt
import ellipse_util as uu
import argparse
import numpy as np
import ShapeDetector as iris
def cal_gaze(ell_A, ell_B, ell_C, ell_D, ell_E, ell_F):
# print('---', ell_A * aa * aa + ell_B * aa * bb + ell_C * bb * bb + ell_D * aa + ell_E * bb + ell_F)
Z = np.array([[ell_A, ell_B / 2.0, -ell_D / (2.0)],
[ell_B / 2.0, ell_C, -ell_E / (2.0)],
[-ell_D / (2.0), -ell_E / (2.0), ell_F]])
eig_vals, eig_vecs = np.linalg.eig(Z)
# print(eig_vals, eig_vecs)
idx = eig_vals.argsort()[::-1]
eig_vals = eig_vals[idx]
eig_vecs = eig_vecs[:, idx]
# print(eig_vals, eig_vecs)
g = np.sqrt((eig_vals[1] - eig_vals[2]) / (eig_vals[0] - eig_vals[2]))
h = np.sqrt((eig_vals[0] - eig_vals[1]) / (eig_vals[0] - eig_vals[2]))
tt = np.array([h,0,g])*np.array([[1,0,-1],[1,0,1],[-1,0,-1],[-1,0,1]])
# tt = np.array([[h, 0, -g], [h, 0, g], [-h, 0, -g], [-h, 0, g]])
R = eig_vecs
# print(tt,tt.T)
normals = R.dot(tt.T)
return normals.T
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", required=True,
help="path to the input video")
args = vars(ap.parse_args())
cap = cv2.VideoCapture(args["video"])
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
image = frame
# cv2.imshow('frame',frame)
# continue
resized = frame
ratio = 1
# convert the resized image to grayscale, blur it slightly,
# and threshold it
gray = cv2.cvtColor(resized, cv2.COLOR_BGR2GRAY)
gray[:480,:] = 180
# cv2.imshow('gray',gray)
# cv2.waitKey(0)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.adaptiveThreshold(blurred,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
cv2.THRESH_BINARY,3,5)
# # Otsu's thresholding
# ret,thresh = cv2.threshold(blurred,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# cv2.imshow("Thresh", thresh)
# cv2.waitKey(0)
thresh = 255 - thresh
# cv2.waitKey(100)
# continue
# find contours in the thresholded image and initialize the
# shape detector
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
sd = iris.ShapeDetector()
normals = np.array([[0,0,0]])
contour = []
# loop over the contours
for c in cnts:
# compute the center of the contour, then detect the name of the
# shape using only the contour
shape = sd.detect(c)
print(shape)
if shape != 'circle':
continue
print('lenm',len(c))
if len(c) < 50:
continue
contour = c[:, 0, :]
for con in contour:
cv2.circle(image, (con[0], con[1]), 1, (255, 0, 255), -1)
# cv2.imshow('outline', image)
# cv2.waitKey(0)
# TODO:undistort
# contour = contour - [image.shape[0] / 2, image.shape[1] / 2]
fx = 711.23473925
fy = 718.29852683
cx = 282.9217
cy = 495.5409
# cx = (image.shape[0] / 2)
# cy = (image.shape[1] / 2)
u = (contour[:,1] - cy) / fy
v = (contour[:,0] - cx) / fx
ell_A, ell_B, ell_C, ell_D, ell_E, ell_F, _ = uu.Ellipse(v, u)
print(ell_A, ell_B, ell_C, ell_D, ell_E, ell_F)
# evalute ellipse fitting
xx = _[0]
yy = _[1]
zz = _[2]
plt.plot(v, u, color='pink')
plt.plot(xx, yy, color='red')
plt.plot(xx, zz, color='green')
val = cal_gaze(ell_A, ell_B, ell_C, ell_D, ell_E, ell_F)
normals=np.concatenate((normals,val))
plt.title('Ellipse fittig evaluation')
plt.ylabel('contour points in height')
# plt.show()
# show gaze
vs.show_gaze(resized, normals)
print normals
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
|
a2aafb506ba956a80280c44cab2c7e56b1a10c5f
|
[
"Python"
] | 4
|
Python
|
xinyang1812/show_gaze
|
ee2137f1dfde5ec492e1e89494fe12c72532ece1
|
2d61f92381a0c786d984bc1b3b65fb19266c9c0a
|
refs/heads/master
|
<repo_name>sagarsoni7/impact-design-system<file_sep>/gulpfile.js
/**
* Gulp file to automate the various tasks
*/
const autoprefixer = require('gulp-autoprefixer');
const browserSync = require('browser-sync').create();
const cleanCss = require('gulp-clean-css');
const del = require('del');
const htmlmin = require('gulp-htmlmin');
const cssbeautify = require('gulp-cssbeautify');
const npmDist = require('gulp-npm-dist');
const gulp = require('gulp');
const sass = require('gulp-sass');
const wait = require('gulp-wait');
const sourcemaps = require('gulp-sourcemaps');
const fileinclude = require('gulp-file-include');
// Define paths
const paths = {
dist: {
base: './dist/',
front: {
base: './dist/front/',
css: './dist/front/css',
html: './dist/front/pages',
assets: './dist/front/assets',
partials: './dist/front/partials/',
scss: './dist/front/scss',
},
dashboard: {
base: './dist/dashboard/',
css: './dist/dashboard/css',
html: './dist/dashboard/pages',
assets: './dist/dashboard/assets',
partials: './dist/dashboard/partials/',
scss: './dist/dashboard/scss',
},
vendor: './dist/vendor'
},
dev: {
base: './html&css/',
front: {
base: './html&css/front/',
css: './html&css/front/css',
html: './html&css/front/pages',
assets: './html&css/front/assets',
partials: './html&css/front/partials/',
scss: './html&css/front/scss',
},
dashboard: {
base: './html&css/dashboard/',
css: './html&css/dashboard/css',
html: './html&css/dashboard/pages',
assets: './html&css/dashboard/assets',
partials: './html&css/dashboard/partials/',
scss: './html&css/dashboard/scss',
},
vendor: './html&css/vendor'
},
base: {
base: './',
node: './node_modules'
},
src: {
html: './src/*.html',
front: {
base: './src/front/',
css: './src/front/css',
html: './src/front/pages/**/*.html',
assets: './src/front/assets/**/*.*',
partials: './src/front/partials',
scss: './src/front/scss',
},
dashboard: {
base: './src/dashboard/',
css: './src/dashboard/css',
html: './src/dashboard/pages/**/*.html',
assets: './src/dashboard/assets/**/*.*',
partials: './src/dashboard/partials',
scss: './src/dashboard/scss',
},
node_modules: './node_modules/',
vendor: './vendor'
},
temp: {
base: './.temp/',
front: {
base: './.temp/front',
css: './.temp/front/css',
html: './.temp/front/pages',
assets: './.temp/front/assets',
},
dashboard: {
base: './.temp/dashboard',
css: './.temp/dashboard/css',
html: './.temp/dashboard/pages',
assets: './.temp/dashboard/assets',
},
vendor: './.temp/vendor'
}
};
// Compile SCSS
gulp.task('scss-front', function () {
return gulp.src([paths.src.front.scss + '/front/**/*.scss', paths.src.front.scss + '/front.scss'])
.pipe(wait(500))
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer({
overrideBrowserslist: ['> 1%']
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(paths.temp.front.css))
.pipe(browserSync.stream());
});
gulp.task('scss-dashboard', function () {
return gulp.src([paths.src.dashboard.scss + '/**/*.scss', paths.src.dashboard.scss + '/dashboard.scss'])
.pipe(wait(500))
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer({
overrideBrowserslist: ['> 1%']
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(paths.temp.dashboard.css))
.pipe(browserSync.stream());
});
gulp.task('scss', gulp.series('scss-front', 'scss-dashboard'));
gulp.task('html-front', function () {
return gulp.src([paths.src.front.html])
.pipe(fileinclude({
prefix: '@@',
basepath: paths.src.front.partials
}))
.pipe(gulp.dest(paths.temp.front.html))
.pipe(browserSync.stream());
});
gulp.task('html-dashboard', function () {
return gulp.src([paths.src.dashboard.html])
.pipe(fileinclude({
prefix: '@@',
basepath: paths.src.dashboard.partials
}))
.pipe(gulp.dest(paths.temp.dashboard.html))
.pipe(browserSync.stream());
});
gulp.task('html-base', function () {
return gulp.src([paths.src.html])
.pipe(fileinclude({
prefix: '@@',
basepath: paths.src.front.partials
}))
.pipe(gulp.dest(paths.temp.base))
.pipe(browserSync.stream());
});
gulp.task('html', gulp.series('html-front', 'html-dashboard', 'html-base'));
gulp.task('assets-front', function () {
return gulp.src([paths.src.front.assets])
.pipe(gulp.dest(paths.temp.front.assets))
.pipe(browserSync.stream());
});
gulp.task('assets-dashboard', function () {
return gulp.src([paths.src.dashboard.assets])
.pipe(gulp.dest(paths.temp.dashboard.assets))
.pipe(browserSync.stream());
});
gulp.task('assets', gulp.series('assets-front', 'assets-dashboard'));
gulp.task('vendor', function() {
return gulp.src(npmDist(), { base: paths.src.node_modules })
.pipe(gulp.dest(paths.temp.vendor));
});
gulp.task('serve', gulp.series('scss', 'html', 'assets', 'vendor', function() {
browserSync.init({
server: paths.temp.base
});
gulp.watch([paths.src.front.scss + '/front/**/*.scss', paths.src.front.scss + '/front.scss'], gulp.series('scss-front'));
gulp.watch([paths.src.dashboard.scss + '/**/*.scss', paths.src.dashboard.scss + '/dashboard.scss'], gulp.series('scss-dashboard'));
gulp.watch([paths.src.html], gulp.series('html-base'));
gulp.watch([paths.src.front.html, paths.src.front.base + '*.html', paths.src.front.partials + '/**/*.html'], gulp.series('html-front', 'html'));
gulp.watch([paths.src.dashboard.html, paths.src.dashboard.base + '*.html', paths.src.dashboard.partials + '/**/*.html'], gulp.series('html-dashboard', 'html'));
gulp.watch([paths.src.front.assets], gulp.series('assets-front'));
gulp.watch([paths.src.dashboard.assets], gulp.series('assets-dashboard'));
gulp.watch([paths.src.vendor], gulp.series('vendor'));
}));
// Beautify CSS
gulp.task('beautify-front:css', function () {
return gulp.src([
paths.dev.front.css + '/front.css'
])
.pipe(cssbeautify())
.pipe(gulp.dest(paths.dev.front.css))
});
gulp.task('beautify-dashboard:css', function () {
return gulp.src([
paths.dev.dashboard.css + '/dashboard.css'
])
.pipe(cssbeautify())
.pipe(gulp.dest(paths.dev.dashboard.css))
});
gulp.task('beautify:css', gulp.series('beautify-front:css', 'beautify-dashboard:css'));
// Minify CSS
gulp.task('minify-front:css', function () {
return gulp.src([
paths.dist.front.css + '/front.css'
])
.pipe(cleanCss())
.pipe(gulp.dest(paths.dist.front.css))
});
gulp.task('minify-dashboard:css', function () {
return gulp.src([
paths.dist.dashboard.css + '/dashboard.css'
])
.pipe(cleanCss())
.pipe(gulp.dest(paths.dist.dashboard.css))
});
gulp.task('minify:css', gulp.series('minify-front:css', 'minify-dashboard:css'));
// Minify Html
gulp.task('minify-front:html', function () {
return gulp.src([paths.dist.front.html + '/**/*.html'])
.pipe(htmlmin({
collapseWhitespace: true
}))
.pipe(gulp.dest(paths.dist.front.html))
});
gulp.task('minify-dashboard:html', function () {
return gulp.src([paths.dist.dashboard.html + '/**/*.html'])
.pipe(htmlmin({
collapseWhitespace: true
}))
.pipe(gulp.dest(paths.dist.dashboard.html))
});
gulp.task('minify:html', gulp.series('minify-front:html', 'minify-dashboard:html'));
// Clean
gulp.task('clean:dist', function () {
return del([paths.dist.base]);
});
gulp.task('clean:dev', function () {
return del([paths.dev.base]);
});
// Compile and copy scss/css
gulp.task('copy-front:dist:css', function () {
return gulp.src([paths.src.front.scss + '/front/**/*.scss', paths.src.front.scss + '/front.scss'])
.pipe(wait(500))
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer({
overrideBrowserslist: ['> 1%']
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(paths.dist.front.css))
});
gulp.task('copy-dashboard:dist:css', function () {
return gulp.src([paths.src.dashboard.scss + '/**/*.scss', paths.src.dashboard.scss + '/dashboard.scss'])
.pipe(wait(500))
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer({
overrideBrowserslist: ['> 1%']
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(paths.dist.dashboard.css))
});
gulp.task('copy:dist:css', gulp.series('copy-front:dist:css', 'copy-dashboard:dist:css'));
gulp.task('copy-front:dev:css', function () {
return gulp.src([paths.src.front.scss + '/front/**/*.scss', paths.src.front.scss + '/front.scss'])
.pipe(wait(500))
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer({
overrideBrowserslist: ['> 1%']
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(paths.dev.front.css))
});
gulp.task('copy-dashboard:dev:css', function () {
return gulp.src([paths.src.dashboard.scss + '/**/*.scss', paths.src.dashboard.scss + '/dashboard.scss'])
.pipe(wait(500))
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(autoprefixer({
overrideBrowserslist: ['> 1%']
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(paths.dev.dashboard.css))
});
gulp.task('copy:dev:css', gulp.series('copy-front:dev:css', 'copy-dashboard:dev:css'));
// Copy Html
gulp.task('copy-front:dist:html', function () {
return gulp.src([paths.src.front.html])
.pipe(fileinclude({
prefix: '@@',
basepath: paths.src.front.partials
}))
.pipe(gulp.dest(paths.dist.front.html))
.pipe(browserSync.stream());
});
gulp.task('copy-dashboard:dist:html', function () {
return gulp.src([paths.src.dashboard.html])
.pipe(fileinclude({
prefix: '@@',
basepath: paths.src.dashboard.partials
}))
.pipe(gulp.dest(paths.dist.dashboard.html));
});
gulp.task('copy-base:dist:html', function () {
return gulp.src([paths.src.html])
.pipe(fileinclude({
prefix: '@@',
basepath: paths.src.front.partials
}))
.pipe(gulp.dest(paths.dist.base))
.pipe(browserSync.stream());
});
gulp.task('copy:dist:html', gulp.series('copy-front:dist:html', 'copy-dashboard:dist:html', 'copy-base:dist:html'));
// Copy Html
gulp.task('copy-front:dev:html', function () {
return gulp.src([paths.src.front.html])
.pipe(fileinclude({
prefix: '@@',
basepath: paths.src.front.partials
}))
.pipe(gulp.dest(paths.dev.front.html))
.pipe(browserSync.stream());
});
gulp.task('copy-dashboard:dev:html', function () {
return gulp.src([paths.src.dashboard.html])
.pipe(fileinclude({
prefix: '@@',
basepath: paths.src.dashboard.partials
}))
.pipe(gulp.dest(paths.dev.dashboard.html));
});
gulp.task('copy-base:dev:html', function () {
return gulp.src([paths.src.html])
.pipe(fileinclude({
prefix: '@@',
basepath: paths.src.front.partials
}))
.pipe(gulp.dest(paths.dev.base))
.pipe(browserSync.stream());
});
gulp.task('copy:dev:html', gulp.series('copy-front:dev:html', 'copy-dashboard:dev:html', 'copy-base:dev:html'));
// Copy assets
gulp.task('copy-front:dist:assets', function () {
return gulp.src(paths.src.front.assets)
.pipe(gulp.dest(paths.dist.front.assets))
});
gulp.task('copy-dashboard:dist:assets', function () {
return gulp.src(paths.src.dashboard.assets)
.pipe(gulp.dest(paths.dist.dashboard.assets))
});
gulp.task('copy:dist:assets', gulp.series('copy-front:dist:assets', 'copy-dashboard:dist:assets'));
gulp.task('copy-front:dev:assets', function () {
return gulp.src(paths.src.front.assets)
.pipe(gulp.dest(paths.dev.front.assets))
});
gulp.task('copy-dashboard:dev:assets', function () {
return gulp.src(paths.src.dashboard.assets)
.pipe(gulp.dest(paths.dev.dashboard.assets))
});
gulp.task('copy:dev:assets', gulp.series('copy-front:dev:assets', 'copy-dashboard:dev:assets'));
// Copy node_modules
gulp.task('copy:dist:vendor', function() {
return gulp.src(npmDist(), { base: paths.src.node_modules })
.pipe(gulp.dest(paths.dist.vendor));
});
gulp.task('copy:dev:vendor', function() {
return gulp.src(npmDist(), { base: paths.src.node_modules })
.pipe(gulp.dest(paths.dev.vendor));
});
gulp.task('build:dev', gulp.series('clean:dev', 'copy:dev:css', 'copy:dev:html', 'copy:dev:assets', 'beautify:css', 'copy:dev:vendor'));
gulp.task('build:dist', gulp.series('clean:dist', 'copy:dist:css', 'copy:dist:html', 'copy:dist:assets', 'minify:css', 'minify:html', 'copy:dist:vendor'));
// Default
gulp.task('default', gulp.series('serve'));
|
a40da7f9223d273fa7c72c120816f568c8d20cd6
|
[
"JavaScript"
] | 1
|
JavaScript
|
sagarsoni7/impact-design-system
|
59c38d7017d003a5592450950a3a7ed8f669ddbe
|
4f9ac27b409f9e0b402e400408f21c9cffccc8bb
|
refs/heads/master
|
<file_sep>package com.pb.bulakh.hw2;
import java.util.Scanner;
public class Interval {
public static void main(String[] args) {
int input;
Scanner inp = new Scanner(System.in);
System.out.println("Введите число в промежутке от 0 до 100:");
input = inp.nextInt();
if (input >= 0 & input <= 14) {
System.out.println("Число в промежутке [0 - 14]");
} else if (input >= 15 & input <= 35) {
System.out.println("Число в промежутке [15 - 35]");
} else if (input >= 36 & input <= 50) {
System.out.println("Число в промежутке [36 - 50]");
} else if (input >= 51 & input <= 100) {
System.out.println("Число в промежутке [51 - 100]");
} else System.out.println("Введенное вами число, не находится в промежутке от 0 до 100");
}
}
<file_sep>package com.pb.bulakh.hw2;
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
int operand1;
int operand2;
String sign;
System.out.println("Пожалуйста введите первое число:");
Scanner num1 = new Scanner(System.in);
operand1 = num1.nextInt();
System.out.println("Пожалуйста введите второе число:");
Scanner num2 = new Scanner(System.in);
operand2 = num1.nextInt();
System.out.println("Пожалуйста введите знак арифметической операции:");
Scanner mark = new Scanner(System.in);
sign = mark.nextLine();
switch (sign) {
case ("+"):
System.out.println("Результат сложения чисел = " + (operand1 + operand2));
break;
case ("-"):
System.out.println("Результат вычитания чисел = " + (operand1 - operand2));
break;
case ("*"):
System.out.println("Результат умножения чисел = " + (operand1 * operand2));
break;
case ("/"):
if (operand2 == 0) {
System.out.println("ошибка! невозможно выполненить деление на 0");
// или throw new ArithmeticException("ошибка! невозможно выполненить деление на 0");
}
System.out.println("Результат деления чисел = " + (operand1 / operand2));
break;
}
}
}
|
27c3ba2620e3cc7ce572ba2698f52211ab75d7a5
|
[
"Java"
] | 2
|
Java
|
alex18031997/JavaHomeWork
|
7c84516153313e9c764ee430722c44dc3d78666e
|
4b0acbb5d7ad62c9de46edeb4b02b5cab34c425e
|
refs/heads/master
|
<repo_name>tomc944/2048-WebApp<file_sep>/js/input_manager.js
function InputManager() {
// setup game to have listeners for keypressing arrows
this.listen();
}
InputManager.prototype.listen = function() {
// need to map the arrow keys accordingly
var keys = {
37: 0, // left
38: 1, // up
39: 2, // right
40: 3 // down
}
$(document).keydown(function(e) {
switch(e.keyCode) {
// placeholders for now
// should move tiles over in the correct direction
case 37:
alert("You pressed left")
break;
case 38:
alert("You pressed up")
break;
case 39:
alert("You pressed right")
break;
case 40:
alert("You pressed down")
break;
default: return;
}
e.preventDefault();
})
}
module.exports = InputManager
<file_sep>/notes.md
### Plan of Attack
1. Create the basic html that will render instructions, score, highscore,
and the grid.
2. Put one square on the board. Allow for input and move one square around.
3. Randomly put square on board on an empty square in the grid.
4. Collapse these two tiles together to make a larger tile.
5. Updates score when two tiles collapse.
6. Alerts user when they have created a 2048 (end game or continue?)
7. Recognizes when the grid is full and the user has lost.
8. Checks to see whether score is a highscore; logs accordingly.
### Classes
- Tile
- Grid
- User input?
<file_sep>/js/bundle.js
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ exports: {},
/******/ id: moduleId,
/******/ loaded: false
/******/ };
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/ // Flag the module as loaded
/******/ module.loaded = true;
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/js/";
/******/ // Load entry module and return exports
/******/ return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {
var Game = __webpack_require__(1);
var InputManager = __webpack_require__(2);
window.addEventListener('DOMContentLoaded', function() {
new Game(4, InputManager);
})
/***/ },
/* 1 */
/***/ function(module, exports) {
function Game(size, InputManager) {
this.size = size; // Defaults to 4x4
this.inputManager = new InputManager;
this.setup();
}
Game.prototype.setup = function() {
// find all tiles that are unoccupied
// pick random empty space
// give it a 2 or 4
var $openTiles = $(".open");
var numUnoccupiedTiles = $openTiles.length;
var $randomTile = $openTiles[Math.floor(Math.random() * numUnoccupiedTiles)];
$randomTile.textContent = 2;
$randomTile.className = "grid-cell two-tile"
};
module.exports = Game;
/***/ },
/* 2 */
/***/ function(module, exports) {
function InputManager() {
// setup game to have listeners for keypressing arrows
this.listen();
}
InputManager.prototype.listen = function() {
// need to map the arrow keys accordingly
var keys = {
37: 0, // left
38: 1, // up
39: 2, // right
40: 3 // down
}
$(document).keydown(function(e) {
switch(e.keyCode) {
// placeholders for now
// should move tiles over in the correct direction
case 37:
alert("You pressed left")
break;
case 38:
alert("You pressed up")
break;
case 39:
alert("You pressed right")
break;
case 40:
alert("You pressed down")
break;
default: return;
}
e.preventDefault();
})
}
module.exports = InputManager
/***/ }
/******/ ]);<file_sep>/js/game.js
function Game(size, InputManager) {
this.size = size; // Defaults to 4x4
this.inputManager = new InputManager;
this.setup();
}
Game.prototype.setup = function() {
// find all tiles that are unoccupied
// pick random empty space
// give it a 2 or 4
var $openTiles = $(".open");
var numUnoccupiedTiles = $openTiles.length;
var $randomTile = $openTiles[Math.floor(Math.random() * numUnoccupiedTiles)];
$randomTile.textContent = 2;
$randomTile.className = "grid-cell two-tile"
};
module.exports = Game;
|
21bb11bead85174a6abc5b7ee4a8dc8412924518
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
tomc944/2048-WebApp
|
bf53d696a5623c7c4cf33eb10bac7b7727ab688d
|
a3251b02bfd7572f8038f3308c05edcb56624b24
|
refs/heads/master
|
<file_sep># Adding Scripts
Make sure to follow the guidelines in [CONTRIBUTING](../CONTRIBUTING).
<file_sep># Machine Learning Algorithms 🚀


A curated list of all (almost) machine learning and deep learning algorithms grouped by category. This repository is meant to help understand the various machine learning algorithms (Inspired by `awesome-machine-learning`). You can star this repo for future reference :)
## Contributing
Please see [CONTRIBUTING](./CONTRIBUTING.md) for more details on how to contribute.
## List of Algorithms
- Regression Algorithms
- [Linear Regression](https://towardsdatascience.com/linear-regression-using-least-squares-a4c3456e8570)
- [Logistic Regression](https://medium.com/data-science-group-iitr/logistic-regression-simplified-9b4efe801389)
- [Stepwise Regression](https://en.wikipedia.org/wiki/Stepwise_regression)
- [Multivariate Adaptive Regression Splines (MARS)](https://en.wikipedia.org/wiki/Multivariate_adaptive_regression_spline)
- [Locally Estimated Scatterplot Smoothing (LOESS)](https://towardsdatascience.com/loess-373d43b03564)
- Instance-Based Algorithms
- [k-Nearest Neighbor (kNN)](https://towardsdatascience.com/machine-learning-basics-with-the-k-nearest-neighbors-algorithm-6a6e71d01761)
- [Self-Organizing Map (SOM)](https://towardsdatascience.com/self-organizing-maps-ff5853a118d4)
- [Support Vector Machines (SVM)](https://towardsdatascience.com/support-vector-machine-simply-explained-fee28eba5496)
- Clustering Algorithms
- [k-Means](https://towardsdatascience.com/understanding-k-means-clustering-in-machine-learning-6a6e67336aa1)
- [Expectation Maximisation (EM)](https://medium.com/@chloebee/the-em-algorithm-explained-52182dbb19d9)
- [Hierarchical Clustering](https://www.kdnuggets.com/2019/09/hierarchical-clustering.html)
- Bayesian Algorithms
- [Naive Bayes](https://towardsdatascience.com/naive-bayes-explained-9d2b96f4a9c0)
- [Gaussian Naive Bayes](https://medium.com/@LSchultebraucks/gaussian-naive-bayes-19156306079b)
- [Averaged One-Dependence Estimators (AODE)](https://en.wikipedia.org/wiki/Averaged_one-dependence_estimators)
- [Bayesian Network (BN)](https://towardsdatascience.com/basics-of-bayesian-network-79435e11ae7b)
- [Bayesian Belief Network (BBN)](https://www.probabilisticworld.com/bayesian-belief-networks-part-1/)
- Decision Tree Algorithms
- [Conditional Decision Trees](https://medium.com/greyatom/decision-trees-a-simple-way-to-visualize-a-decision-dc506a403aeb)
- [Classification and Regression Tree (CART)](https://www.digitalvidya.com/blog/classification-and-regression-trees/)
- [Iterative Dichotomiser 3 (ID3)](https://towardsdatascience.com/decision-trees-introduction-id3-8447fd5213e9)
- [C4.5 and C5.0](https://towardsdatascience.com/what-is-the-c4-5-algorithm-and-how-does-it-work-2b971a9e7db0)
- Regularization Algorithms
- [Ridge Regression](https://towardsdatascience.com/ridge-regression-for-better-usage-2f19b3a202db)
- [Least Absolute Shrinkage and Selection Operator (LASSO)](https://medium.com/@alielagrebi/regularization-lasso-ridge-regression-105f426b749c)
- [Elastic Net](https://medium.com/@vijay.swamy1/lasso-versus-ridge-versus-elastic-net-1d57cfc64b58)
- [Least-Angle Regression (LARS)](https://medium.com/acing-ai/what-is-least-angle-regression-lar-bb86756f01d0)
- Association Rule Learning Algorithms
- [Apriori algorithm](https://www.digitalvidya.com/blog/apriori-algorithms-in-data-mining/)
- [Eclat algorithm](https://medium.com/machine-learning-researcher/association-rule-apriori-and-eclat-algorithm-4e963fa972a4)
- Ensemble Algorithms
- [Random Forest](https://towardsdatascience.com/an-implementation-and-explanation-of-the-random-forest-in-python-77bf308a9b76)
- [Boosting](https://medium.com/greyatom/a-quick-guide-to-boosting-in-ml-acf7c1585cb5)
- [Bootstrapped Aggregation (Bagging)](https://towardsdatascience.com/ensemble-methods-bagging-boosting-and-stacking-c9214a10a205)
- [AdaBoost](https://towardsdatascience.com/understanding-adaboost-2f94f22d5bfe)
- [Weighted Average (Blending)](https://www.analyticsvidhya.com/blog/2018/06/comprehensive-guide-for-ensemble-models/)
- [Stacked Generalization (Stacking)](https://medium.com/weightsandbiases/an-introduction-to-model-ensembling-63effc2ca4b3)
- [Gradient Boosting Machines (GBM)](https://towardsdatascience.com/understanding-gradient-boosting-machines-9be756fe76ab)
- [Gradient Boosted Regression Trees (GBRT)](https://www.youtube.com/watch?v=3CC4N4z3GJc)
- Artificial Neural Network Algorithms
- [Perceptron](https://towardsdatascience.com/what-the-hell-is-perceptron-626217814f53)
- [Multilayer Perceptrons (MLP)](https://medium.com/@AI_with_Kain/understanding-of-multilayer-perceptron-mlp-8f179c4a135f)
- [Back-Propagation](https://towardsdatascience.com/understanding-backpropagation-algorithm-7bb3aa2f95fd)
- [Stochastic Gradient Descent](https://towardsdatascience.com/stochastic-gradient-descent-clearly-explained-53d239905d31)
- [Hopfield Network](https://medium.com/@serbanliviu/hopfield-nets-and-the-brain-e5880070cdba)
- [Radial Basis Function Network (RBFN)](https://towardsdatascience.com/radial-basis-functions-neural-networks-all-we-need-to-know-9a88cc053448)
- Deep Learning Neural Network Algorithms
- [Convolutional Neural Network (CNN)](https://towardsdatascience.com/simple-introduction-to-convolutional-neural-networks-cdf8d3077bac)
- [Recurrent Neural Networks (RNNs)](https://towardsdatascience.com/learn-how-recurrent-neural-networks-work-84e975feaaf7)
- [Long Short-Term Memory Networks (LSTMs)](https://towardsdatascience.com/illustrated-guide-to-lstms-and-gru-s-a-step-by-step-explanation-44e9eb85bf21)
- [Stacked Auto-Encoders](https://medium.com/@venkatakrishna.jonnalagadda/sparse-stacked-and-variational-autoencoder-efe5bfe73b64)
- [Deep Boltzmann Machine (DBM)](https://towardsdatascience.com/restricted-boltzmann-machines-simplified-eab1e5878976)
- [Deep Belief Networks (DBN)](https://medium.com/analytics-army/deep-belief-networks-an-introduction-1d52bb867a25)
- [Generative Adversarial Networks (GANs)](https://medium.com/ai-society/gans-from-scratch-1-a-deep-introduction-with-code-in-pytorch-and-tensorflow-cb03cdcdba0f)
- Dimensionality Reduction Algorithms
- [Principal Component Analysis (PCA)](https://towardsdatascience.com/a-one-stop-shop-for-principal-component-analysis-5582fb7e0a9c)
- [Principal Component Regression (PCR)](https://en.wikipedia.org/wiki/Principal_component_regression)
- [Partial Least Squares Regression (PLSR)](https://en.wikipedia.org/wiki/Partial_least_squares_regression)
- [Linear Discriminant Analysis (LDA)](https://medium.com/@srishtisawla/linear-discriminant-analysis-d38decf48105)
- [Sammon Mapping](https://iq.opengenus.org/principle-of-sammon-mapping/)
- [Multidimensional Scaling (MDS)](https://medium.com/datadriveninvestor/the-multidimensional-scaling-mds-algorithm-for-dimensionality-reduction-9211f7fa5345)
- [Projection Pursuit](https://towardsdatascience.com/interesting-projections-where-pca-fails-fe64ddca73e6)
## Credits
- Articles from [machine learning Mastery](https://machinelearningmastery.com/). (Inspired from)
- Articles from [towardsdatascience](https://towardsdatascience.com/). (Credit goes to the respective authors)
- Articles from [medium](https://medium.com/). (Credit goes to the respective authors)
- Articles from [wikipedia](https://en.wikipedia.org/).
- Articles from [kdnuggets](https://www.kdnuggets.com/).
- Articles from [probabilisticworld](https://www.probabilisticworld.com/).
- Articles from [digitalvidya](https://www.digitalvidya.com/).
- Articles from [analyticsvidhya](https://www.analyticsvidhya.com/).
- Videos from [youtube](https://www.youtube.com/).
- Articles from [opengenus](https://iq.opengenus.org/).
<file_sep># Sample script to add in this folder<file_sep># Contribution Guidelines
If you think an algorithm is missing or placed in the wrong category and want to contribute (please do), open a pull request with the modified changes and I'll be happy to merge. You can make one of the following types of changes in each pull request:
### 1. Adding an algorithm to README:
- Please make an individual commit for each algorithm for easier maintenance.
- Keep in mind that when you are adding to the list, the link to the article should be simple enough to understand the theoretical concepts.
- Make sure a duplicate algorithm doesn't already exist under another category.
- The title of the pull request should be of the format: `Added <new-algorithm-name> to README`.
### 2. Adding your own script to `scripts` folder:
- If you have made any python program on these algorithms and want to help, please add it to the scripts folder with the file name like `<algorithm-name>.py`
- If another script for an algorithm exists, please don't add your own. Instead, see if anything would make the existing script better.
- The title of the pull request should be of the format: `Added <new-algorithm-name>.py to scripts`.
|
d39a648a715e6241253d258cdbac2f9842f8bbc3
|
[
"Markdown",
"Python"
] | 4
|
Markdown
|
sriramswar/machine-learning-algorithms
|
29e02b9ec7d61b16be6af46eba3ec02600a57e08
|
c5196fe67722822860149b1595ca037f8e6a79b9
|
refs/heads/master
|
<repo_name>Paridhi815/javaScripting<file_sep>/variable.js
let example = 'paridhi';
console.log(example);
<file_sep>/program.js
a = [1, 2, 3, 4];
b = a.filter((number) => { if (number % 2 != 0) return number; });
console.log(b);
console.log(a);
<file_sep>/number-to-string.js
let num = 128;
console.log(num.toString());
<file_sep>/functions.js
// function eat(food="orange")
// {
// return food + ' tasted really good.';
// }
// console.log(eat());
function eat(food = 'orange') {
return `${food} tasted really good.`;
}
console.log(eat());
|
19f49abf5f9af336a3270d052611beb3d576b42a
|
[
"JavaScript"
] | 4
|
JavaScript
|
Paridhi815/javaScripting
|
bfbabbacbc7d5f9c7412ce578c689c3b3eb2c196
|
2520d443e6c20c4e3cc29be1fa45fdf78f27b16c
|
refs/heads/master
|
<repo_name>n2ptune/firebase-functions-express<file_sep>/README.md
## Firebase Project
Nuxt.js와 함께 사용될 Firebase Project입니다.
---
### Note
1. Spark 요금제로는 외부 API 서버에 접근 못함
2. Express로 Backend 작성하는 것처럼 코드를 짜는 것이 가능<file_sep>/index.js
const functions = require('firebase-functions');
// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions
// exports.helloWorld = functions.https.onRequest((request, response) => {
// response.send("Hello from Firebase!");
// });
const express = require('express');
const app = express();
const dummyJson = require('./some.json');
app.get('/news', (req, res) => res.send('/news route'))
app.get('/news/:keyword', (req, res) => {
res.json(dummyJson);
})
exports.api = functions.https.onRequest(app)
|
84a3c1bd63b7e819d971b0fa322b884acd599752
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
n2ptune/firebase-functions-express
|
0fe4354e5a5b33e6fb9d871901df3eabe338bea7
|
2b8f84711177f0934028387f58d669c470dab918
|
refs/heads/master
|
<repo_name>huangynj/gem-3.3.7<file_sep>/scripts/Um_entry.ksh
#!/bin/ksh
arguments=$*
. r.entry.dot
eval `cclargs_lite $0 \
-_status "ABORT" "ABORT" "[return status ]" \
++ $arguments`
set ${SETMEX:-+ex}
cd ${TASK_WORK}
if [ -d ${TASK_INPUT}/INREP ] ; then
ls -1 ${TASK_INPUT}/INREP > liste_inputfiles_for_LAM
cat liste_inputfiles_for_LAM
fi
. r.call.dot ${TASK_BIN}/Um_cmclog.ksh -mod 1
export CMC_LOGFILE=$_CMC_LOGFILE
# Run executable (entry)
$TASK_BIN/ATM_NTR.Abs
. r.call.dot ${TASK_BIN}/Um_cmclog.ksh -mod 2 -CMC_LOGFILE $_CMC_LOGFILE
# Perform status update in output directory
cd $TASK_OUTPUT
status_file=status_ent.dot
if [ -s ${status_file} ] ; then
. ${status_file} ; /bin/rm -f ${status_file}
fi
# End of task
. r.return.dot
<file_sep>/README.md
gem-3.3.7
=========
forecast version 3.3.7
initial push
=========
added scripts
version 3.3.7.0
=========
version 3.3.7.1
=========
version 3.3.7.2
=========
version 3.3.7.3
=========
<file_sep>/scripts/Um_output_dplusp.ksh
#!/bin/ksh
#
#====> Obtaining the arguments:
eval `cclargs_lite -D $0 \
-dm "" "" "[list of dm files]"\
-dp "" "" "[list of dp files]"\
-dh "" "" "[list of dh files]"\
-pm "" "" "[list of pm files]"\
-pp "" "" "[list of pp files]"\
-ph "" "" "[list of ph files]"\
++ $*`
#
EDIT=editfst+
#
for i in ${dm} ; do
for src in `ls *dm[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*${i} 2> /dev/null` ; do
dest=`echo ${src} | sed 's/\(.*\)dm\([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]\)\(.*\)/\1m\2\3/'`
/bin/mv $src $dest 2> /dev/null
done
done
for i in ${pm} ; do
for src in `ls *pm[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*${i} 2> /dev/null` ; do
dest=`echo ${src} | sed 's/\(.*\)pm\([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]\)\(.*\)/\1m\2\3/'`
echo $EDIT -s ${src} -d ${dest} -i /dev/null
$EDIT -s ${src} -d ${dest} -i /dev/null
/bin/rm -f ${src}
done
done
for i in ${pp} ; do
for src in `ls *pp[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*${i} 2> /dev/null` ; do
dest=`echo ${src} | sed 's/\(.*\)pp\([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]\)\(.*\)/\1p\2\3/'`
echo $EDIT -s ${src} -d ${dest} -i /dev/null
$EDIT -s ${src} -d ${dest} -i /dev/null
/bin/rm -f ${src}
done
done
for i in ${ph} ; do
for src in `ls *ph[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*${i} 2> /dev/null` ; do
dest=`echo ${src} | sed 's/\(.*\)ph\([0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]\)\(.*\)/\1h\2\3/'`
echo $EDIT -s ${src} -d ${dest} -i /dev/null
$EDIT -s ${src} -d ${dest} -i /dev/null
/bin/rm -f ${src}
done
done
#
<file_sep>/scripts/Um_output.ksh
#!/bin/ksh
#
script=${0##*/}
args="$@"
arguments=$*
#====> Obtaining the arguments:
eval `cclargs_lite $0 \
-execdir "" "" "[Execution directory ]" \
-dotcfg "" "" "[Dotable config file ]" \
-cfg_file "" "" "[User config file ]" \
-job "" "" "[jobname ]" \
-listing "" "" "[listing directory ]" \
-ppid "" "" "[ppid ]" \
-endstepno "0" "0" "[Last timestep # ]" \
-mod_status "RS" "RS" "[status of Um_runmod.ksh]" \
-listm "" "" "[xfer model listings ]" \
-forceit "0" "1" "[force execution ]" \
-phyversion "" "" "[physics package version]" \
++ $arguments`
#
echo "\n=====> Um_output.ksh starts: `date` ###########\n"
Um_checkfs.ksh $execdir
if [ $? -ne 0 ] ; then exit 1 ; fi
cd $execdir
. $dotcfg
if [ ! "$UM_EXEC_xfer" ] ; then
echo "\n No file xfer requested\n"
exit 0
fi
# Set task end step number
if [ $endstepno -gt 0 ] ; then
endstep=`echo ${endstepno} | sed 's/^0*//'`
else
endstep=0
fi
repoutput=RUNMOD/output
replast=XFERMOD_upload/input/last_step_$endstep
mkdir -p ${replast}
MV=${TMPDIR}/mv$$
cat > ${MV} << EOF
f=${repoutput}/\$1
if [ ! -d \${f} ] ; then
mv \${f} $replast
else
echo \${f} is a directory
fi
EOF
chmod 755 ${MV}
echo "\nMove files from ${repoutput} in $replast"
ls ${repoutput} | xargs -l1 ${MV}
echo "##### UM_TIMING Um_output MV2LAST-: "`date`
/bin/rm -f ${MV}
# UM_EXEC_casc=0 ==> leave casc in ${repoutput} (do nothing)
# UM_EXEC_casc=1 ==> move casc in $replast for transfer
# UM_EXEC_casc=2 ==> transfer casc and leave a copy in ${repoutput}
if [ ${UM_EXEC_casc:-1} -gt 0 ] ; then
if [ `ls -L ${repoutput}/casc 2> /dev/null | wc -l` -gt 0 ] ; then
if [ ${UM_EXEC_casc:-1} -gt 1 ] ; then
echo "\nCopy directory ${repoutput}/casc from ${repoutput} in $replast"
cp -r ${repoutput}/casc $replast
else
echo "\nMove directory ${repoutput}/casc from ${repoutput} in $replast"
mv ${repoutput}/casc $replast
fi
fi
fi
nf2xfer=`find -L ${replast} -type f | wc -l`
echo "\n=====> $nf2xfer files in directory ${replast}"
echo "##### UM_TIMING Um_output -LASTFIND-: "`date`
if [ $nf2xfer -ge 1 -o $forceit -ge 1 ] ; then
# Task structure setup
rep=XFERMOD
mkdir -p ${rep}
export TASK_BASEDIR=`true_path $rep`
TASK_INPUT=${TASK_BASEDIR}/input
TASK_BIN=${TASK_BASEDIR}/bin
TASK_WORK=${TASK_BASEDIR}/work
TASK_OUTPUT=${TASK_BASEDIR}/output
if [ -n "$phyversion" ] ; then
# main_FESERI=${ARMNLIB}/modeles/PHY/v_${phyversion}/bin/${BASE_ARCH}/feseri_${BASE_ARCH}_${phyversion}.Abs
# main_FESERI=${ARMNLIB}/modeles/PHY/v_4.7.2/bin/${BASE_ARCH}/feseri_${BASE_ARCH}_4.7.2.Abs
main_FESERI=$rpnphy/v_${phyversion}/bin/${BASE_ARCH}/feseri_${BASE_ARCH}_${phyversion}.Abs
fi
main_FESERI=${main_FESERI:-ls}
# Generate configuration file on-the-fly if not provided
CFGFILE=''
if [ -n "$cfg_file" ] ; then
if [ -s $cfg_file ] ; then
echo "Using config file: $cfg_file"
CFGFILE=`true_path $cfg_file`
fi
else
PREP_cfg='# Um_output_prep.ksh '`which Um_output_prep.ksh 2>/dev/null`
XFER_cfg='# Um_output_xfer.ksh '`which Um_output_xfer.ksh 2>/dev/null`
D2Z_cfg='# Um_output_d2z.ksh '`which Um_output_d2z.ksh 2>/dev/null`
DPLUSP_cfg='# Um_output_dplusp.ksh '`which Um_output_dplusp.ksh 2>/dev/null`
MACH_cfg='# Um_output_mach.ksh '`which Um_output_mach.ksh 2>/dev/null`
RSYNC_cfg='# Um_output_rsync.ksh '`which Um_output_rsync.ksh 2>/dev/null`
SERI_cfg="# FESERI $main_FESERI"
INDATA_cfg="# last_step_${endstep} ::PWD::/last_step_::endstep::"
DOTCFG_cfg="# configexp.cfg ${dotcfg}"
CFGFILE=$TMPDIR/xfer$$.cfg
cat > $CFGFILE <<EOF
#############################################
# <input>
${INDATA_cfg}
${DOTCFG_cfg}
# </input>
# <executables>
${PREP_cfg}
${XFER_cfg}
${D2Z_cfg}
${DPLUSP_cfg}
${MACH_cfg}
${RSYNC_cfg}
${SERI_cfg}
# </executables>
# <output>
# </output>
#############################################
EOF
fi
echo "### Content of config file to TASK_SETUP ####"
cat $CFGFILE 2>/dev/null
echo "\n##### EXECUTING TASK_SETUP #####"
/bin/rm -rf ${TASK_BASEDIR}/.setup
${TASK_SETUP:-task_setup-0.7.7.py} -f $CFGFILE --base $TASK_BASEDIR
if [ $? -ne 0 ] ; then exit 1 ; fi
echo "\n#############################################\n"
/bin/rm -f $CFGFILE
cd ${TASK_WORK}
jobname=${job:-task_X}${endstep}
lajob=${jobname}_job
touch ${lajob}
lajob=`true_path ${lajob}`
cat > ${jobname} << EOF
#!/bin/sh
#
set +x
echo "##### UM_TIMING OUTPUT -BEGIN-: "\`date\`
echo "\n######################################################"
echo "########### USER'S JOB STARTS HERE - XFER ###########"
echo "########### soumet_lajob ${lajob}"
echo "######################################################\n"
#
. /users/dor/armn/mod/ovbin/sm5 -version ${MODEL_VERSION}
#
set -ex
Um_checkfs.ksh ${TASK_WORK}
cd ${TASK_WORK}
. ${TASK_INPUT}/configexp.cfg
RUNPREP=${TASK_BIN}/Um_output_prep.ksh
if [ ! -x \${RUNPREP} ] ; then
RUNPREP=""
fi
RUNXFER=${TASK_BIN}/Um_output_xfer.ksh
if [ ! -x \${RUNXFER} ] ; then
RUNXFER=""
fi
. r.call.dot \${RUNPREP:-${TASK_BIN}/Um_output_prep.ksh} \
-tskbdir ${TASK_BASEDIR} \
-d2z \${UM_EXEC_d2z:-0} -dplusp \${UM_EXEC_dplusp:-0} \
-prefix \${UM_EXEC_prefix} -listm ${listm} -endstep ${endstep}
STATUS_prep=\$_status
if [ "\$STATUS_prep" != "ABORT" ] ; then
echo ". /users/dor/armn/mod/ovbin/sm5 -version ${MODEL_VERSION} ; Um_checkfs.ksh ${TASK_WORK} ;\
if [ \$? -ne 0 ] ; then exit 1 ; fi ; cd ${TASK_WORK} ;\
\${RUNXFER:-${TASK_BIN}/Um_output_xfer.ksh} \
-s ${TRUE_HOST}:\${_rep2xfer} \
-d \${UM_EXEC_xfer}" | ssh ${TRUE_HOST} bash --login
STATUS_xfer='ABORT'
if [ -s status_xfer ] ; then
. status_xfer
STATUS_xfer=\$status_xfer
fi
echo STATUS_xfer=\$STATUS_xfer
if [ "\$STATUS_xfer" != "ABORT" ] ; then
if [ "${mod_status}" = "ED" ] ; then
tailjob=${TASK_BASEDIR}_upload/input/tailjob_X
if [ -s \${tailjob} ] ; then
echo "\n LAUNCHING "\${tailjob}"\n"
echo "soumet_lajob \${tailjob}" | ssh ${TRUE_HOST} bash --login
fi
fi
else
cat > unmail << eofmail
Problem with Um_output_xfer.ksh
YOU SHOULD TRY TO EXECUTE THE COMMAND:
$script $args -forceit
on ${TRUE_HOST}
OR DEAL OTHERWISE WITH FILES IN
${TRUE_HOST}:\${_rep2xfer}
IN ORDER TO EMPTY THIS DIRECTORY
=====> AS SOON AS POSSIBLE. <=====
eofmail
mail -s "Problem with Um_output_xfer.ksh" $USER < unmail
/bin/rm unmail
fi
else
cat > unmail << eofmail
Problem with Um_output_prep.ksh
YOU SHOULD TRY TO EXECUTE THE COMMAND:
$script $args -forceit
on ${TRUE_HOST}
OR DEAL OTHERWISE WITH FILES IN
${TRUE_HOST}:${TASK_BASEDIR}/input/last_step_${endstep}
IN ORDER TO EMPTY THIS DIRECTORY
=====> AS SOON AS POSSIBLE. <=====
eofmail
mail -s "Problem with Um_output_prep.ksh" $USER < unmail
/bin/rm unmail
fi
echo "##### UM_TIMING OUTPUT -END -: "\`date\`
EOF
chmod 755 ${jobname}
cputime=3600
cmemory=500000
listing=${listing:-${HOME}/listings}
if [ -d $listing/${BACKEND_mach} -o -L $listing/${BACKEND_mach} ] ; then
listing=$listing/${BACKEND_mach}
fi
ord_soumet ${jobname} -mach ${TRUE_HOST} -t ${cputime} -cm ${cmemory} \
-listing ${listing} -jn ${jobname} -ppid ${ppid} \
-nosubmit
/bin/mv lajob.tar ${lajob}
soumet_lajob ${lajob}
else
echo "\n No file to transfer from $replast \n"
fi
#
echo "\n=====> Um_output.ksh ends: `date` ###########\n"
<file_sep>/scripts/Um_output_prep.ksh
#!/bin/ksh
#
arguments=$*
. r.entry.dot
#====> Obtaining the arguments:
eval `cclargs_lite $0 \
-tskbdir "" "" "[task base directory ]" \
-d2z "0" "1" "[Bemol or not ]" \
-dplusp "0" "1" "[combine dynamics and physics output]" \
-endstep "0" "0" "[Last timestep # ]" \
-prefix "" "" "[Prefix for output files ]" \
-listm "" "" "[xfer model listings along ]" \
-cfg_file "" "" "[User config file ]" \
-_rep2xfer "" "" "[actual directory to transfer ]" \
-_status "ABORT" "ABORT" "[return status ]" \
++ $arguments`
echo "\n=====> Um_output_prep.ksh starts: `date` ###########\n"
# Task structure setup
TASK_BASEDIR=${tskbdir:-XFERMOD}
TASK_BASEDIR=`true_path ${TASK_BASEDIR}`
TASK_INPUT=${TASK_BASEDIR}/input/last_step_${endstep}
TASK_BIN=${TASK_BASEDIR}/bin
TASK_WORK=${TASK_BASEDIR}/work
TASK_OUTPUT=${TASK_BASEDIR}/output
ici=`pwd`
feseri=${TASK_BIN}/FESERI
output_step_rep=${TASK_OUTPUT}/last_step_${endstep}
_rep2xfer=$output_step_rep
if [ "${listm}" ] ; then
mkdir -p ${output_step_rep}
lalistetomv=`ls ${listm}* 2> /dev/null | xargs`
if [ -n "$lalistetomv" ] ; then
mv ${lalistetomv} ${output_step_rep} 2> /dev/null
fi
fi
nbfiles=`find -L ${TASK_INPUT} -type f | wc -l`
echo "##### UM_TIMING OUTPUT -PREP_1find-: "`date`
laliste="dm dp dh pm pp ph"
if [ ${nbfiles} -gt 0 ] ; then
mkdir -p ${output_step_rep}
flag_err=0
echo "D2Z starts ${nbfiles}: "`date`
d2z_error=0
for i in ${laliste} ; do
#
f2t=${i}\*
time nf2t=`find -L ${TASK_INPUT} -name "${i}[0-9]*" -type f | wc -l`
if [ ${nf2t} -gt 0 ] ; then
echo "\n Processing ${f2t} "
pivot_rept=tmp_d2z
mkdir -p ${pivot_rept}
time find -L ${TASK_INPUT} -name "${i}[0-9]*" -type f -exec mv {} ${pivot_rept} \;
echo "##### UM_TIMING OUTPUT -PREP_2find1mv $i $nf2t: "`date`
if [ ${d2z} -gt 0 ] ; then
echo "\n ${TASK_BIN}/Um_output_d2z.ksh -rep ${pivot_rept}"
time ${TASK_BIN}/Um_output_d2z.ksh -rep ${pivot_rept}
if [ $? -ne 0 ] ; then
echo "\n Error in d2z job \n"
let d2z_error=${d2z_error}+1
fi
echo "##### UM_TIMING OUTPUT -PREP_bemol: "`date`
fi
cd ${pivot_rept}
for file in * ; do
mv ${file} ${output_step_rep}/${prefix}${file}
done
cd ${ici}
rmdir ${pivot_rept}
fi
done
echo "\nD2Z ends: `date`\n"
flag_err=d2z_error
if [ ${flag_err} -eq 0 ] ; then
if [ -s ${TASK_INPUT}/time_series.bin ] ; then
cp ${TASK_INPUT}/time_series.bin .
echo "\n ${feseri} -iserial time_series.bin -omsorti time_series.fst \n"
${feseri} -iserial time_series.bin -omsorti time_series.fst 1> /dev/null
if [ $? -ne 0 ]; then
echo "\n ${feseri} aborted \n"
/bin/rm -f time_series.fst
flag_err=1
else
mv time_series.fst ${output_step_rep}
/bin/rm -f ${TASK_INPUT}/time_series.bin
fi
fi
/bin/rm -f time_series.bin
fi
if [ ${flag_err} -eq 0 ] ; then
find -L ${TASK_INPUT} -type f -name "zonaux_*" -exec mv {} $output_step_rep \;
if [ -d ${TASK_INPUT}/casc ] ; then
mv ${TASK_INPUT}/casc ${output_step_rep}
fi
find -L ${TASK_INPUT} -type f -exec mv {} $output_step_rep \;
fi
cd ${output_step_rep}
if [ ${flag_err} -eq 0 ] ; then
if [ ${dplusp} -gt 0 ] ; then
dmliste=`find ./ -name "${prefix}dm[0-9]*" | sed 's/.*_//' | xargs`
dpliste=`find ./ -name "${prefix}dp[0-9]*" | sed 's/.*_//' | xargs`
dhliste=`find ./ -name "${prefix}dh[0-9]*" | sed 's/.*_//' | xargs`
pmliste=`find ./ -name "${prefix}pm[0-9]*" | sed 's/.*_//' | xargs`
ppliste=`find ./ -name "${prefix}pp[0-9]*" | sed 's/.*_//' | xargs`
phliste=`find ./ -name "${prefix}ph[0-9]*" | sed 's/.*_//' | xargs`
echo "\nDPLUSP starts: "`date`
time ${TASK_BIN}/Um_output_dplusp.ksh -dm $dmliste -dp $dpliste -dh $dhliste -pm $pmliste -pp $ppliste -ph $phliste 1> scrap$$
/bin/rm -f scrap$$
echo "\nDPLUSP ends: "`date`
fi
echo "##### UM_TIMING OUTPUT -PREP_dplusp: "`date`
_status='OK'
nbfiles=`find -L ./ -type f | wc -l`
echo "\n FINAL # of files after Um_output_prep: ${nbfiles}\n"
else
echo "ERRORS found with d2z in ${TASK_BIN}/Um_output_d2z.ksh - ABORT"
fi
else
echo "\n No files to process from ${TASK_INPUT}\n"
_status='NOFILE'
fi
echo "\n=====> Um_output_prep.ksh ends: `date` ###########\n"
# End of task
. r.return.dot
<file_sep>/scripts/checknml
#!/bin/ksh
#
set +x
#====> Obtaining the arguments:
eval `cclargs_lite $0 \
-help "0" "1" "[help ]"\
++ $*`
#
if ((help)) then
echo file "gem_settings.nml" must be at the current directory
echo example: checknml [namelist name]
echo example: checknml gem_cfgs
elif [ $1 ] ;then
awk -v NAMELIST="$1" -f $gem/scripts/getnml $gem/scripts/dict.nml | sort > $TMPDIR/model_list
echo " " >> $TMPDIR/model_list
awk -v NAMELIST="$1" -f $gem/scripts/getnml gem_settings.nml | sort > $TMPDIR/your_list
echo " " >> $TMPDIR/your_list
if [ $HOSTTYPE = AIX ] ; then
sdiff $TMPDIR/model_list $TMPDIR/your_list
elif [ $HOSTTYPE = IRIX5 ] ; then
mgdiff $TMPDIR/model_list $TMPDIR/your_list
else
xxdiff $TMPDIR/model_list $TMPDIR/your_list
fi
rm $TMPDIR/model_list
rm $TMPDIR/your_list
else
echo file "gem_settings.nml" must be at the current directory
echo example: checknml [namelist name]
echo example: checknml gem_cfgs
fi
<file_sep>/scripts/Um_drive.ksh
#!/bin/ksh
#
arguments=$*
if ! [ -n "${MODEL}" -a -n "${MODEL_VERSION}" -a -n "${MODEL_PATH}" ] ; then
echo "\n Shadow script Um_launch could NOT establish environment"
echo " Model environment not set properly --- ABORT ---\n" ; exit 1
fi
. r.entry.dot
#====> Obtaining the arguments:
eval `cclargs_lite $0 \
-liste "0" "1" "[List available OPS configs]" \
-restart "0" "1" "[Restart mode ]" \
-_job "" "" "[OUTPUT: jobname ]" \
-_listing "" "" "[OUTPUT: listing directory ]" \
-_npex "0" "0" "[OUTPUT: # of cpus along x ]" \
-_npey "0" "0" "[OUTPUT: # of cpus along y ]" \
-_npeOMP "0" "0" "[OUTPUT: # of OpenMP cpus ]" \
++ $arguments`
# Check validity of input arguments
if [ -z "$1" -o "`echo $1 | cut -c 1`" = "-" ] ; then
echo "\nUSAGE: Um_launch DIRECTORY [OPTIONS (-help for list)]\n"; exit 1
fi
if [ ! -d $1 ] ; then
echo "\nERROR: $1 is not a directory\n"; exit 1
fi
if [ $liste -gt 0 ] ; then
echo "\n LISTE of available OPS configs:"
find ${MODEL_PATH}/run_configs -name OG*_* -exec basename {} \;
find ${MODEL_PATH}/run_configs -name OL*_* -exec basename {} \;
echo
exit 0
fi
export REPCFG=$1
export NMLFILE=${MODEL}_settings.nml
export ledotfile=${REPCFG}/configexp_drive.cfg
if [ ! -s $ledotfile ] ; then . Um_aborthere.ksh "File $ledotfile unavailable" ; fi
if [ ! -s $REPCFG/$NMLFILE ] ; then . Um_aborthere.ksh "File $REPCFG/$NMLFILE unavailable" ; fi
. $ledotfile
if [ ! $BACKEND_mach ] ; then . Um_aborthere.ksh "BACKEND_mach undefined" ; fi
if [ ! $UM_EXEC_exp ] ; then . Um_aborthere.ksh "UM_EXEC_exp undefined" ; fi
if [ -n "$BACKEND_execdir" ] ; then
export EXECDIR=${BACKEND_execdir}
else
rootdir_exec=${HOME}/MODEL_EXEC_RUN/${BACKEND_mach}
ssh $BACKEND_mach "cd ${rootdir_exec} 2> /dev/null;echo \$?" > $TMPDIR/flag$$
flagrootdir=X`cat $TMPDIR/flag$$` ; /bin/rm -f $TMPDIR/flag$$
if [ "$flagrootdir" != "X0" ] ; then
. Um_aborthere.ksh "Directory ${rootdir_exec} unavailable on $BACKEND_mach"
fi
export EXECDIR=${rootdir_exec}/${MODEL}/${UM_EXEC_exp}
fi
_listing=${BACKEND_listings:-${HOME}/listings}
if [ -d $_listing/${BACKEND_mach} -o -L $_listing/${BACKEND_mach} ] ; then
_listing=$_listing/${BACKEND_mach}
fi
export LISTING=$_listing
#
#====> Uploading stuff on ${batch_mach}
#
. r.call.dot Um_upload.ksh -restart $restart
if [ "$_status" != "OK" ] ; then . Um_aborthere.ksh "Problem with Um_upload.ksh" ; fi
PHYSICS_VERSION=`Um_fetchnml.ksh phy_pck_version $REPCFG/$NMLFILE | sed "s/RPN-CMC_//"`
#
#====> Establishing jobnames
#
PPID=$$
#
lajob=${_job:-${UM_EXEC_exp}}
jobname=${REPCFG}/${lajob}
/bin/rm -f ${jobname}_*
xfer_lis=''
if [ ${UM_EXEC_xferl:-0} -gt 0 ] ; then
xfer_lis="${LISTING}/${lajob}_*.${PPID}*"
fi
batch_class=""
batch_nosubmit=""
if [ ${BACKEND_nosubmit} -gt 0 ] ; then batch_nosubmit="-nosubmit" ; fi
if [ ${BACKEND_class} ] ; then batch_class="-cl ${BACKEND_class}" ; fi
if [ ${UM_EXEC_r_ent:-1} -gt 0 ] ; then
cat > ${jobname}_E << EOF01
set +x
echo "##### UM_TIMING BEGIN -ENTRY-: "\`date\`
echo "\n######################################################"
echo "########### USER'S JOB STARTS HERE - ENTRY ###########"
echo "######################################################\n"
#
. /users/dor/armn/mod/ovbin/sm5 -version ${MODEL_VERSION}
set -x
#
Um_checkfs.ksh $EXECDIR
if [ \$? -ne 0 ] ; then exit 1 ; fi
cd $EXECDIR
. RUNENT_upload/configexp.cfg
if [ -s RUNENT_upload/boot ] ; then
/bin/rm -rf RUNENT ; /bin/rm -f RUNENT_upload/boot
fi
export TASK_SETUP=$TASK_SETUP
export UM_EXEC_cmclog=${UM_EXEC_cmclog}
headscript=RUNENT_upload/bin/headscript
if [ -x \${headscript} ] ; then
echo "\n Running ${UM_EXEC_headscript} as "\${headscript}"\n"
\${headscript}
fi
RUNENT=RUNENT_upload/bin/Um_runent.ksh
if [ ! -x \${RUNENT} ] ; then
RUNENT=""
fi
. r.call.dot \${RUNENT:-Um_runent.ksh} -inrep ${UM_EXEC_inrep} -anal ${UM_EXEC_anal} \\
-climato ${UM_EXEC_climato} -geophy ${UM_EXEC_geophy}
if [ "\$_status" = "ED" ] ; then
tailjob=RUNENT_upload/input/tailjob_E
if [ -s \${tailjob} ] ; then
echo "\n LAUNCHING "\${tailjob}"\n"
soumet_lajob \${tailjob} ; /bin/rm -f \${tailjob}
fi
fi
#
echo "##### UM_TIMING END -ENTRY-: "\`date\`
EOF01
set -x
ord_soumet ${jobname}_E -t $BACKEND_time_ntr -cm 1G -cpus 1x1 -mach $BACKEND_mach \
-listing $_listing -jn `basename ${jobname}_E` -ppid $PPID \
-mpi ${batch_class} -nosubmit
set +x
if [ $? -eq 0 ] ; then
mv lajob.tar ${jobname}_E.tar
else
echo "\n PROBLEM with ord_soumet ${jobname}_E -- ABORT --\n"
exit 1
fi
fi
if [ `r.get_arch $BACKEND_mach` = "AIX-powerpc7" ] ; then
if [ ${BACKEND_SMT} -gt 0 ] ; then
SMT=-smt
fi
fi
if [ ${UM_EXEC_r_mod:-1} -gt 0 ] ; then
cat > ${jobname}_M << EOF02
set +x
echo "##### UM_TIMING BEGIN -MODEL-: "\`date\`
echo "\n######################################################"
echo "########### USER'S JOB STARTS HERE - MODEL ###########"
echo "######################################################\n"
#
. /users/dor/armn/mod/ovbin/sm5 -version ${MODEL_VERSION}
set -x
#
Um_checkfs.ksh $EXECDIR
if [ \$? -ne 0 ] ; then exit 1 ; fi
cd $EXECDIR
. RUNMOD_upload/configexp.cfg
if [ -s RUNMOD_upload/boot ] ; then
/bin/rm -rf RUNMOD ; /bin/rm -f RUNMOD_upload/boot
fi
get_info_nodes \$LOADL_STEP_ID
export TASK_SETUP=$TASK_SETUP
export UM_EXEC_cmclog=${UM_EXEC_cmclog}
RUNMOD=RUNMOD_upload/bin/Um_runmod.ksh
if [ ! -x \${RUNMOD} ] ; then
RUNMOD=""
fi
if [[ \$BASE_ARCH = Linux ]] ; then
. r.ssmuse.dot mpich2
fi
. r.call.dot \${RUNMOD:-Um_runmod.ksh} -lam_init \${UM_EXEC_lam_init} -lam_bcs \${UM_EXEC_lam_bcs} \\
-geophy_m \${UM_EXEC_geophy_m} -xchgdir \${UM_EXEC_xchgdir} \\
-barrier \${UM_EXEC_barrier} -timing \${UM_EXEC_timing} \\
-manoutp \${UM_EXEC_manoutp}
if [ "\$_status" != "ABORT" ] ; then
XFERSH=RUNMOD_upload/bin/Um_output.ksh
if [ ! -x \${XFERSH} ] ; then
XFERSH=""
fi
set -x
\${XFERSH:-Um_output.ksh} -execdir ${EXECDIR} -dotcfg RUNMOD_upload/configexp.cfg \
-job ${UM_EXEC_exp}_X -endstepno \$_endstep -ppid $PPID \
-phyversion ${PHYSICS_VERSION} \
-listm ${xfer_lis} -mod_status \$_status -listing $_listing
if [ "\$_status" = "ED" ] ; then
/bin/rm -rf RUNENT/output
tailjob=RUNMOD_upload/input/tailjob_M
if [ -s \${tailjob} ] ; then
echo "\n LAUNCHING "\${tailjob}"\n"
soumet_lajob \${tailjob} ; /bin/rm -f \${tailjob}
fi
fi
set +x
else
Um_aborthere.ksh "Problem with Um_runmod.ksh"
fi
#
SOUMET=ls
if [ "\$_status" = "RS" ] ; then
SOUMET=qsub
else
if [ "\$_status" = "ED" ] ; then
SOUMET=rm
fi
fi
echo "##### UM_TIMING END -MODEL-: "\`date\`
STEP_ID=\`echo \$LOADL_STEP_ID | sed 's/cmc\.ec\.gc\.ca\.//'\`
llq -l \$STEP_ID
EOF02
if [ $UM_EXEC_barrier -eq 0 ] ; then
set -x
ord_soumet ${jobname}_M \ -mach $BACKEND_mach -t $BACKEND_time_mod -cm $BACKEND_cm \
-cpus ${_cpus}x${_npeOMP} -clone -listing $_listing \
-jn `basename ${jobname}_M` -mpi -ppid $PPID ${batch_class} \
-nosubmit $SMT
set +x
if [ $? -eq 0 ] ; then
mv lajob.tar ${jobname}_M.tar
else
echo "\n PROBLEM with ord_soumet ${jobname}_M -- ABORT --\n"
exit 1
fi
fi
fi
######################################################################
if [ $UM_EXEC_barrier -gt 0 ] ; then BACKEND_nosubmit=1 ; fi
if [ $BACKEND_nosubmit -eq 0 ] ; then
if [ -s ${jobname}_E.tar ] ; then
if [ -s ${jobname}_M.tar ] ; then
scp ${jobname}_M.tar $BACKEND_mach:${EXECDIR}/RUNENT_upload/input/tailjob_E
fi
echo "\n Launching: `basename ${jobname}_E` with soumet_lajob\n"
soumet_lajob ${jobname}_E.tar
elif [ -s ${jobname}_M.tar ] ; then
echo "\n Launching: `basename ${jobname}_M` with soumet_lajob\n"
soumet_lajob ${jobname}_M.tar
else
echo "\n =====> NO JOB TO launch"
fi
else
echo "\n =====> JOB NOT launched"
fi
echo $USER ${MODEL} 'v_'${MODEL_VERSION} $BACKEND_mach `date` >> /users/dor/armn/mid/public/Um_driver.log 2> /dev/null
echo "\n Config directory: `true_path $REPCFG`\n"
_job=${jobname}
_listing=${LISTING}
#
. r.return.dot
<file_sep>/scripts/grille
#!/bin/ksh -x
#
if [ ! ${MODEL} -o ! ${MODEL_VERSION} ] ; then
echo "\n Model environment not set properly --- ABORT ---\n" ; exit 1
fi
#
eval `cclargs $0 \
-iref "0" "0" "[i index of reference point]"\
-jref "0" "0" "[j index of reference point]"\
-latr "=-100" "=-100" "[true reference latitude]"\
-lonr "=-400" "=-400" "[true reference longitude]"\
-outf "tape1" "tape1" "[Output file name]"\
-genphysx "0" "1" "[Produce geophysical fields with genphysx]"\
-xrec "0" "1" "[Visualize grid with xrec]"\
++ $*`
#
GENGRID=gemgrid_${BASE_ARCH}_${MODEL_VERSION}.Abs
export EDITFST=editfst2000
export PGSM=pgsm2000
#================== Model dependent variables ================
settingsfile="gem_settings.nml"
echo ${settingsfile}
typeline="Grd_typ_S= 'LU'"
namelistname="&grid"
if [ "x$MODEL" = "xmc2" ]
then
settingsfile="mc2_settings.nml"
typeline=" "
namelistname="&grille"
fi
#
#================== Set Grid Parameters ================
if [ ! -s $settingsfile ] ; then
cat > $settingsfile <<EOF
$namelistname
$typeline
Grd_ni = 101 , Grd_nj = 101
Grd_iref= 50 , Grd_jref= 50
Grd_latr= 46. , Grd_lonr= 91.
Grd_dx= .1,
Grd_proj_S= 'L' , Grd_phir= 22.5 , Grd_dgrw= 260.
Grd_xlat1= 0., Grd_xlon1=100.,Grd_xlat2= 0., Grd_xlon2= 190.
/
EOF
cat <<EOF
==================================================
PLEASE SET GRID PARAMETERS IN $settingsfile
and rerun script "grille" again.
==================================================
EOF
exit 0
else
cat <<EOF
============================================================
GRID PARAMETERS READ FROM $settingsfile (namelist $namelistname)
============================================================
EOF
fi
#================== Unify settings file ================
cp model_settings.cfg model_settings.cfg_bk$$ 2>/dev/null
if [ "x$MODEL" = "xmc2" ]
then
cat > dir.dir$$ <<__EOF
s/\&grille/\&grid/
s/[gG]rd_proj_S/Grd_typ_S=\"LU\",Grd_proj_S/
__EOF
cat dir.dir$$
cat $settingsfile | sed -f dir.dir$$ > model_settings.cfg
/bin/rm -f dir.dir$$
else
cat $settingsfile> model_settings.cfg
fi
#================== Produce Grid Pos Rec ================
/bin/rm -f tape1 $outf gfilemap.txt 2> /dev/null
#
$GENGRID
#
if [ X"$outf" != X"tape1" ] ; then
mv tape1 $outf
fi
/bin/rm -f model_settings.cfg
mv model_settings.cfg_bk$$ model_settings.cfg 2>/dev/null
#================== Visualise the grid ================
if [ $xrec -eq 1 -a -s $outf ] ; then
#
r.fstliste -izfst $outf -nomvar ">>" -etiket "GRDZ" | sed 's/\://g' > liste
export ip1=`cat liste | awk '{print $3}'`
export ip2=`cat liste | awk '{print $4}'`
export ip3=`cat liste | awk '{print $5}'`
/bin/rm -f liste
#
cat > p1.dir <<pgsm100
sortie (std,1000)
compac=-24
grille (tape2,$ip1,$ip2,$ip3)
*
heure(0)
outlalo(-1,-1,-1)
*
setintx(cubique)
champ('ME')
end
pgsm100
#
cp $outf tmp$$
$PGSM -iment /users/dor/armn/mid/data3/clim/glbclim -ozsrt tmp$$ -i p1.dir
/bin/rm -f p1.dir
#
xrec5 -imflds tmp$$ ; /bin/rm -f tmp$$
#
fi
#
if [ $genphysx -gt 0 ] ; then
ls -al /data/dormrb04/genphysx/bin/genphysx
/data/dormrb04/genphysx/bin/genphysx -nml ${settingsfile}
fi
<file_sep>/scripts/Um_model.ksh
#!/bin/ksh
arguments=$*
. r.entry.dot
eval `cclargs_lite $0 \
-barrier "0" "0" "[DO NOT run binary ]" \
-manoutp "1" "1" "[Manage model output ]" \
-_status "ABORT" "ABORT" "[return status ]" \
-_endstep "" "" "[last time step performed ]" \
-_npe "1" "1" "[number of subdomains ]" \
++ $arguments`
set ${SETMEX:-+ex}
cd ${TASK_WORK}
REPGEOPHY=${TASK_INPUT}/LAM_geophy
if [ -L ${REPGEOPHY} ] ; then
prefixg=$(echo $(basename `ls -L ${REPGEOPHY}/*_gfilemap.txt 2> /dev/null`) | sed 's/_gfilemap\.txt//')
echo ${prefixg##*/} > geophy_fileprefix_for_LAM
fi
# Task-specific setup
nml=model_settings.nml
npx=`${TASK_BIN}/Um_fetchnml.ksh npex $nml`
npy=`${TASK_BIN}/Um_fetchnml.ksh npey $nml`
npx=${npx:-1}
npy=${npy:-1}
let _npe=npx*npy
echo localhost $_npe
for i in `find $TASK_INPUT/ -name "BUSPER4spinphy*" 2> /dev/null` ; do
tar xvf $i
done
. r.call.dot ${TASK_BIN}/Um_cmclog.ksh -mod 1
export CMC_LOGFILE=$_CMC_LOGFILE
# Run executable (main)
echo "Running ${TASK_BIN}/ATM_MOD.Abs on $_npe ($npx x $npy) PEs:"
if [ $barrier -gt 0 ] ; then
echo GEM_Mtask 1
r.barrier
echo GEM_Mtask 2
r.barrier
echo "\n =====> Um_model.ksh CONTINUING after last r.barrier\n"
else
echo "${TASK_BIN}/r.mpirun -pgm ${TASK_BIN}/ATM_MOD.Abs -npex $npx -npey $npy"
echo OMP_NUM_THREADS=$OMP_NUM_THREADS
${TASK_BIN}/r.mpirun -pgm ${TASK_BIN}/ATM_MOD.Abs -npex $npx -npey $npy
fi
echo "##### UM_TIMING Um_model -MAINDM-: "`date`
. r.call.dot ${TASK_BIN}/Um_cmclog.ksh -mod 2 -CMC_LOGFILE $_CMC_LOGFILE
export CMC_LOGFILE=$_CMC_LOGFILE
# Status update in output directory
cd $TASK_OUTPUT
status_file=status_mod.dot
if [ -s ${status_file} ] ; then
. ${status_file} ; /bin/rm -f ${status_file}
fi
# Manage model output
if [ $manoutp -gt 0 ] ; then
cd $TASK_WORK
find ./ -type f -name "[a-zA-Z][a-zA-Z][0-9]*-[0-9]*-[0-9]*_[0-9]*" -exec mv {} $TASK_OUTPUT \;
errmv=$?
echo "##### UM_TIMING Um_model -FIRSTMV-: "`date`
cnt=`find ./000-000 -name "BUSPER4spinphy*" 2> /dev/null | wc -l`
if [ $cnt -gt 0 ] ; then
fn=`ls 000-000/BUSPER4spinphy*`
fn=`basename $fn`
tar cvf $TASK_OUTPUT/${fn}.tar [0-9]*/BUSPER4spinphy*
/bin/rm -f [0-9]*/BUSPER4spinphy*
fi
if [ $errmv -eq 0 -a "$_status" = "ED" ] ; then
find ./ -type f -name "time_series.bin" -exec mv {} $TASK_OUTPUT \;
find ./ -type f -name "zonaux_*" -exec mv {} $TASK_OUTPUT \;
for i in [0-9]* ; do
if [ -d $i ] ; then
find ./ -type f -name "*_0000.hpm*" -exec mv {} $TASK_OUTPUT \;
/bin/rm -rf $i
fi
done
if [ ! -s ${TASK_OUTPUT}/time_series.bin ] ; then
echo "${TASK_OUTPUT}/time_series.bin is empty - will be removed"
ls -l ${TASK_OUTPUT}/time_series.bin 2> /dev/null
/bin/rm -f ${TASK_OUTPUT}/time_series.bin
fi
fi
fi
# End of task
. r.return.dot
<file_sep>/scripts/Um_upload_data.ksh
#!/bin/ksh
#
arguments=$*
eval `cclargs_lite $0 \
-src "" "" "[ ]" \
-dst "" "" "[ ]" \
-fcp "0" "1" "[ ]" \
-q "0" "1" "[ ]" \
++ $arguments`
set -e
src_mach=`echo $src | awk '{print $1}'`
src_file=`echo $src | awk '{print $2}'`
dst_mach=`echo $dst | awk '{print $1}'`
dst_file=`echo $dst | awk '{print $2}'`
if [ -z "$src" -o -z "$dst_mach" -o -z "$dst_file" ] ; then
exit 0
fi
if [ -z "$src_file" ] ; then
src_file=$src_mach
src_mach=$dst_mach
fi
cnt=`echo $src_file | grep @@ | wc -l`
if [ $cnt -eq 1 ] ; then
opt=${src_file##*@@}
src_file=${src_file%%@@*}
fcp=1
fi
if [ ${src_mach} = ${dst_mach} -a $fcp -eq 0 ] ; then
if [ $q -eq 0 ] ; then
echo "ln -sf $src_file ${dst_file}/."
fi
ssh ${dst_mach} "ln -sf $src_file ${dst_file}"
else
if [ $fcp -gt 0 ] ; then
opt=-L
fi
set +e
isrep=0
ssh $src_mach "cd $src_file 2> /dev/null"
if [ $? -eq 0 ] ; then
isrep=1
fi
set -e
if [ $isrep -eq 1 ] ; then
rootdir=`dirname ${dst_file}`
dirname=`basename ${dst_file}`
echo "r.rsync -ssh $opt $src_mach:${src_file} ${rootdir};echo STATUS=\$?" | ssh ${dst_mach} bash --login > $TMPDIR/r.rsync.lis
grep "STATUS=" $TMPDIR/r.rsync.lis > $TMPDIR/r.rsync.err
. $TMPDIR/r.rsync.err ; /bin/rm -f $TMPDIR/r.rsync.lis $TMPDIR/r.rsync.err
if [ $STATUS -ne 0 ] ; then exit 1 ; fi
ssh ${dst_mach} "mv ${rootdir}/`basename ${src_file}` ${rootdir}/$dirname"
else
echo "r.rsync -ssh $opt $src_mach:${src_file} ${dst_file};echo STATUS=\$?" | ssh ${dst_mach} bash --login > $TMPDIR/r.rsync.lis
grep "STATUS=" $TMPDIR/r.rsync.lis > $TMPDIR/r.rsync.err
. $TMPDIR/r.rsync.err ; /bin/rm -f $TMPDIR/r.rsync.lis $TMPDIR/r.rsync.err
if [ $STATUS -ne 0 ] ; then exit 1 ; fi
fi
exit 0
fi
<file_sep>/scripts/findfft
#!/bin/ksh
#
set +x
#====> Obtaining the arguments:
eval `cclargs_lite $0 \
-gnimin "150" "150" "[min grid points for X (G_ni)]"\
-gnimax "250" "250" "[max grid points for X (G_ni)]"\
-cfl "0" "1" "[max cfl] "\
-help "0" "1" "[help ]"\
++ $*`
#
if ((help)) then
echo ie: findfft -gnimin $gnimin -gnimax $gnimax -pw $pw -pe $pe
echo
echo '-gnimin "150" "150" "[min grid points for X (G_ni)]"'
echo '-gnimax "250" "250" "[max grid points for X (G_ni)]"'
-cfl "0" "1" "[max cfl] "\
echo
exit
fi
if (($cfl > 0)) then
let pil=$cfl+5
else
let pil=0
fi
echo "Chosen maxcfl="$cfl," gives ====> pil="$pil
echo "G_ni numbers that would work for FFT:"
let j=${gnimin}
while [ ${j} -le ${gnimax} ] ; do
let F_nn=${j}-$pil-$pil
let F_n=$F_nn
if (($F_nn <= 8))
then let F_n=9
fi
let i=$F_n
while true
do
if (($i == 1)) then
if (($F_nn == $F_n))
then echo 'gni = ' ${j}
break
else
break
fi
fi
if (($i%2==0)) then
let i=$i/2
elif (($i%3==0)) then
let i=$i/3
elif (($i%5==0)) then
let i=$i/5
else
let F_n=$F_n+1
let i=$F_n
fi
done
let j=${j}+1
done
<file_sep>/scripts/Um_output_rsync.ksh
#!/bin/ksh
#
arguments=$*
echo "\n=====> Um_output_rsync.ksh starts: `date` ###########\n"
. r.entry.dot
#
#====> Obtaining the arguments:
eval `cclargs_lite $0 \
-reps "" "" "[remote source directory]" \
-repd "" "" "[remote destination directory]" \
-machs "" "" "[remote source system]" \
-machd "" "" "[remote destination system]" \
-attempts "${attempts:-36}" "1" "[Number of attempts to try each transfer before giving up]"\
-sleeptime "${sleeptime:-120}" "0" "[Interval in seconds between transfer attemps]"\
-_status "ABORT" "ABORT" "[return status]" \
++ $arguments`
#
if [ ! "${machs}" -o ! "${machd}" -o ! "${reps}" -o ! "${repd}" ] ; then
attempts=0
fi
#
nbfiles=`ssh ${machs} -n "cd ${reps} ; ls -l 2> /dev/null | wc -l"`
if [ $nbfiles -le 1 ] ; then
echo "\n NO FILE TO TRANFER: (Um_xfer_rsync)\n"
_status=NOFILE
. r.return.dot
exit
fi
#
echo "\n File transfer from ${machs}:${reps} to ${machd}:${repd} using rsync\n"
#
attempt=${attempts}
while [ ${attempt} -gt 0 ] ; do
#
HHi=`date`
r.rsync -ssh --copy-links ${reps} ${machd}:${repd}
flag_rcp=$?
if [ ${flag_rcp} -ne 0 ] ; then
#
attempt=$(( ${attempt} - 1 ))
#
if [ ${attempt} -gt 0 ]; then
echo " Problem with rsync from ${machs}:${reps} at `date`"
echo " Process sleeps for ${sleeptime} seconds and will retry"
sleep ${sleeptime}
else
echo " Problem with rsync from ${machs}:${reps} after ${attempts} attempts"
echo " Files will remain on ${machs}"
attempt=0
fi
#
else
#
repd=${repd}/`basename ${reps}`
echo "\nContent of destination directory ${repd} on ${machd}: \n"
ssh ${machd} -n "cd ${repd} ; ls -l"
#
size_src=`find ${reps}/ -type f -exec ls -l {} \; | awk 'BEGIN{s=0}{s = s + $5}END{printf "%.10g\n", s / 1048576.}'`
nf_src=`find ${reps}/ -type f -exec ls -l {} \; | wc -l`
size_dst=`ssh ${machd} "find ${repd}/ -type f -exec ls -l {} \;" | awk 'BEGIN{s=0}{s = s + $5}END{printf "%.10g\n", s / 1048576.}'`
nf_dst=`ssh ${machd} -n "find ${repd}/ -type f -exec ls -l {} \;" | wc -l`
fract=$(echo "scale=5 ; ($size_src-$size_dst) / $size_dst * 100" | bc -l)
if [ $fract -lt 0 ] ; then
fract=$(echo "scale=5 ; ($size_dst-$size_src) / $size_dst * 100" | bc -l)
fi
fract=$(echo "scale=5 ; $fract * 1000" | bc -l)
tolerance=1
if [ $nf_src -eq $nf_dst ] ; then
if [ $fract -le $tolerance ] ; then
echo "\n Rsync Transfer started at " $HHi
echo " Rsync Transfer ended at " `date`
_status=OK
fi
fi
attempt=0
#
fi
#
done
#
echo "\nUm_output_rsync.ksh ends: "`date`"\n"
. r.return.dot
#
<file_sep>/scripts/head_strato_OPS.ksh
#!/usr/bin/ksh -ex
#
cd RUNENT_upload/input
mv ANALYSIS ANALYSIS_orig
cat > e1.dir <<EOF
desire (-1,"TS")
zap (-1,"I7",-1,-1,1199,-1,-1)
end
EOF
cat > e2.dir <<EOF
desire (-1,"TS")
zap (-1,"I9",-1,-1,1199,-1,-1)
end
EOF
cat > e3.dir <<EOF
desire (-1,"SD")
zap (-1,-1,-1,-1,1199,-1,-1)
stdcopi(-1)
desire (-1,"SD")
zap (-1,-1,-1,-1,1198,-1,-1)
stdcopi(-1)
desire (-1,"SD")
zap (-1,-1,-1,-1,1197,-1,-1)
stdcopi(-1)
desire (-1,"SD")
zap (-1,-1,-1,-1,1196,-1,-1)
stdcopi(-1)
desire (-1,"SD")
zap (-1,-1,-1,-1,1195,-1,-1)
stdcopi(-1)
end
EOF
cp ANALYSIS_orig analysis ; chmod u+w analysis
editfst -s analysis -d analysis_i7 -i e1.dir
editfst -s analysis -d analysis_i9 -i e2.dir
editfst -s analysis -d analysis_sd -i e3.dir
editfst -s analysis_i7 analysis_i9 analysis_sd -d analysis -i /dev/null
mv analysis ANALYSIS
/bin/rm -f e1.dir e2.dir e3.dir analysis_sd analysis_i7 analysis_i9
<file_sep>/scripts/findtopo
#!/bin/ksh
#
set +x
#====> Obtaining the arguments:
eval `cclargs_lite $0 \
-gni "24" "24" "[Nb of points along any axis]"\
-min "1" "1" "[min number of PE to use]"\
-max "1" "1" "[max number of PE to use]"\
-help "0" "1" "[help ]"\
++ $*`
#
if ((help)) then
echo ie: findtopo -gni $gni -min $min -max $max
echo
echo '-gni "24" "24" "[Nb of points along any axis]"'
echo '-min "1" "1" "[min number of PE to use]"'
echo '-max "1" "1" "[max number of PE to use]"'
echo
exit
fi
let gtot=$gni
if (($min < 1))
then let min=1
fi
if (($min > $max))
then let max=$min
fi
npe=$min
echo 'findtopo -gni '$gni' -min '$min' -max '$max
while true
do
if (($npe > $max))
then exit
fi
let val1=$gtot+$npe-1
let val1=$val1/$npe
let val3=$npe-1
let val3=$val3*$val1
let val2=$gtot-$val3
if (($val2 <= 0)) then
# echo 'npe= '$npe 'is NOT ok for gni='$gtot,' val2= '$val2
echo 'npe= '$npe 'is NOT ok for gni='$gni
else
# echo 'npe= '$npe 'is OK, val2= '$val2
echo 'npe= '$npe 'is OK for gni='$gni
fi
# let val4=$npe-1
# let val4=$val4*$val1
# let val4=$val4+1
# if (($val4 > $gtot)) then
# echo 'npe= '$npe 'is NOT ok, gtot= '$gtot,' val4= '$val4,'val2=',$val2
# else
# echo 'npe= '$npe 'is OK, val4= '$val4,'val2=',$val2
# fi
let npe=$npe+1
done
<file_sep>/scripts/linkit
#!/bin/ksh
#
if [ ! "$storage_model" ] ; then
if [ -d /usr/local/env/localmrb/armn/${USER} ] ; then
storage=/usr/local/env/localmrb/armn/${USER}
else
echo "\n Must define environment variable storage_model"
echo " (to store *.o *.Abs etc... on pollux) \n"
exit
fi
else
storage=$storage_model
fi
ici=`true_path .`
cd $storage 2> /dev/null
if test $? != 0 ; then
echo "\n DIRECTORY $storage does not exist \n"
exit
fi
cd $ici
storage=${storage}/`true_path . | awk 'BEGIN{FS="/"}{print $NF}'`
#
mkdir $storage 2> /dev/null
new=`true_path $storage`
if [ "$new" = "$ici" ]; then
same=1
else
same=""
fi
#
mkdir -p $storage/malib${EC_ARCH}
if [ ! "$same" ]; then
if [ -n "$SETUP_KIND" ] ; then
/bin/rm -rf malib${BASE_ARCH} ; mkdir malib${BASE_ARCH}
ln -s $storage/malib${EC_ARCH} malib${BASE_ARCH}/
else
/bin/rm -rf malib${EC_ARCH} ; ln -sf $storage/malib${EC_ARCH} malib${EC_ARCH}
fi
fi
mainntr=main${MODEL}ntr_${BASE_ARCH}_${MODEL_VERSION}.Abs
maindm=main${MODEL}dm_${BASE_ARCH}_${MODEL_VERSION}.Abs
if [ ! "$same" ]; then
/bin/rm -f ${mainntr}; ln -sf $storage/${mainntr} ${mainntr} ; touch $storage/${mainntr}
/bin/rm -f ${maindm} ; ln -sf $storage/${maindm} ${maindm} ; touch $storage/${maindm}
fi
chmod 755 $storage/${mainntr} $storage/${maindm}
#
/bin/rm -rf RUNENT RUNMOD
mkdir -p $storage/RUNENT $storage/RUNMOD 2> /dev/null
if [ ! "$same" ]; then
ln -s $storage/RUNENT .
ln -s $storage/RUNMOD .
fi
#
<file_sep>/scripts/head_reg_OPS.ksh
#!/usr/bin/ksh -ex
#
cd RUNENT_upload/input
mv ANALYSIS ANALYSIS_orig
cat > e3.dir <<EOF
desire (-1,"SD")
zap (-1,-1,-1,-1,1199,-1,-1)
stdcopi(-1)
desire (-1,"SD")
zap (-1,-1,-1,-1,1198,-1,-1)
stdcopi(-1)
desire (-1,"SD")
zap (-1,-1,-1,-1,1197,-1,-1)
stdcopi(-1)
desire (-1,"SD")
zap (-1,-1,-1,-1,1196,-1,-1)
stdcopi(-1)
desire (-1,"SD")
zap (-1,-1,-1,-1,1195,-1,-1)
stdcopi(-1)
end
EOF
cp ANALYSIS_orig analysis ; chmod u+w analysis
editfst -s analysis -d analysis_sd -i e3.dir
editfst -s analysis_sd -d analysis -i /dev/null
mv analysis ANALYSIS
/bin/rm -f e3.dir analysis_sd
<file_sep>/scripts/Um_runmod.ksh
#!/bin/ksh
#
arguments=$*
. r.entry.dot
#
eval `cclargs_lite $0 \
-cfg_file "" "" "[user config file ]"\
-lam_init "" "" "[input data directory for LAM in self-nest)]"\
-lam_bcs "" "" "[input data directory for LAM in self-nest)]"\
-geophy_m "" "" "[input data directory for LAM in self-nest)]"\
-barrier "0" "0" "[DO NOT run binary ]"\
-manoutp "1" "1" "[Manage model output ]"\
-theoc "${theoc:-0}" "1" "[theoretical case flag ]"\
-xchgdir "" "" "[exchange directory ]"\
-timing "0" "0" "[report performance timers ]"\
-task_basedir "RUNMOD" "RUNMOD" "[name of task dir ]"\
-no_setup "0" "1" "[do not run setup ]"\
-_status "ABORT" "ABORT" "[return status ]"\
-_endstep "" "" "[last time step performed ]"\
-_npe "1" "1" "[number of subdomains ]"\
++ $arguments`
echo "\n=====> Um_runmod.ksh starts: `date` ###########\n"
set ${SETMEX:-+ex}
# Task structure setup
mkdir -p ${task_basedir}
export TASK_BASEDIR=`true_path $task_basedir`
export TASK_INPUT=${TASK_BASEDIR}/input
export TASK_BIN=${TASK_BASEDIR}/bin
export TASK_WORK=${TASK_BASEDIR}/work
export TASK_OUTPUT=${TASK_BASEDIR}/output
export RPN_COMM_DIAG=0
export fn_const=constantes
export fn_ozone=ozone_clim.fst
export fn_irtab=rad_table.fst
# Generate configuration file on-the-fly if not provided
CFGFILE=''
if [ $cfg_file ] ; then
if [ -s $cfg_file ] ; then
echo "Using config file: $cfg_file"
CFGFILE=`true_path $cfg_file`
fi
else
#===> input
INIT_SFC_cfg="#"
INIT_3D_cfg="#"
BCDS_3D_cfg="#"
XCHGDIR_cfg="#"
GEOPHY_cfg="#"
OUTCFG_cfg="#"
NMLCPL_cfg="#"
if [ -d ${TASK_BASEDIR}/../RUNENT/output/INIT_SFC ] ; then
INIT_SFC_cfg='# INIT_SFC ::TASK_BASEDIR::/../RUNENT/output/INIT_SFC'
fi
if [ -n "${lam_init}" ] ; then
INIT_3D_cfg="# INIT_3D ${lam_init}"
else
if [ -d ${TASK_BASEDIR}/../RUNENT/output/INIT_3D ] ; then
INIT_3D_cfg='# INIT_3D ::TASK_BASEDIR::/../RUNENT/output/INIT_3D'
fi
fi
if [ -n "${lam_bcs}" ] ; then
BCDS_3D_cfg="# BCDS_3D ${lam_bcs}"
else
if [ -d ${TASK_BASEDIR}/../RUNENT/output/BCDS_3D ] ; then
BCDS_3D_cfg='# BCDS_3D ::TASK_BASEDIR::/../RUNENT/output/BCDS_3D '
fi
fi
if [ -n "${geophy_m}" ] ; then
GEOPHY_cfg="# LAM_geophy ${geophy_m}"
fi
# Exchange directory requested
if [ -n "${xchgdir}" ] ; then
XCHGDIR_cfg="# xchgdir ${xchgdir}"
fi
if [ -s ${TASK_BASEDIR}_upload/input/coupleur_settings.nml -o -e coupleur_settings.nml ] ; then
NMLCPL_cfg="# coupleur_settings.nml ::PWD::/coupleur_settings.nml"
fi
if [ -s ${TASK_BASEDIR}_upload/input/output_settings -o -s outcfg.out ] ; then
OUTCFG_cfg="# output_settings ::PWD::/outcfg.out"
fi
CONSTANTES_cfg="# $fn_const ::AFSISIO::/datafiles/constants/thermoconsts"
if [ -s ${TASK_BASEDIR}_upload/input/$fn_const -o -s $fn_const ] ; then
CONSTANTES_cfg="# $fn_const ::PWD::/::fn_const::"
fi
OZONE_cfg="# $fn_ozone"
if [ -s ${TASK_BASEDIR}_upload/input/$fn_ozone -o -s $fn_ozone ] ; then
OZONE_cfg="# $fn_ozone ::PWD::/$fn_ozone"
fi
IRTAB_cfg="# $fn_irtab ::AFSISIO::/datafiles/constants/irtab5_std"
if [ -s ${TASK_BASEDIR}_upload/input/$fn_irtab -o -s $fn_irtab ] ; then
IRTAB_cfg="# $fn_irtab ::PWD::/$fn_irtab"
fi
#===> executables
FETCHNML_cfg='# Um_fetchnml.ksh '`which Um_fetchnml.ksh`
CMCLOG_cfg='# Um_cmclog.ksh '`which Um_cmclog.ksh`
UM_MOD_cfg='# Um_model.ksh '`which Um_model.ksh`
MPIRUN_cfg='# r.mpirun '`which r.mpirun2`
#
CFGFILE=$TMPDIR/mod$$.cfg
cat > $CFGFILE <<EOF
#############################################
# <input>
${INIT_SFC_cfg}
${INIT_3D_cfg}
${BCDS_3D_cfg}
${GEOPHY_cfg}
# model_settings_template ::PWD::/::MODEL::_settings.nml
${CONSTANTES_cfg}
${OZONE_cfg}
${IRTAB_cfg}
${OUTCFG_cfg}
${NMLCPL_cfg}
# </input>
# <executables>
# ATM_MOD.Abs ::PWD::/main::MODEL::dm_::BASE_ARCH::_::MODEL_VERSION::.Abs
${FETCHNML_cfg}
${CMCLOG_cfg}
${UM_MOD_cfg}
${MPIRUN_cfg}
# </executables>
# <output>
${XCHGDIR_cfg}
# </output>
#############################################
EOF
fi
echo "### Content of config file to TASK_SETUP ####"
cat $CFGFILE 2>/dev/null
echo "\n##### DOTING file $CFGFILE #####"
. $CFGFILE
echo "\n#############################################"
# Use performance timers on request
if [ ${timing} -gt 0 ] ; then export TMG_ON=YES; fi
export OMP_NUM_THREADS=${OMP_NUM_THREADS:-1}
# Set up working directory if running the first time slice
if [ -s ${TASK_WORK}/000-000/restart ] ; then
echo "Running in RESTART mode"
else
if [ ${no_setup} = 0 ] ; then
echo "\n##### EXECUTING TASK_SETUP #####"
/bin/rm -rf ${TASK_BASEDIR}/.resetenv ${TASK_WORK}/.resetenv
${TASK_SETUP:-task_setup-0.7.7.py} -f $CFGFILE --base $TASK_BASEDIR --clean
if [ $? = 1 ] ; then . Um_aborthere.ksh "PROBLEM with task_setup.py" ; fi
fi
fi
/bin/rm -f ${TASK_WORK}/theoc
if [ ${theoc} -gt 0 ] ; then
touch ${TASK_WORK}/theoc
fi
cp ${TASK_INPUT}/model_settings_template ${TASK_WORK}/model_settings.nml
# Run main program wrapper
. r.call.dot ${TASK_BIN}/Um_model.ksh -barrier ${barrier} -manoutp ${manoutp}
# Config file cleanup
/bin/rm -f $TMPDIR/mod$$.cfg
echo "\n=====> Um_runmod.ksh ends: `date` ###########\n"
# End of task
. r.return.dot
<file_sep>/scripts/Um_upload.ksh
#!/bin/ksh
#
. r.entry.dot
echo "************** Um_upload *******************"
#====> Obtaining the arguments:
eval `cclargs_lite $0 \
-restart "0" "0" "[Restart mode ]" \
-_npex "0" "0" "[# of cpus along x ]" \
-_npey "0" "0" "[# of cpus along y ]" \
-_npeOMP "0" "0" "[# of cpus for OpenMP]" \
-_cpus "0" "0" "[Total # of cpus ]" \
-_status "ABORT" "" "[return status ]" \
++ $*`
set -e
cfgfile=$ledotfile
. $cfgfile
if [ -z "$BACKEND_mach" -o -z "$EXECDIR" ] ; then
. Um_aborthere.ksh "Undefined variable (BACKEND_mach or EXECDIR)"
fi
if [ -z "${UM_EXEC_ozone}" ] ; then
. Um_aborthere.ksh "Undefined variable (UM_EXEC_ozone)"
fi
TARGET_BASE_ARCH=`r.get_arch $BACKEND_mach`
ici=${PWD}
#
#====> Launching message
#
echo "\n#############################################################"
echo " LAUNCHING ${MODEL} MODEL v_${MODEL_VERSION} on $BACKEND_mach:$EXECDIR type=$TARGET_BASE_ARCH"
echo "############################################################# \n"
TARGET_DIR_E=${EXECDIR}/RUNENT_upload
TARGET_DIR_M=${EXECDIR}/RUNMOD_upload
TARGET_DIR_X=${EXECDIR}/XFERMOD_upload
ssh ${BACKEND_mach} "/bin/rm -rf ${TARGET_DIR_E}/* ${TARGET_DIR_M}/* ${TARGET_DIR_X}/* ;\
mkdir -p ${TARGET_DIR_E}/bin ${TARGET_DIR_M}/bin ${TARGET_DIR_X}/bin \
${TARGET_DIR_E}/input ${TARGET_DIR_M}/input ${TARGET_DIR_X}/input"
MODELVERSION=$UM_EXEC_binops
if [ -z "$MODELVERSION" ] ; then
MODELVERSION=${MODEL_VERSION}
fi
main_ntr=main${MODEL}ntr_${TARGET_BASE_ARCH}_${MODELVERSION}.Abs
main_dm=main${MODEL}dm_${TARGET_BASE_ARCH}_${MODELVERSION}.Abs
if [ ${UM_EXEC_ovbin} ] ; then
cnt=`echo ${UM_EXEC_ovbin} | grep @@ | wc -l`
if [ $cnt -eq 1 ] ; then
opt=${UM_EXEC_ovbin##*@@}
main_ntr=${main_ntr}@@${opt}
main_dm=${main_dm}@@${opt}
UM_EXEC_ovbin=${UM_EXEC_ovbin%%@@*}
fi
echo "\n Copying ${UM_EXEC_ovbin}/*${TARGET_BASE_ARCH}*.Abs"
Um_upload_data.ksh -src ${UM_EXEC_ovbin}/${main_ntr} -dst ${BACKEND_mach}:${TARGET_DIR_E}/bin/ATM_NTR.Abs
Um_upload_data.ksh -src ${UM_EXEC_ovbin}/${main_dm} -dst ${BACKEND_mach}:${TARGET_DIR_M}/bin/ATM_MOD.Abs
else
echo "\n UM_EXEC_ovbin NOT defined -- ABORT --\n"
exit
fi
for i in `ls -1 ${REPCFG}/*.ksh 2> /dev/null` ; do
Um_upload_data.ksh -src ${TRUE_HOST}:$i -dst ${BACKEND_mach}:${TARGET_DIR_E}/bin -fcp
Um_upload_data.ksh -src ${TRUE_HOST}:$i -dst ${BACKEND_mach}:${TARGET_DIR_M}/bin -fcp
Um_upload_data.ksh -src ${TRUE_HOST}:$i -dst ${BACKEND_mach}:${TARGET_DIR_X}/bin -fcp
done
if [ ${UM_EXEC_ovdata} ] ; then
echo "\n Copying ${UM_EXEC_ovdata}"
cd ${UM_EXEC_ovdata}
scp -q constantes ozoclim* irtab5_* ${BACKEND_mach}:${EXECDIR}/data
cd $ici
fi
if [ ${UM_EXEC_headscript} ] ; then
echo "\n Copying ${UM_EXEC_headscript}"
Um_upload_data.ksh -src ${UM_EXEC_headscript} -dst ${BACKEND_mach}:${TARGET_DIR_E}/bin/headscript -fcp
fi
if [ -n "${UM_EXEC_tailjob_M}" ] ; then
echo "\n Copying ${UM_EXEC_tailjob_M}"
Um_upload_data.ksh -src ${UM_EXEC_tailjob_M} -dst ${BACKEND_mach}:${TARGET_DIR_M}/input/tailjob_M -fcp
fi
if [ -n "${UM_EXEC_tailjob_X}" ] ; then
echo "\n Copying ${UM_EXEC_tailjob_X}"
Um_upload_data.ksh -src ${UM_EXEC_tailjob_X} -dst ${BACKEND_mach}:${TARGET_DIR_X}/input/tailjob_X -fcp
fi
if [ -n "$UM_EXEC_lam_init" -a "$UM_EXEC_lam_init" == "$UM_EXEC_lam_bcs" ] ; then
UM_EXEC_lam_bcs=${BACKEND_mach}:${TARGET_DIR_M}/input/INIT_3D
fi
Um_upload_data.ksh -src ${UM_EXEC_anal} -dst ${BACKEND_mach}:${TARGET_DIR_E}/input/ANALYSIS
Um_upload_data.ksh -src ${UM_EXEC_inrep} -dst ${BACKEND_mach}:${TARGET_DIR_E}/input/INREP
Um_upload_data.ksh -src ${UM_EXEC_climato} -dst ${BACKEND_mach}:${TARGET_DIR_E}/input/CLIMATO
Um_upload_data.ksh -src ${UM_EXEC_geophy} -dst ${BACKEND_mach}:${TARGET_DIR_E}/input/GEOPHY
Um_upload_data.ksh -src ${UM_EXEC_constantes} -dst ${BACKEND_mach}:${TARGET_DIR_E}/input/constantes
Um_upload_data.ksh -src ${UM_EXEC_lam_init} -dst ${BACKEND_mach}:${TARGET_DIR_M}/input/INIT_3D
Um_upload_data.ksh -src ${UM_EXEC_lam_bcs} -dst ${BACKEND_mach}:${TARGET_DIR_M}/input/BCDS_3D
Um_upload_data.ksh -src ${UM_EXEC_geophy_m} -dst ${BACKEND_mach}:${TARGET_DIR_M}/input/LAM_geophy
Um_upload_data.ksh -src ${UM_EXEC_constantes} -dst ${BACKEND_mach}:${TARGET_DIR_M}/input/constantes
Um_upload_data.ksh -src ${UM_EXEC_ozone} -dst ${BACKEND_mach}:${TARGET_DIR_M}/input/ozone_clim.fst
Um_upload_data.ksh -src ${UM_EXEC_irtab} -dst ${BACKEND_mach}:${TARGET_DIR_M}/input/rad_table.fst
Um_upload_data.ksh -src ${UM_EXEC_nmlcpl} -dst ${BACKEND_mach}:${TARGET_DIR_M}/input/coupleur_settings.nml
if [ ${restart} -eq 0 ]; then
boot=${TMPDIR}/boot
echo " " > ${boot}
fi
scp -q $REPCFG/$NMLFILE ${BACKEND_mach}:${TARGET_DIR_E}/input/model_settings_template
scp -q $REPCFG/$NMLFILE ${BACKEND_mach}:${TARGET_DIR_M}/input/model_settings_template
scp -q $cfgfile ${BACKEND_mach}:${TARGET_DIR_E}/configexp.cfg
scp -q $cfgfile ${BACKEND_mach}:${TARGET_DIR_M}/configexp.cfg
set +e
scp -q $REPCFG/outcfg.out ${BACKEND_mach}:${TARGET_DIR_M}/input/output_settings 2> /dev/null
scp -q ${boot} ${BACKEND_mach}:${TARGET_DIR_E} 2> /dev/null
scp -q ${boot} ${BACKEND_mach}:${TARGET_DIR_M} 2> /dev/null
/bin/rm -f ${boot}
ssh ${BACKEND_mach} "cd ${TARGET_DIR_E}/bin ; set -x ;for i in \`ls -1\` ; do if [ ! -L \$i ] ; then chmod 755 \$i; fi; done"
ssh ${BACKEND_mach} "cd ${TARGET_DIR_M}/bin ; set -x ;for i in \`ls -1\` ; do if [ ! -L \$i ] ; then chmod 755 \$i; fi; done"
set -e
echo "\n ----- Updated content of ${EXECDIR}/*_upload directories on ${BACKEND_mach} -----"
ssh ${BACKEND_mach} "cd ${TARGET_DIR_E} ; pwd ; ls -l * ;\
cd ${TARGET_DIR_M} ; pwd ; ls -l * ;\
cd ${TARGET_DIR_X} ; pwd ; ls -l *"
echo " -----------------------------------------------------"
_npex=`Um_fetchnml.ksh npex $REPCFG/$NMLFILE`
_npey=`Um_fetchnml.ksh npey $REPCFG/$NMLFILE`
_npex=${_npex:-1}
_npey=${_npey:-1}
_npeOMP=${BACKEND_OMP:-1}
let _cpus=_npex*_npey
_status=OK
echo "************** Um_upload DONE *******************"
. r.return.dot
<file_sep>/scripts/Um_lance
#!/bin/ksh
#
if [ ! ${MODEL} -o ! ${MODEL_VERSION} ] ;then
echo "\n Model environment not set properly --- ABORT ---\n" ; exit 1
fi
arguments=$*
#
ici=${PWD} ; REPCFG=${PWD}
if [ $1 ] ; then
cd $1 2> /dev/null
if [ $? -eq 0 ] ; then
REPCFG=${PWD}
else
echo "\n Directory $1 is unavailable --- ABORT ---\n"
exit
fi
cd ${ici}
fi
ledotfile=${REPCFG}/configexp.dot.cfg
if [ -f ${ledotfile} ] ; then
. ${ledotfile}
fi
ledotfile=${REPCFG}/configexp_drive.cfg
#
. r.entry.dot
#
eval `cclargs_lite -D " " $0 \
\
-BACKEND_mach "${BACKEND_mach}" "" "[Backend machine name ]" \
-BACKEND_time_ntr "${BACKEND_time_ntr:-600}" "600" "[Job resources: gemntr wallclock time]" \
-BACKEND_time_mod "${BACKEND_time_mod:-3600}" "3600" "[Job resources: gemdm wallclock time]" \
-BACKEND_cm "${BACKEND_cm:-10G}" "10G" "[Job resources: gemdm memory size ]" \
-BACKEND_OMP "${BACKEND_OMP:-1}" "1" "[Job resources: gemdm OMP_NUM_THREADS]" \
-BACKEND_SMT "${BACKEND_SMT:-1}" "1" "[Job resources: gemdm use smt feature]" \
-BACKEND_execdir "${BACKEND_execdir}" "" "[Working directory ]" \
-BACKEND_listings "${BACKEND_listings:-${HOME}/listings}" "" "[Directory for job listings ]" \
-BACKEND_class "${BACKEND_class}" "" "[to control -cl option with soumet ]" \
-BACKEND_nosubmit "${BACKEND_nosubmit:-0}" "1" "[to issu -nosubmit option with soumet]" \
\
-UM_EXEC_exp "${UM_EXEC_exp:-dbg1}" "dbg1" "[Current experiment name ]" \
-UM_EXEC_anal "${UM_EXEC_anal}" "" "[Full path of the analysis ]" \
-UM_EXEC_inrep "${UM_EXEC_inrep}" "" "[Full path of INIT & BCS for LAM ]" \
-UM_EXEC_lam_init "${UM_EXEC_lam_init}" "" "[Full path of INIT data for LAM_casc ]" \
-UM_EXEC_lam_bcs "${UM_EXEC_lam_bcs}" "" "[Full path of BCS data for LAM_casc ]" \
-UM_EXEC_ovbin "${UM_EXEC_ovbin}" "" "[Full path of main model executables ]" \
-UM_EXEC_binops "${UM_EXEC_binops}" "" "[Name of specific operational application ]" \
-UM_EXEC_climato "${UM_EXEC_climato}" "" "[Full path of climatology file ]" \
-UM_EXEC_geophy "${UM_EXEC_geophy}" "" "[Full path of geophysical file ]" \
-UM_EXEC_geophy_m "${UM_EXEC_geophy_m}" "" "[Full path of geophysical files for LAM_casc]" \
-UM_EXEC_ozone "${UM_EXEC_ozone}" "" "[Full path of climatology ozone file ]" \
-UM_EXEC_irtab "${UM_EXEC_irtab}" "" "[Full path of radiation table file ]" \
-UM_EXEC_constantes "${UM_EXEC_constantes}" "" "[Full path of geophysical constantes file ]" \
-UM_EXEC_r_ent "${UM_EXEC_r_ent:-1}" "0" "[To run GEMNTR ]" \
-UM_EXEC_r_mod "${UM_EXEC_r_mod:-1}" "0" "[To run GEMDM ]" \
-UM_EXEC_d2z "${UM_EXEC_d2z:-0}" "1" "[To re-assemble output files ]" \
-UM_EXEC_xfer "${UM_EXEC_xfer}" "" "[WS:full-path-dir on which to scp results ]" \
-UM_EXEC_xferl "${UM_EXEC_xferl:-0}" "1" "[Transfer listings along with model output ]" \
-UM_EXEC_casc "${UM_EXEC_casc:-1}" "0" "[Transfer sub-dir casc for LAM_casc ]" \
-UM_EXEC_prefix "${UM_EXEC_prefix}" "" "[Prefix for output filenames ]" \
-UM_EXEC_dplusp "${UM_EXEC_dplusp:-0}" "1" "[To assemble dynamics and physics output ]" \
-UM_EXEC_headscript "${UM_EXEC_headscript}" "" "[Script to execute before GEMNTR ]" \
-UM_EXEC_tailjob_M "${UM_EXEC_tailjob_M}" "" "[Job to launch after Um_runmod.ksh ]" \
-UM_EXEC_tailjob_X "${UM_EXEC_tailjob_X}" "" "[Job to launch after Um_output_xfer.ksh ]" \
-UM_EXEC_xchgdir "${UM_EXEC_xchgdir}" "" "[Exchange directory for coupling ]" \
-UM_EXEC_cmclog "${UM_EXEC_cmclog}" "" "[Full path for CMC log file ]" \
-UM_EXEC_barrier "${UM_EXEC_barrier:-0}" "1" "[Third party job (SM) will run the model ]" \
-UM_EXEC_manoutp "${UM_EXEC_manoutp:-1}" "1" "[Model output management by Um_runmod ]" \
-UM_EXEC_nmlcpl "${UM_EXEC_nmlcpl}" "" "[Shared namcouple file btw cpl components ]" \
-UM_EXEC_timing "${UM_EXEC_timing}" "" "[AIX HPM timing info ]" \
\
-liste "0" "1" "[List available OPS configs]" \
-restart "0" "1" "[Restart mode ]" \
-_job "" "" "[OUTPUT: jobname ]" \
-_listing "" "" "[OUTPUT: listing directory ]" \
-_npex "0" "0" "[OUTPUT: # of cpus along x ]" \
-_npey "0" "0" "[OUTPUT: # of cpus along y ]" \
-_npeOMP "0" "0" "[OUTPUT: # of OpenMP cpus ]" \
++ $arguments`
#
cat > ${ledotfile} <<EOF
BACKEND_mach=$BACKEND_mach
BACKEND_time_ntr=$BACKEND_time_ntr
BACKEND_time_mod=$BACKEND_time_mod
BACKEND_cm=$BACKEND_cm
BACKEND_OMP=$BACKEND_OMP
BACKEND_SMT=$BACKEND_SMT
BACKEND_execdir=$BACKEND_execdir
BACKEND_listings=$BACKEND_listings
BACKEND_class=$BACKEND_class
BACKEND_nosubmit=$BACKEND_nosubmit
UM_EXEC_exp=$UM_EXEC_exp
UM_EXEC_anal=$UM_EXEC_anal
UM_EXEC_inrep=$UM_EXEC_inrep
UM_EXEC_ovbin=$UM_EXEC_ovbin
UM_EXEC_binops=$UM_EXEC_binops
UM_EXEC_headscript=$UM_EXEC_headscript
UM_EXEC_climato=$UM_EXEC_climato
UM_EXEC_geophy=$UM_EXEC_geophy
UM_EXEC_d2z=$UM_EXEC_d2z
UM_EXEC_xfer=$UM_EXEC_xfer
UM_EXEC_xferl=$UM_EXEC_xferl
UM_EXEC_casc=$UM_EXEC_casc
UM_EXEC_prefix=$UM_EXEC_prefix
UM_EXEC_dplusp=$UM_EXEC_dplusp
UM_EXEC_tailjob_M=$UM_EXEC_tailjob_M
UM_EXEC_tailjob_X=$UM_EXEC_tailjob_X
UM_EXEC_xchgdir=$UM_EXEC_xchgdir
UM_EXEC_r_ent=$UM_EXEC_r_ent
UM_EXEC_r_mod=$UM_EXEC_r_mod
UM_EXEC_lam_init=$UM_EXEC_lam_init
UM_EXEC_lam_bcs=$UM_EXEC_lam_bcs
UM_EXEC_geophy_m=$UM_EXEC_geophy_m
UM_EXEC_ozone=$UM_EXEC_ozone
UM_EXEC_irtab=$UM_EXEC_irtab
UM_EXEC_constantes=$UM_EXEC_constantes
UM_EXEC_cmclog=$UM_EXEC_cmclog
UM_EXEC_barrier=$UM_EXEC_barrier
UM_EXEC_manoutp=$UM_EXEC_manoutp
UM_EXEC_nmlcpl=$UM_EXEC_nmlcpl
UM_EXEC_timing=$UM_EXEC_timing
EOF
. r.call.dot Um_drive.ksh $REPCFG -liste $liste -restart $restart -job ${_job}
. r.return.dot
<file_sep>/scripts/Um_output_xfer.ksh
#!/bin/ksh
#
arguments=$*
echo "\n=====> Um_output_xfer.ksh starts: `date` ###########\n"
#====> Obtaining the arguments:
eval `cclargs_lite $0 \
-s "" "" "[source ]" \
-d "" "" "[destination]" \
++ $arguments`
#
d=`echo $d | sed 's/:/ /g'`
#
export src_mach=${s%% *}
src_rept=${s##* }
export dest_mach=${d%% *}
dest_rept=${d##* }
#
REP=XFERMOD_upload
RUNMACH=${REP}/bin/Um_output_mach.ksh
if [ ! -x "${RUNPREP}" ] ; then
RUNMACH=""
fi
RUNSYNC=${REP}/bin/Um_output_rsync.ksh
if [ ! -x ${RUNSYNC} ] ; then
RUNSYNC=""
fi
. r.call.dot ${RUNMACH:-Um_output_mach.ksh} -attempts 2
if [ "$_status" = "ABORT" ] ; then
echo "\n ----------- ABORT ---------\n" ; exit 5
fi
nbfiles=`ssh ${src_mach} -n ls -x ${src_rept} | wc -w`
_status=ABORT
/bin/rm -f status_xfer
if [ ${nbfiles} -eq 0 ] ; then
#
echo "\n No file to transfer from ${src_mach}:${src_rept}\n"
_status='NOFILE'
#
else
#
_status=ABORT
CHECKFS=`which Um_checkfs.ksh`
CHECKFS=`true_path $CHECKFS`
flag1=`ssh ${dest_mach} -n "mkdir -p ${dest_rept} ; cd $dest_rept 2> /dev/null; echo \$?"`
flag2=`ssh ${dest_mach} -n "$CHECKFS ${dest_rept} 1> /dev/null 2> /dev/null ; echo \$?"`
if [ $flag1 -eq 0 -a $flag2 -eq 0 ] ; then
repxfer=${src_rept}_$$
/bin/mv ${src_rept} ${repxfer}
. r.call.dot ${RUNSYNC:-Um_output_rsync.ksh} -machs ${src_mach} -reps ${repxfer} \
-machd ${dest_mach} -repd ${dest_rept} -attempts 2
/bin/mv ${repxfer} ${src_rept}
else
_status='ABORT'
fi
if [ "$_status" = "OK" ] ; then
echo " Rsync Transfer succeeded at" `date`
echo "\n All pending transfers succeeded"
echo "\n Removing ${src_rept} on ${src_mach} ...."
ssh ${src_mach} -n /bin/rm -rf ${src_rept}
echo "\n Moving data from ${dest_rept} on ${dest_mach} ....\n"
echo ". /users/dor/armn/mod/ovbin/sm5 -version ${MODEL_VERSION} ; Um_output_lastmv.ksh ${dest_rept} `basename $repxfer` " | ssh $dest_mach bash --login
echo "\n Moving data DONE...\n"
fi
fi
#
echo "status_xfer=$_status" > status_xfer
#
echo "\nUm_output_xfer.ksh ends: "`date`"\n"
<file_sep>/scripts/Um_runent.ksh
#!/bin/ksh
arguments=$*
. r.entry.dot
DIR=$MODEL_PATH/dfiles/${BASE_ARCH}/bcmk
inrep=$DIR
anal=$DIR/20010920.120000
climato=$DIR/clim_gef_400_mars96
geophy=$DIR/geophy_400.fst_0000001-0000001
eval `cclargs_lite -D " " $0 \
-inrep "$inrep" "" "[input directory ]" \
-anal "$anal" "" "[analysis ]" \
-climato "$climato" "" "[climatology file]" \
-geophy "$geophy" "" "[genphysX file ]" \
-cfg_file "" "" "[user config file]" \
-task_basedir "RUNENT" "RUNENT" "[name of task dir]" \
-no_setup "0" "1" "[do not run setup]" \
-_status "ABORT" "ABORT" "[return status ]" \
++ $arguments`
echo "\n=====> Um_runent.ksh starts: `date` ###########\n"
set ${SETMEX:-+ex}
# Task structure setup
if [ ${no_setup} = 0 ] ; then
rm -fr ${task_basedir:-yenapas}/*
fi
mkdir -p ${task_basedir}
TASK_BASEDIR=`true_path $task_basedir`
export TASK_BASEDIR
#
export TASK_INPUT=${TASK_BASEDIR}/input
export TASK_BIN=${TASK_BASEDIR}/bin
export TASK_WORK=${TASK_BASEDIR}/work
export TASK_OUTPUT=${TASK_BASEDIR}/output
export fn_const=constantes
# Generate configuration file on-the-fly if not provided
CFGFILE=''
if [ -n "$cfg_file" ] ; then
if [ -s $cfg_file ] ; then
echo "Using config file: $cfg_file"
CFGFILE=`true_path $cfg_file`
fi
else
#===> input
ANALYSIS_cfg='#'
INREP_cfg='#'
CLIMATO_cfg='#'
GEOPHY_cfg='#'
if [ -n "${anal}" ] ; then
ANALYSIS_cfg="# ANALYSIS ${anal}"
fi
if [ -n "${inrep}" ] ; then
INREP_cfg="# INREP ${inrep}"
fi
if [ -n "${climato}" ] ; then
CLIMATO_cfg="# CLIMATO ${climato}"
fi
if [ -n "${geophy}" ] ; then
GEOPHY_cfg="# GEOPHY ${geophy}"
fi
CONSTANTES_cfg="# $fn_const ::AFSISIO::/datafiles/constants/thermoconsts"
if [ -s $fn_const ] ; then
CONSTANTES_cfg="# $fn_const ::PWD::/::fn_const::"
fi
#===> executables
FETCHNML_cfg='# Um_fetchnml.ksh '`which Um_fetchnml.ksh 2> /dev/null`
CMCLOG_cfg='# Um_cmclog.ksh '`which Um_cmclog.ksh 2> /dev/null`
UM_NTR_cfg='# Um_entry.ksh '`which Um_entry.ksh 2> /dev/null`
#
CFGFILE=$TMPDIR/ntr$$.cfg
cat > $CFGFILE <<EOF
#############################################
# <input>
${ANALYSIS_cfg}
${INREP_cfg}
${CLIMATO_cfg}
${GEOPHY_cfg}
# model_settings_template ::PWD::/::MODEL::_settings.nml
${CONSTANTES_cfg}
# </input>
# <executables>
# ATM_NTR.Abs ::PWD::/main::MODEL::ntr_::BASE_ARCH::_::MODEL_VERSION::.Abs
${FETCHNML_cfg}
${CMCLOG_cfg}
${UM_NTR_cfg}
# </executables>
# <output>
# </output>
#############################################
EOF
fi
echo "### Content of config file to TASK_SETUP ####"
cat $CFGFILE 2>/dev/null
echo "\n##### DOTING file $CFGFILE #####"
. $CFGFILE
echo "\n#############################################"
# Set up working directory
if [ ${no_setup} = 0 ] ; then
echo "\n##### EXECUTING TASK_SETUP #####"
/bin/rm -rf ${TASK_BASEDIR}/.resetenv ${TASK_WORK}/.resetenv ${TASK_BASEDIR}/.setup
${TASK_SETUP:-task_setup-0.7.7.py} -f $CFGFILE --base $TASK_BASEDIR --clean
if [ $? = 1 ] ; then . Um_aborthere.ksh "PROBLEM with task_setup.py" ; fi
fi
cp ${TASK_INPUT}/model_settings_template ${TASK_WORK}/model_settings.nml
# Run main program wrapper
. r.call.dot ${TASK_BIN}/Um_entry.ksh
# Config file cleanup
/bin/rm -f $TMPDIR/ntr$$.cfg
echo "\n=====> Um_runent.ksh ends: `date` ###########\n"
# End of task
. r.return.dot
|
84fb273be370639ac53a3309d9ee2dba405e6a0a
|
[
"Markdown",
"Shell"
] | 21
|
Shell
|
huangynj/gem-3.3.7
|
d7d9693957d65f31a9ace255e1012521748585ab
|
8e1eecb4c4ddfe506c00f8ef019123b31c4f8d52
|
refs/heads/master
|
<file_sep>package dam.m06.jokes_and_riddles_mysql;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
/**
* @encrypt █║▌│ █│║▌ ║││█║▌ │║║█║
* @author Author : Regør [★]
* @who Who in Black Byte
* @program Program Jokes & Riddles - SQLiteV.1
*/
public class JRDataBase extends AssetDatabaseOpenHelper {
private static final String DATABASE_NAME = "JRDataBase";
public JRDataBase(Context context) {
super(context, DATABASE_NAME);
}
/** INSERT JOKE & RIDDLE CATEGORY **/
public long insertCategory(String nom, String description) {
SQLiteDatabase db = this.openDatabase();
ContentValues cv = new ContentValues();
cv.put("name", nom);
cv.put("description", description);
db.insert("JOKES_CATEGORY", null, cv);
return db.insert("RIDDLE_CATEGORY", null, cv);
}
public long insertCategory(String nom, String description,String tableName) {
SQLiteDatabase db = this.openDatabase();
ContentValues cv = new ContentValues();
cv.put("name", nom);
cv.put("description", description);
return db.insert(tableName, null, cv);
}
/** INSERT JOKES **/
public long insertJoke(String statment, int category_id, int language_id) {
SQLiteDatabase db = this.openDatabase();
ContentValues cv = new ContentValues();
cv.put("statment", statment);
cv.put("category_id", category_id);
cv.put("language_id", language_id);
return db.insert("JOKES", null, cv);
}
/** INSERT RIDDLE **/
public long insertRiddle(String question, String answer, int category_id,
int language_id) {
SQLiteDatabase db = this.openDatabase();
ContentValues cv = new ContentValues();
cv.put("question", question);
cv.put("answer", answer);
cv.put("category_id", category_id);
cv.put("language_id", language_id);
return db.insert("RIDDLE", null, cv);
}
/** UPDATE RIDDLE **/
public boolean updateRiddle(long id, String question, String answer,
String created, int category_id, int language_id) {
SQLiteDatabase db = this.openDatabase();
ContentValues cv = new ContentValues();
cv.put("question", question);
cv.put("answer", answer);
cv.put("created", created);
cv.put("category_id", category_id);
cv.put("language_id", language_id);
return db.update("RIDDLE", cv, "_id=" + id, null) > 0;
}
public boolean updateRiddle(long id, String question, String answer, int category_id, int language_id) {
SQLiteDatabase db = this.openDatabase();
ContentValues cv = new ContentValues();
cv.put("question", question);
cv.put("answer", answer);
cv.put("category_id", category_id);
cv.put("language_id", language_id);
return db.update("RIDDLE", cv, "_id=" + id, null) > 0;
}
/** UPDATE JOKES **/
public boolean updateJoke(long id, String statment, String created,
int category_id, int language_id) {
SQLiteDatabase db = this.openDatabase();
ContentValues cv = new ContentValues();
cv.put("statment", statment);
cv.put("created", created);
cv.put("category_id", category_id);
cv.put("language_id", language_id);
return db.update("JOKES", cv, "_id=" + id, null) > 0;
}
public boolean updateJoke(long id, String statment,
int category_id, int language_id) {
SQLiteDatabase db = this.openDatabase();
ContentValues cv = new ContentValues();
cv.put("statment", statment);
cv.put("category_id", category_id);
cv.put("language_id", language_id);
return db.update("JOKES", cv, "_id=" + id, null) > 0;
}
/** SELECTS **/
public Cursor getJokesOrRiddlesByCategory(int idCategory, String tableName) {
return getCursorFrom(tableName + " WHERE category_id = '" + idCategory
+ "'");
}
public Cursor getCursorFrom(String tableName) {
SQLiteDatabase db = this.openDatabase();
String sql = "SELECT * FROM " + tableName;
Cursor c = db.rawQuery(sql, null);
c.moveToFirst();
return c;
}
public Cursor getCursorFromDate(String tableName) {
SQLiteDatabase db = this.openDatabase();
String sql = "SELECT DISTINCT strftime('%Y-%m-%d',created) AS _id FROM "
+ tableName;
Cursor c = db.rawQuery(sql, null);
c.moveToFirst();
return c;
}
public boolean deleteFrom(String tableName, int id){
SQLiteDatabase db = this.openDatabase();
return db.delete(tableName, "_id = " + id, null) > 0;
}
}
|
7fe481e480cb7761483ab76a178a00cf496d5410
|
[
"Java"
] | 1
|
Java
|
regorDam/Jokes_and_Riddles
|
929c09758dd42e948d425832261a23664e3d9e0b
|
1411096d4c6c18fff99e29a379d6efb5f94bf411
|
refs/heads/master
|
<file_sep># python
Utility focused python scripts for common tasks
#### img_resize
*Resizes images to desired height in px, output to a new directory:*
```img_resize [input directory] [max height]```
#### zippex
*Extracts all zip archives in current directory to new directory "unzips":*
```zippex```
<file_sep>#!/usr/bin/env python
from PIL import Image
import os
import sys
"""Resizes images to desired height in px, output to new directory [input]-[image height]
takes 2 arguments - input directory and image height """
#prevent max image size issues
Image.MAX_IMAGE_PIXELS = None
inDir, maxHeight = sys.argv[1], int(sys.argv[2])
#paths
cwd = os.getcwd()
outDir = inDir + '-' + str(maxHeight)
inDir = os.path.join(cwd, inDir)
files = os.listdir(inDir)
os.mkdir(os.path.join(cwd, outDir))
outDir = os.path.join(cwd, outDir)
print('\nOutput Directory is: ' + outDir +'\n')
i = 1
for file in files:
imgPath = os.path.join(inDir, file)
if os.path.isfile(imgPath):
im = Image.open(imgPath)
else:
print(' Not an image, skipping...')
continue
#resize
ratio = (maxHeight/im.size[1])
width = int((ratio * im.size[0]))
im = im.resize((width, maxHeight), Image.ANTIALIAS)
#export
imgName = (file[:-4] + '-' + str(maxHeight) + file[-4:])
imgOut = os.path.join(outDir, imgName)
im.save(imgOut)
print(' ' + imgName)
i += 1
print('\n{0} images total'.format(i))
print('resize complete')<file_sep>#!/usr/bin/env python
import zipfile
import os
cwd = os.getcwd()
unzips = os.path.join(cwd, "unzips")
for zips in os.listdir(cwd):
try:
with zipfile.ZipFile(zips, "r") as zipref:
zipref.extractall(unzips)
except:
break
|
6774744e0b810c20615b269e5fa8042f7bec838a
|
[
"Markdown",
"Python"
] | 3
|
Markdown
|
mxwllndrsn/python
|
e628975143cd7bc0ac816dd3c5b5b0b97305cae7
|
34abd3176e7039336ce35a4c8a07c4831a81f5b9
|
refs/heads/main
|
<repo_name>NishithPaul/missingImputation<file_sep>/rmiMAE.R
###############################################################################
### Robust Missing imputation by minimizing two way mean absolute error ###
### (RMIMAE) Function ###
###############################################################################
rmiMAE<- function (x,contRate=99){
origdat<-x
RegCoef <- function(x, a) {
keep <- (a != 0) & (!is.na(x))
a <- a[keep]
return(matrixStats::weightedMedian(x[keep]/a, abs(a), na.rm = TRUE, interpolate = FALSE))
}
absReg <- function(x, a, b) {
x <- as.vector(x)
ab <- as.vector(outer(a, b))
keep <- (ab != 0) & (!is.na(x))
ab <- ab[keep]
return(matrixStats::weightedMedian(x[keep]/ab, abs(ab), na.rm = TRUE, interpolate = FALSE))
}
metU <- matrix(NA, nrow = nrow(x), ncol = ncol(x))
samV <- matrix(NA, nrow = ncol(x), ncol = ncol(x))
vard <- rep(NA, ncol(x))
for (k in 1:ncol(x)) {
ak <- apply(abs(x), 1, median, na.rm = TRUE)
converged <- FALSE
repe<-0
while (!converged) {
akprev <- ak
c <- apply(x, 2, RegCoef, ak)
bk <- c/sqrt(sum(c^2))
d <- apply(x, 1, RegCoef, bk)
ak <- d/sqrt(sum(d^2))
if (k!=1){
rk<-ak
coef.proj <- c(crossprod(rk,metU[,1:(k-1)]))/diag(crossprod(metU[,1:(k-1)]))
ak <- rk - matrix(metU[,1:(k-1)],nrow=nrow(x))%*%matrix(coef.proj,nrow=(k-1))
#ak<-ak/sqrt(sum(ak^2))
ck<-bk
coef.proj <- c(crossprod(ck,samV[,1:(k-1)]))/diag(crossprod(samV[,1:(k-1)]))
bk<- ck - matrix(samV[,1:(k-1)],nrow=ncol(x))%*%matrix(coef.proj,nrow=(k-1))
#bk<-bk/sqrt(sum(bk^2))
}
repe<-repe+1
if (sum((ak - akprev)^2) < 0.05)
converged <- TRUE
else if (repe > 4)
converged <- TRUE
}
eigenk <- absReg(x, ak, bk)
x <- x - eigenk * ak %*% t(bk)
metU[, k] <- ak
samV[, k] <- bk
vard[k] <- eigenk
}
vard[is.na(vard)]<-0
metU[is.na(metU)]<-0
samV[is.na(samV)]<-0
sm<-0
tsum<-sum(vard*vard)
expVar<-NULL
ik<-0
targetVar<-FALSE
while(!targetVar){
ik=ik+1
sm=sm+vard[ik]*vard[ik]
expVar[ik]=(sm/tsum)*100
if (expVar[ik]>= contRate){
targetVar <- TRUE
}
}
if(ik<2){
approX<-(vard[1:ik]*metU[,1:ik])%*%t(samV[,1:ik])
}
if(ik>1){
approX<-metU[,1:ik]%*%diag(vard[1:ik])%*%t(samV[,1:ik])
}
q1<-NULL
q3<-NULL
iqR<-NULL
for (k in 1:nrow(origdat)){
q1[k]<-quantile(origdat[k,],na.rm=TRUE)[2][[1]]
q3[k]<-quantile(origdat[k,],na.rm=TRUE)[4][[1]]
iqR[k]<-quantile(origdat[k,],na.rm=TRUE)[4][[1]]-quantile(origdat[k,],na.rm=TRUE)[2][[1]]
}
recmat<-origdat
# rmed<-rowMedians(origdat,na.rm=TRUE)
# rvar<-RowVar(origdat)
for (i in 1:nrow(x)){
for (j in 1:ncol(x)) {if (is.na(recmat[i,j])|| recmat[i,j]> (q3[i]+iqR[i])|| recmat[i,j]< (q1[i]-iqR[i])) recmat[i,j]<-approX[i,j]
}
}
imputeDat<-list()
imputeDat$x<-recmat
imputeDat$u<-metU
imputeDat$v<-samV
imputeDat$d<-vard
return(imputeDat)
}
###############################################################
### THE END ###
###############################################################
|
744852fd8a37b38cc734354ba81cb8583af5ddff
|
[
"R"
] | 1
|
R
|
NishithPaul/missingImputation
|
2ab6388ce187d0184cbcf1911c34239f8b32b344
|
b8f0bd161bcf077034ab1afc2180cb751b518b9b
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.